query
stringlengths
7
3.85k
document
stringlengths
11
430k
metadata
dict
negatives
sequencelengths
0
101
negative_scores
sequencelengths
0
101
document_score
stringlengths
3
10
document_rank
stringclasses
102 values
function specf() is a wrapper for function spec() that constructs the string using the specified printfstyle format strings + arguments.
func (c *ReturnCode) specf(format string, v ...interface{}) *ReturnCode { s := fmt.Sprintf(format, v...) return c.spec(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func specString(spec sequence) string {\n\ts := make([]string, len(spec))\n\tfor i, v := range spec {\n switch v.value.(type) {\n case stringer:\n s[i] = v.value.(stringer).String()\n\t\tdefault:\n\t\t\ts[i] = fmt.Sprintf(\"%#v\", v.value)\n }\n\t}\n\treturn strings.Join(s, \" \")\n}", "func (c *ReturnCode) kspecf(kind ReturnCodeKind, format string, v ...interface{}) *ReturnCode {\n\tc.kind = kind\n\treturn c.specf(format, v...)\n}", "func PPf(format string, a ...interface{}) (int, error) {\n\treturn pp.Printf(format, a...)\n}", "func Printf(format string, v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprintf(format, v...)\n\tstd.Report(s)\n\tlog.Print(s)\n}", "func Printf(format string, a ...interface{}) {\n\tfmt.Fprintf(Noticer, format, a...)\n}", "func Printf(z []byte, params ...interface{}) string {\n\tp := newParametizer(z)\n\tdefer p.reset()\n\n\t// make sure we always have 9 parameters -- makes it easier\n\t// later to skip checks and its faster\n\tfor i := 0; i < len(p.params) && i < len(params); i++ {\n\t\tp.params[i] = params[i]\n\t}\n\n\treturn p.exec()\n}", "func Tracef(format string, v ...interface{}) { std.lprintf(TRACE, format, v...) }", "func Fprintf(buf *TrackedBuffer, format string, values ...interface{}) {\n\tend := len(format)\n\tfieldnum := 0\n\tfor i := 0; i < end; {\n\t\tlasti := i\n\t\tfor i < end && format[i] != '%' {\n\t\t\ti++\n\t\t}\n\t\tif i > lasti {\n\t\t\tbuf.WriteString(format[lasti:i])\n\t\t}\n\t\tif i >= end {\n\t\t\tbreak\n\t\t}\n\t\ti++ // '%'\n\t\tswitch format[i] {\n\t\tcase 's':\n\t\t\tnodeValue := values[fieldnum].([]byte)\n\t\t\tbuf.Write(nodeValue)\n\t\tcase 'v':\n\t\t\tnode := values[fieldnum].(*Node)\n\t\t\tnode.Format(buf)\n\t\tdefault:\n\t\t\tpanic(\"unexpected\")\n\t\t}\n\t\tfieldnum++\n\t\ti++\n\t}\n}", "func Sprintf(format string, a ...interface{}) string { return fmt.Sprintf(format, a...) }", "func Fprintf(w io.Writer, format string, args ...interface{}) (n int, err error) {\n\tn, err = w.Write([]byte(Sprintf(format, args...)))\n\treturn\n}", "func Printf(buf []byte, fmt string, a ...interface{}) (n int, err error) {\n\treturn Fprintf(os.Stdout, buf, fmt, a...)\n}", "func Printf(format string, a ...interface{}) {\n\tPrint(\n\t\tfmt.Sprintf(\n\t\t\tformat, a...,\n\t\t),\n\t)\n}", "func Printf(format string, v ...interface{}) {\n Std.Output(LevelInfo, CallDepth, fmt.Sprintf(format, v...))\n}", "func Fprintf(w io.Writer, s string, tabulated string, cellPrinters ...func(string, int)) {\n\tWriter = w\n\tStyle = s\n\tPrint(tabulated, cellPrinters...)\n}", "func Printf(format string, a ...interface{}) (n int, err error) { return fmt.Printf(format, a...) }", "func Printf(format string, v ...interface{}) { std.lprintf(INFO, format, v...) }", "func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {\n\treturn fmt.Fprintf(w, format, a...)\n}", "func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {\n\treturn fmt.Fprintf(w, format, a...)\n}", "func TestFormatterPrintln(t *testing.T) {\n\tf := F(1)\n\texpect := \"<v=F(1)>\\n\"\n\ts := Sprint(f, \"\\n\")\n\tif s != expect {\n\t\tt.Errorf(\"Sprint wrong with Formatter: expected %q got %q\", expect, s)\n\t}\n\ts = Sprintln(f)\n\tif s != expect {\n\t\tt.Errorf(\"Sprintln wrong with Formatter: expected %q got %q\", expect, s)\n\t}\n\ts = Sprintf(\"%v\\n\", f)\n\tif s != expect {\n\t\tt.Errorf(\"Sprintf wrong with Formatter: expected %q got %q\", expect, s)\n\t}\n}", "func (printer Printer) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {\n\tif printer.DryRun {\n\t\treturn 0, nil\n\t}\n\treturn fmt.Fprintf(w, format, a...)\n}", "func Fprintf(w io.Writer, buf []byte, fmt string, a ...interface{}) (n int, err error) {\n\tvar d dumper\n\td.input = buf\n\td.doDump(fmt, a)\n\tn, err = w.Write(d.buf.Bytes())\n\treturn\n}", "func TestPrettyPrint(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\tfakeSFDP []byte\n\t\tparamLookup []ParamLookupEntry\n\t\tprettyPrint string\n\t}{\n\t\t{\n\t\t\tname: \"MX66L51235F\",\n\t\t\tfakeSFDP: spimock.FakeSFDP,\n\t\t\tparamLookup: BasicTableLookup,\n\t\t\tprettyPrint: fakeSFDPPrettyPrint,\n\t\t},\n\t\t{\n\t\t\tname: \"error prints\",\n\t\t\tfakeSFDP: spimock.FakeSFDP,\n\t\t\tparamLookup: errorLookupParams,\n\t\t\tprettyPrint: errorPrettyPrint,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := bytes.NewReader(tt.fakeSFDP)\n\t\t\tsfdp, err := Read(r)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tw := &bytes.Buffer{}\n\t\t\tif err := sfdp.PrettyPrint(w, tt.paramLookup); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif w.String() != tt.prettyPrint {\n\t\t\t\tt.Errorf(\"sfdp.PrettyPrint() =\\n%s\\n;want\\n%s\", w.String(), tt.prettyPrint)\n\t\t\t}\n\t\t})\n\t}\n}", "func Infof(template string, args ...interface{}) {\n\tInfo(fmt.Sprintf(template, args...))\n}", "func renderPerfect(format, file string) {\n\tswitch format {\n\tcase FORMAT_TINY:\n\t\tfmtc.Printf(\"%24s: {g}✔ {!}\\n\", file)\n\tcase FORMAT_JSON:\n\t\tfmt.Println(\"{}\")\n\tcase FORMAT_XML:\n\t\tfmt.Println(`<?xml version=\"1.0\" encoding=\"UTF-8\"?>`)\n\t\tfmt.Println(\"<alerts>\\n</alerts>\")\n\tcase \"\", FORMAT_SUMMARY, FORMAT_SHORT:\n\t\tfmtc.Println(\"{g}This spec is perfect!{!}\")\n\t}\n}", "func (c Colors) Fprintf(w io.Writer, format string, args ...interface{}) error {\n\t_, err := io.WriteString(w, c.Sprintf(format, args...))\n\treturn err\n}", "func Printf(format string, args ...interface{}) {\n\tprintdeps(sentry.CaptureMessage, 3, fmt.Sprintf(format, args...))\n}", "func printf(format string, a ...interface{}) {\n\tfmt.Fprintf(stdout, format, a...)\n}", "func printf(format string, a ...interface{}) {\n\tfmt.Fprintf(stdout, format, a...)\n}", "func format(str string, args ...Any) string {\n\treturn fmt.Sprintf(str, args...)\n}", "func Stdf(format string, a ...interface{}) {\n\tfmt.Printf(format, a...)\n}", "func Complainf(format string, args ...interface{}) {\n\tComplain(fmt.Sprintf(format, args...))\n}", "func fmtString(fs fmt.State, c rune, prec, width int, wantPlus bool) string {\n\tvar b strings.Builder\n\tb.WriteByte('%')\n\tfor _, f := range \"0+- \" {\n\t\tif fs.Flag(int(f)) || (f == '+' && wantPlus) {\n\t\t\tb.WriteByte(byte(f))\n\t\t}\n\t}\n\tif width >= 0 {\n\t\tfmt.Fprint(&b, width)\n\t}\n\tif prec >= 0 {\n\t\tb.WriteByte('.')\n\t\tif prec > 0 {\n\t\t\tfmt.Fprint(&b, prec)\n\t\t}\n\t}\n\tb.WriteRune(c)\n\treturn b.String()\n}", "func printUsage(f *os.File, kind HelpType) {\n\tconst usageTempl = `\nUSAGE:\n{{.Sp3}}{{.AppName}} --mount=<directory> --shadow=<directory> [--out=<file>]\n{{.Sp3}}{{.AppNameFiller}} [(--csv | --json)] [--ro]\n{{.Sp3}}{{.AppName}} --help\n{{.Sp3}}{{.AppName}} --version\n{{if eq .UsageVersion \"short\"}}\nUse '{{.AppName}} --help' to get detailed information about options and\nexamples of usage.{{else}}\n\nDESCRIPTION:\n{{.Sp3}}{{.AppName}} mounts a synthesized file system which purpose is to generate\n{{.Sp3}}trace events for each low level file I/O operation executed on any file\n{{.Sp3}}or directory under its control. Examples of such operations are open(2),\n{{.Sp3}}read(2), write(2), close(2), access(2), etc.\n\n{{.Sp3}}{{.AppName}} exposes the contents of the directory specified by the\n{{.Sp3}}option '--shadow' via the path specified by the option '--mount'. {{.AppName}}\n{{.Sp3}}generates a trace event for each I/O operation and forwards the operation\n{{.Sp3}}to the target file system, that is, the one which actually hosts the shadow\n{{.Sp3}}directory. See the EXAMPLES section below.\n\n{{.Sp3}}Individual trace events generated by {{.AppName}} are written to the specified\n{{.Sp3}}output file (option --out) in the specified format.\n\n\nOPTIONS:\n{{.Sp3}}--mount=<directory>\n{{.Tab1}}This is the top directory through which the files and directories residing\n{{.Tab1}}under the shadow directory will be exposed. See the EXAMPLES section below.\n{{.Tab1}}The specified directory must exist and must be empty.\n\n{{.Sp3}}--shadow=<directory>\n{{.Tab1}}This is a directory where the files and directories you want to trace\n{{.Tab1}}actually reside.\n{{.Tab1}}The specified directory must exist but may be empty.\n\n{{.Sp3}}--out=<file>\n{{.Tab1}}Path of the text file to write the trace events to. If this file\n{{.Tab1}}does not exist it will be created, otherwise new events will be appended.\n{{.Tab1}}Note that this file cannot be located under the shadow directory.\n{{.Tab1}}Use '-' (dash) to write the trace events to the standard output.\n{{.Tab1}}In addition, you can specify a file name with extension '.csv' or '.json'\n{{.Tab1}}to instruct {{.AppName}} to emit records in the corresponding format,\n{{.Tab1}}as if you had used the '--csv' or '--json' options (see below).\n{{.Tab1}}Default: write trace records to standard output.\n\n{{.Sp3}}--csv\n{{.Tab1}}Format each individual trace event generated by {{.AppName}} as a set of\n{{.Tab1}}comma-separated values in a single line.\n{{.Tab1}}Note that not all events contain the same information since each\n{{.Tab1}}low level I/O operation requires specific arguments. Please refer to\n{{.Tab1}}the documentation at 'https://github.com/airnandez/{{.AppName}}' for\n{{.Tab1}}details on the format of each event.\n{{.Tab1}}CSV is the default output format unless the output file name (see option\n{{.Tab1}}'--out' above) has a '.json' extension.\n\n{{.Sp3}}--json\n{{.Tab1}}Format each individual trace event generated by {{.AppName}} as\n{{.Tab1}}a JSON object. Events in this format are self-described but not all\n{{.Tab1}}events contain the same information since each low level I/O operation\n{{.Tab1}}requires specific arguments. Please refer to the documentation\n{{.Tab1}}at 'https://github.com/airnandez/{{.AppName}}' for details on the format\n{{.Tab1}}of each event.\n\n{{.Sp3}}--ro\n{{.Tab1}}Expose the shadow file system as a read-only file system.\n{{.Tab1}}Default: if this option is not specified, the file system is mounted in\n{{.Tab1}}read-write mode.\n\n{{.Sp3}}--allowother\n{{.Tab1}}Allow other users to access the file system.\n\n{{.Sp3}}--help\n{{.Tab1}}Show this help\n\n{{.Sp3}}--version\n{{.Tab1}}Show version information and source repository location\n\nEXAMPLES:\n{{.Sp3}}To trace file I/O operations on files under $HOME/data use:\n\n{{.Tab1}}{{.AppName}} --mount=/tmp/trace --shadow=$HOME/data\n\n{{.Sp3}}After a successfull mount, the contents under $HOME/data are also\n{{.Sp3}}accessible by using the path /tmp/trace. For instance, if the\n{{.Sp3}}file $HOME/data/hello.txt exists, {{.AppName}} traces all the file I/O\n{{.Sp3}}operations induced by the command:\n\n{{.Tab1}}cat /tmp/trace/hello.txt\n\n{{.Sp3}}Trace events for each one of the low level operations induced by the\n{{.Sp3}}'cat' command above will be written to the output file, the standard\n{{.Sp3}}output in this particular example.\n\n{{.Sp3}}You can also create new files under /tmp/trace. For instance, the file\n{{.Sp3}}I/O operations induced by the shell command:\n\n{{.Tab1}}echo \"This is a new file\" > /tmp/trace/newfile.txt\n\n{{.Sp3}}will be traced and the file will actually be created in\n{{.Sp3}}$HOME/data/newfile.txt. This file will persist even after unmounting\n{{.Sp3}}{{.AppName}} (see below on how to unmount the synthetized file system).\n\n{{.Sp3}}Please note that any destructive action, such as removing or modifying\n{{.Sp3}}the contents of a file or directory using the path /tmp/trace will\n{{.Sp3}}affect the corresponding file or directory under $HOME/data.\n{{.Sp3}}For example, the command:\n\n{{.Tab1}}rm /tmp/trace/notes.txt\n\n{{.Sp3}}will have the same destructive effect as if you had executed\n\n{{.Tab1}}rm $HOME/data/notes.txt\n\n{{.Sp3}}To unmount the file system exposed by {{.AppName}} use:\n\n{{.Tab1}}umount /tmp/trace\n\n{{.Sp3}}Alternatively, on MacOS X you can also use the diskutil(8) command:\n\n{{.Tab1}}/usr/sbin/diskutil unmount /tmp/trace\n{{end}}\n`\n\n\tfields := map[string]string{\n\t\t\"AppName\": programName,\n\t\t\"AppNameFiller\": strings.Repeat(\" \", len(programName)),\n\t\t\"Sp2\": \" \",\n\t\t\"Sp3\": \" \",\n\t\t\"Sp4\": \" \",\n\t\t\"Sp5\": \" \",\n\t\t\"Sp6\": \" \",\n\t\t\"Tab1\": \"\\t\",\n\t\t\"Tab2\": \"\\t\\t\",\n\t\t\"Tab3\": \"\\t\\t\\t\",\n\t\t\"Tab4\": \"\\t\\t\\t\\t\",\n\t\t\"Tab5\": \"\\t\\t\\t\\t\\t\",\n\t\t\"Tab6\": \"\\t\\t\\t\\t\\t\\t\",\n\t\t\"UsageVersion\": \"short\",\n\t}\n\tif kind == HelpLong {\n\t\tfields[\"UsageVersion\"] = \"long\"\n\t}\n\tminWidth, tabWidth, padding := 8, 4, 0\n\ttabwriter := tabwriter.NewWriter(f, minWidth, tabWidth, padding, byte(' '), 0)\n\ttempl := template.Must(template.New(\"\").Parse(usageTempl))\n\ttempl.Execute(tabwriter, fields)\n\ttabwriter.Flush()\n}", "func Debugf(format string, v ...interface{}) { std.lprintf(DEBUG, format, v...) }", "func Wrapf(err error, format string, args ...interface{}) error {\n\treturn wrap(err, fmt.Sprintf(format, args...))\n}", "func Fprintf(w io.Writer, format string, a ...interface{}) (int, error) {\n\tformat += ResetCode\n\tformat = compile(format)\n\treturn fmt.Fprintf(w, format, a...)\n}", "func Fprintf(w io.Writer, z []byte, params ...interface{}) {\n\tw.Write([]byte(Printf(z, params...)))\n}", "func (g *Generator) Printf(format string, args ...interface{}) {\n\t_, _ = fmt.Fprintf(&g.buf, format, args...)\n}", "func (g *Generator) Printf(format string, args ...interface{}) {\n\t_, _ = fmt.Fprintf(&g.buf, format, args...)\n}", "func PrintFaint(format string, a ...interface{}) { fmt.Println(Faint(format, a...)) }", "func (c *SetupCommand) printf(format string, values ...interface{}) {\n\tc.UI.Output(fmt.Sprintf(format, values...))\n}", "func printfFormatStringVerbs(info types.Info, call *ast.CallExpr) ([]string, bool) {\n\tif len(call.Args) <= 1 {\n\t\treturn nil, false\n\t}\n\tstrLit, ok := call.Args[0].(*ast.BasicLit)\n\tif !ok {\n\t\t// Ignore format strings that are not literals.\n\t\treturn nil, false\n\t}\n\tformatString := constant.StringVal(info.Types[strLit].Value)\n\n\tpp := printfParser{str: formatString}\n\tverbs, err := pp.ParseAllVerbs()\n\tif err != nil {\n\t\treturn nil, false\n\t}\n\torderedVerbs := verbOrder(verbs, len(call.Args)-1)\n\n\tresolvedVerbs := make([]string, len(orderedVerbs))\n\tfor i, vv := range orderedVerbs {\n\t\tfor _, v := range vv {\n\t\t\tresolvedVerbs[i] = v.format\n\t\t\tif v.format == \"w\" {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\treturn resolvedVerbs, true\n}", "func SimpleSpec(name, image string, cmd []string) string {\n\tcmds, err := json.Marshal(cmd)\n\tif err != nil {\n\t\t// This shouldn't happen.\n\t\tpanic(err)\n\t}\n\treturn fmt.Sprintf(`\n{\n \"metadata\": {\n \"name\": %q\n },\n \"image\": {\n \"image\": %q\n },\n \"command\": %s\n\t}\n`, name, image, cmds)\n}", "func Fmt(str string, args ...interface{}) Format {\r\n\treturn append(Format{str}, args...)\r\n}", "func Fprintf(w io.Writer, format string, args ...interface{}) (n int, err error) {\n\treturn wrapWriter(w, func() (int, error) {\n\t\treturn fmt.Fprintf(w, style.StyleString(format), styleArgs(args)...)\n\t})\n}", "func debugf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}", "func debugf(format string, a ...interface{}) {\n\tfmt.Fprintf(os.Stderr, format, a...)\n}", "func Printf(format string, v ...interface{}) {\n\tstd.Output(std.callDepth, fmt.Sprintf(format, v...), std.level)\n}", "func printf(s string, args ...interface{}) {\n\tswitch {\n\tcase cfg.Verbose, cfg.RawJSON:\n\t\t// These are handled by the politeiawwww client\n\tcase cfg.Silent:\n\t\t// Do nothing\n\tdefault:\n\t\t// Print to stdout\n\t\tfmt.Printf(s, args...)\n\t}\n}", "func dotPrintf(fullLen int, lfStr, rtFmtStr string, args ...interface{}) {\n\trtStr := fmt.Sprintf(rtFmtStr, args...)\n\tdotLen := fullLen - len(lfStr) - len(rtStr)\n\tif dotLen < 2 {\n\t\tdotLen = 2\n\t}\n\tfmt.Printf(\"%s %s %s\\n\", lfStr, strings.Repeat(\".\", dotLen), rtStr)\n}", "func f(value float64, precision int, envvar string, fixed bool) string {\n\tparts := strings.Split(strconv.FormatFloat(value, 'f', -1, 64), \".\")\n\tif !fixed && len(parts) > 1 {\n\t\tfor ; precision < len(parts[1]); precision += 1 {\n\t\t\tif parts[1][precision] == '0' {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tenvlang, ok := os.LookupEnv(envvar)\n\tif !ok {\n\t\tenvlang = \"en\"\n\t}\n\tlang := language.Make(envlang)\n\n\tformat := fmt.Sprintf(\"%%.%df\", precision)\n\treturn message.NewPrinter(lang).Sprintf(format, value)\n}", "func Fprintf(w io.Writer, f string, a ...any) (int, error) {\n\treturn fmt.Fprintf(w, searchColors(f, -1, DisableColors), a...)\n}", "func Panicf(format string, v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprintf(format, v...)\n\tstd.Report(s)\n\tlog.Panic(s)\n}", "func Wrapf(err error, description string, data ...interface{}) Err {\n\treturn Wrap(err, fmt.Sprintf(description, data...))\n}", "func Wrapf(err error, format string, args ...interface{}) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\treturn &wrap{err, fmt.Sprintf(format, args...)}\n}", "func fncSprintf(ctx core.Context, args []*core.ZVal) (*core.ZVal, error) {\n\tvar fmt core.ZString\n\tn, err := core.Expand(ctx, args, &fmt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn core.Zprintf(ctx, fmt, args[n:]...)\n}", "func panicf(format string, args ...interface{}) {\n\tpanic(fmt.Sprintf(format, args...))\n}", "func wrapf(format string, a ...interface{}) error {\n\treturn fmt.Errorf(\"gpioreg: \"+format, a...)\n}", "func Debugf(template string, args ...interface{}) {\n\tDebug(fmt.Sprintf(template, args...))\n}", "func Wrapf(err error, format string, a ...interface{}) Error {\n\treturn Wrap(err, fmt.Sprintf(format, a...))\n}", "func Printf(format string, a ...interface{}) {\n\t_, _ = p.Printf(format, a...)\n}", "func logf(level string, format string, args ...interface{}) {\n\tfmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+\": \"+level+\": \"+format+\"\\n\", args...)\n}", "func (g *Generator) Printf(format string, args ...interface{}) {\n\tfmt.Fprintf(&g.buf, format, args...)\n}", "func ParamSpecString_(name string, nick string, blurb string, defaultValue string, flags ParamFlags) *ParamSpec {\n\tc_name := C.CString(name)\n\tdefer C.free(unsafe.Pointer(c_name))\n\n\tc_nick := C.CString(nick)\n\tdefer C.free(unsafe.Pointer(c_nick))\n\n\tc_blurb := C.CString(blurb)\n\tdefer C.free(unsafe.Pointer(c_blurb))\n\n\tc_default_value := C.CString(defaultValue)\n\tdefer C.free(unsafe.Pointer(c_default_value))\n\n\tc_flags := (C.GParamFlags)(flags)\n\n\tretC := C.g_param_spec_string(c_name, c_nick, c_blurb, c_default_value, c_flags)\n\tretGo := ParamSpecNewFromC(unsafe.Pointer(retC))\n\n\treturn retGo\n}", "func getFmtStringFromArgs(input string, v1, v2 starlark.Value) string {\n\t// Only calc diff if necessary.\n\tdiff := \"\"\n\tif i3 := strings.Index(input, \"$3\"); i3 >= 0 {\n\t\tdiff = pretty.Compare(v1, v2)\n\t}\n\n\trep := strings.NewReplacer(\n\t\t\"$1\", fmt.Sprint(v1),\n\t\t\"$2\", fmt.Sprint(v2),\n\t\t\"$3\", fmt.Sprint(diff),\n\t\t\"$4\", v1.Type(),\n\t\t\"$5\", v2.Type(),\n\t\t`\\n`, \"\\n\",\n\t\t`\\t`, \"\\t\",\n\t)\n\n\t// Run it through twice to resolve any newlines/tabs that get placed into the diff.\n\treturn rep.Replace(rep.Replace(input))\n}", "func Infof(format string, args ...interface{}) {\n\tfmt.Fprintf(Writer, format, args...)\n}", "func Infof(format string, a ...interface{}) {\n\tInfoln(fmt.Sprintf(format, a...))\n}", "func f(format string, e *Error) string {\n\treturn fmt.Sprintf(format, e)\n}", "func Sprintf(format string, args ...interface{}) string {\n\tctx := new(ctxType)\n\tctx.format = format\n\tctx.args = args\n\tctx.parseFormatString()\n\tctx.applyFormats()\n\treturn ctx.combineFormattedStrings()\n}", "func Sprintf(format string, a ...interface{}) string {\n\treturn p.Sprintf(format, a...)\n}", "func TestComplexFormatting(t *testing.T) {\n\tvar yesNo = []bool{true, false}\n\tvar values = []float64{1, 0, -1, posInf, negInf, NaN}\n\tfor _, plus := range yesNo {\n\t\tfor _, zero := range yesNo {\n\t\t\tfor _, space := range yesNo {\n\t\t\t\tfor _, char := range \"fFeEgG\" {\n\t\t\t\t\trealFmt := \"%\"\n\t\t\t\t\tif zero {\n\t\t\t\t\t\trealFmt += \"0\"\n\t\t\t\t\t}\n\t\t\t\t\tif space {\n\t\t\t\t\t\trealFmt += \" \"\n\t\t\t\t\t}\n\t\t\t\t\tif plus {\n\t\t\t\t\t\trealFmt += \"+\"\n\t\t\t\t\t}\n\t\t\t\t\trealFmt += \"10.2\"\n\t\t\t\t\trealFmt += string(char)\n\t\t\t\t\t// Imaginary part always has a sign, so force + and ignore space.\n\t\t\t\t\timagFmt := \"%\"\n\t\t\t\t\tif zero {\n\t\t\t\t\t\timagFmt += \"0\"\n\t\t\t\t\t}\n\t\t\t\t\timagFmt += \"+\"\n\t\t\t\t\timagFmt += \"10.2\"\n\t\t\t\t\timagFmt += string(char)\n\t\t\t\t\tfor _, realValue := range values {\n\t\t\t\t\t\tfor _, imagValue := range values {\n\t\t\t\t\t\t\tone := Sprintf(realFmt, complex(realValue, imagValue))\n\t\t\t\t\t\t\ttwo := Sprintf(\"(\"+realFmt+imagFmt+\"i)\", realValue, imagValue)\n\t\t\t\t\t\t\tif one != two {\n\t\t\t\t\t\t\t\tt.Error(f, one, two)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *MockLogger) Printf(format string, args ...interface{}) {\n\tm.ctrl.T.Helper()\n\tvarargs := []interface{}{format}\n\tfor _, a := range args {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Printf\", varargs...)\n}", "func panicf(s string, args ...interface{}) {\n\tpanic(fmt.Sprintf(s, args...))\n}", "func (m *MockInterface) Printf(arg0 string, arg1 ...interface{}) {\n\tvarargs := []interface{}{arg0}\n\tfor _, a := range arg1 {\n\t\tvarargs = append(varargs, a)\n\t}\n\tm.ctrl.Call(m, \"Printf\", varargs...)\n}", "func Verbosef(format string, v ...interface{}) {\n\tif std.level >= VerboseLevel {\n\t\tstd.Output(std.callDepth, fmt.Sprintf(format, v...), VerboseLevel)\n\t}\n}", "func Printf(format string, a ...interface{}) { writeLog(fmt.Sprintf(format, a...)) }", "func Panicf(format string, v ...interface{}) {\n\ts := fmt.Sprintf(format, v...)\n\tstd.Output(std.callDepth, s, PanicLevel)\n\tpanic(s)\n}", "func Flushf(s string, vs ...interface{}) {\n\tt := time.Now().Format(\"2006/01/02 15:04:05\")\n\tmsg := fmt.Sprintf(\"\\r\"+t+\" [io] \"+s, vs...)\n\tfmt.Printf(\"\\r\" + strings.Repeat(\" \", len(msg)+1))\n\tfmt.Printf(msg)\n}", "func Printf(format string, a ...interface{}) (int, error) {\n\tformat += ResetCode\n\tformat = compile(format)\n\treturn fmt.Printf(format, a...)\n}", "func (p *Printer) Printf(format string, a ...interface{}) {\n\tdoPrintV2(p.String(), fmt.Sprintf(format, a...))\n}", "func (ts *TableSpec) Format(buf *TrackedBuffer) {\n\tbuf.astPrintf(ts, \"(\\n\")\n\tfor i, col := range ts.Columns {\n\t\tif i == 0 {\n\t\t\tbuf.astPrintf(ts, \"\\t%v\", col)\n\t\t} else {\n\t\t\tbuf.astPrintf(ts, \",\\n\\t%v\", col)\n\t\t}\n\t}\n\tfor _, idx := range ts.Indexes {\n\t\tbuf.astPrintf(ts, \",\\n\\t%v\", idx)\n\t}\n\tfor _, c := range ts.Constraints {\n\t\tbuf.astPrintf(ts, \",\\n\\t%v\", c)\n\t}\n\n\tbuf.astPrintf(ts, \"\\n)%s\", strings.Replace(ts.Options, \", \", \",\\n \", -1))\n}", "func (s Style) Printf(format string, a ...interface{}) {\n\tPrint(s.Sprintf(format, a...))\n}", "func (c Color) Fprintf(w io.Writer, format string, args ...interface{}) error {\n\t_, err := io.WriteString(w, c.Sprintf(format, args...))\n\treturn err\n}", "func (j *JobConfig) fullSpec() string {\n\tif j.Timezone != \"\" {\n\t\treturn fmt.Sprintf(\"TZ=%s %s\", j.Timezone, j.Spec)\n\t}\n\treturn j.Spec\n}", "func Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {\n\treturn fmt.Fprintf(w, scolorf(format), a...)\n}", "func Warnf(template string, args ...interface{}) {\n\tWarn(fmt.Sprintf(template, args...))\n}", "func (c *Cli) Printf(format string, vals ...interface{}) {\n\tfmt.Fprintf(c.Output, format, vals...)\n}", "func F(f string, v ...interface{}) {\n\t// log.Printf(f, v...)\n\tspewInstance.Printf(f+\"\\n\", v...)\n}", "func (fmt shadower) f() {}", "func (p Property) Sprintf(format string, a ...interface{}) string {\n\treturn fmt.Sprintf(\"%s%s%s\", p, fmt.Sprintf(format, a...), Reset)\n}", "func (d *Default) Printf(format string, args ...interface{}) {\n\tif d.PrefixTimeFormat != \"\" {\n\t\td.WriteString(time.Now().UTC().Format(d.PrefixTimeFormat))\n\t}\n\n\td.WriteString(fmt.Sprintf(format, args...))\n\td.WriteString(\"\\n\")\n}", "func Sprintf(format string, a ...interface{}) string {\n\treturn fmt.Sprintf(format, a...)\n}", "func printfArgKind(info *types.Info, call *ast.CallExpr, argIdx int) objKind {\n\t// Printf-like function name must end in \"f\".\n\tfn := exprObj(info, call.Fun)\n\tif fn == nil || !strings.HasSuffix(fn.Name(), \"f\") {\n\t\treturn kindAny\n\t}\n\n\tsig, _ := fn.Type().(*types.Signature)\n\tif sig == nil {\n\t\treturn kindAny\n\t}\n\n\t// Must be variadic and take at least two params.\n\tnumParams := sig.Params().Len()\n\tif !sig.Variadic() || numParams < 2 || argIdx < numParams-1 {\n\t\treturn kindAny\n\t}\n\n\t// Param preceding variadic args must be a (format) string.\n\tif !types.Identical(sig.Params().At(numParams-2).Type(), types.Typ[types.String]) {\n\t\treturn kindAny\n\t}\n\n\t// Format string must be a constant.\n\tstrArg := info.Types[call.Args[numParams-2]].Value\n\tif strArg == nil || strArg.Kind() != constant.String {\n\t\treturn kindAny\n\t}\n\n\treturn formatOperandKind(constant.StringVal(strArg), argIdx-(numParams-1)+1)\n}", "func Printf(s string, tabulated string, cellPrinters ...func(string, int)) {\n\tStyle = s\n\tPrint(tabulated, cellPrinters...)\n}", "func RunF(format string, args ...interface{}) error {\n\treturn Run(fmt.Sprintf(format, args...))\n}", "func Failf(t *testing.T, template string, args ...interface{}) {\n\tf := bufio.NewWriter(os.Stdout)\n\n\t_, err := f.WriteString(fmt.Sprintf(template, args...))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"writing to output failed: %s\", err))\n\t}\n\n\terr = f.WriteByte('\\n')\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"writing to output failed: %s\", err))\n\t}\n\n\terr = f.Flush()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"writing to output failed: %s\", err))\n\t}\n\n\tt.Fail()\n}", "func Panicf(format string, v ...interface{}) {\n s := fmt.Sprintf(format, v...)\n Std.Output(LevelPanic, CallDepth, s)\n panic(s)\n}", "func Printf(format string, a ...interface{}) {\n\tbuf := header(0)\n\tfmt.Fprintf(buf, format, a...)\n\tio.Copy(os.Stdout, buf)\n}", "func (b *printer) Printf(format string, args ...interface{}) {\n\t_, _ = Fprintf(&b.buf, format, args...)\n}", "func Printf(format string, a ...interface{}) {\n\twrite <- []segment{{text: fmt.Sprintf(format, a...)}}\n}" ]
[ "0.63816696", "0.59947926", "0.5981208", "0.5851825", "0.5782323", "0.57790077", "0.57714134", "0.571948", "0.5710342", "0.56592196", "0.5635487", "0.56237805", "0.5622936", "0.561847", "0.56002074", "0.55893624", "0.55875313", "0.55875313", "0.5572603", "0.5544484", "0.5512988", "0.550966", "0.55077547", "0.55060905", "0.5503701", "0.54946274", "0.5486395", "0.5486395", "0.54597217", "0.54519206", "0.54475236", "0.5436637", "0.5430886", "0.5417781", "0.5407422", "0.5404628", "0.53985023", "0.53905433", "0.53905433", "0.53905225", "0.5388332", "0.53798705", "0.5378546", "0.5349176", "0.5347546", "0.5346005", "0.5346005", "0.53374773", "0.53300464", "0.53186053", "0.5311216", "0.5304907", "0.5303737", "0.52938914", "0.5289347", "0.5286485", "0.52831113", "0.5280297", "0.5280154", "0.5278243", "0.5274458", "0.52731514", "0.52579033", "0.5257687", "0.5247723", "0.52395546", "0.52385455", "0.5235099", "0.5227764", "0.52166414", "0.5209321", "0.52059925", "0.520042", "0.51935714", "0.519186", "0.51867735", "0.51812315", "0.5177271", "0.5175766", "0.51718384", "0.51698714", "0.51674694", "0.5164463", "0.5157902", "0.51568323", "0.5155444", "0.5151981", "0.5151596", "0.5150235", "0.51461095", "0.5145885", "0.5145236", "0.514219", "0.5138033", "0.51357985", "0.5132058", "0.5132016", "0.5131909", "0.51302683", "0.5119831" ]
0.8064515
0
function kspecf() is a wrapper for function specf() that changes the kind of ReturnCode from the default.
func (c *ReturnCode) kspecf(kind ReturnCodeKind, format string, v ...interface{}) *ReturnCode { c.kind = kind return c.specf(format, v...) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *ReturnCode) specf(format string, v ...interface{}) *ReturnCode {\n\ts := fmt.Sprintf(format, v...)\n\treturn c.spec(s)\n}", "func (o LookupFeatureResultOutput) Spec() CommonFeatureSpecResponseOutput {\n\treturn o.ApplyT(func(v LookupFeatureResult) CommonFeatureSpecResponse { return v.Spec }).(CommonFeatureSpecResponseOutput)\n}", "func (s *Service) Spec(ctx context.Context) (map[string]interface{}, error) {\n\treturn s.ChainSpec(ctx)\n}", "func (o LookupServiceResultOutput) Spec() ServiceSpecResponseOutput {\n\treturn o.ApplyT(func(v LookupServiceResult) ServiceSpecResponse { return v.Spec }).(ServiceSpecResponseOutput)\n}", "func (c *ReturnCode) spec(info string) *ReturnCode {\n\tc.info = info\n\treturn c\n}", "func (s *BaseConcertoListener) ExitFuncSpec(ctx *FuncSpecContext) {}", "func kprobe(symbol string, prog *ebpf.Program, ret bool) (*perfEvent, error) {\n\tif symbol == \"\" {\n\t\treturn nil, fmt.Errorf(\"symbol name cannot be empty: %w\", errInvalidInput)\n\t}\n\tif prog == nil {\n\t\treturn nil, fmt.Errorf(\"prog cannot be nil: %w\", errInvalidInput)\n\t}\n\tif !rgxTraceEvent.MatchString(symbol) {\n\t\treturn nil, fmt.Errorf(\"symbol '%s' must be alphanumeric or underscore: %w\", symbol, errInvalidInput)\n\t}\n\tif prog.Type() != ebpf.Kprobe {\n\t\treturn nil, fmt.Errorf(\"eBPF program type %s is not a Kprobe: %w\", prog.Type(), errInvalidInput)\n\t}\n\n\t// Use kprobe PMU if the kernel has it available.\n\ttp, err := pmuKprobe(platformPrefix(symbol), ret)\n\tif errors.Is(err, os.ErrNotExist) {\n\t\ttp, err = pmuKprobe(symbol, ret)\n\t}\n\tif err == nil {\n\t\treturn tp, nil\n\t}\n\tif err != nil && !errors.Is(err, ErrNotSupported) {\n\t\treturn nil, fmt.Errorf(\"creating perf_kprobe PMU: %w\", err)\n\t}\n\n\t// Use tracefs if kprobe PMU is missing.\n\ttp, err = tracefsKprobe(platformPrefix(symbol), ret)\n\tif errors.Is(err, os.ErrNotExist) {\n\t\ttp, err = tracefsKprobe(symbol, ret)\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating trace event '%s' in tracefs: %w\", symbol, err)\n\t}\n\n\treturn tp, nil\n}", "func (sat SignatureAlgoType) Specifier() Specifier {\n\tswitch sat {\n\tcase SignatureAlgoEd25519:\n\t\treturn SignatureAlgoEd25519Specifier\n\tdefault:\n\t\treturn SignatureAlgoNilSpecifier\n\t}\n}", "func TestSpec_MustGetValidType(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ttestGet := func(s *Spec, v string) (r string) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tr = fmt.Sprintf(\"%s\", err)\n\t\t\t}\n\t\t}()\n\t\ts.MustGetValidType(v)\n\t\treturn\n\t}\n\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif testGet(s, \"bool\") == \"find <bool> in code <\"+code+\"> failed\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.MustGetValidType(\"bool\").String() == \"bool\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.MustGetValidType(\"bool\").String() == \"bool\" &&\n\t\ts.MustGetValidType(\"fmt\").String() == \"invalid type\" &&\n\t\ts.MustGetValidType(\"a\").String() == \"untyped int\" &&\n\t\ts.MustGetValidType(\"b\").String() == \"float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func (s *RateLimitSuite) TestSpecIsOK(c *C) {\n\tc.Assert(plugin.NewRegistry().AddSpec(GetSpec()), IsNil)\n}", "func (s *RateLimitSuite) TestSpecIsOK(c *C) {\n\tc.Assert(plugin.NewRegistry().AddSpec(GetSpec()), IsNil)\n}", "func getInstanceTypeSpecScore(spec AliyunInstanceTypeSpec) float64 {\n\tscore := (float64(spec.CPUCoreCount*20) + spec.MemorySize*20 + float64(spec.GPUAmount*40) + float64(spec.EniPrivateIPAddressQuantity*2) + float64(spec.EniQuantity*10))\n\tswitch spec.InstanceFamilyLevel {\n\tcase \"CreditEntryLevel\":\n\t\tscore += 100\n\tcase \"EnterpriseLevel\":\n\t\tscore += 500\n\tdefault:\n\t\tscore += 200\n\t}\n\treturn score\n}", "func tracefsKprobe(symbol string, ret bool) (*perfEvent, error) {\n\treturn tracefsProbe(kprobeType, symbol, \"\", 0, perfAllThreads, ret)\n}", "func (ctl *Ctl) SwitchSpec(specType string) error {\n\tswitch specType {\n\tcase EmptySpec:\n\t\tctl.Spec = &alertapi.AlertSpec{}\n\tcase TemplateSpec:\n\t\tctl.Spec = crddefaults.GetAlertTemplate()\n\tcase DefaultSpec:\n\t\tctl.Spec = crddefaults.GetAlertDefault()\n\tdefault:\n\t\treturn fmt.Errorf(\"Alert Spec Type %s is not valid\", specType)\n\t}\n\treturn nil\n}", "func anyClientNilResultValueSpec(spec *MethodSpec, method string) *MethodSpec {\n\t// Commands that can return nil/zero-value given random input and state\n\tswitch method {\n\t// Redis-Spec: DB may be empty and AllKeys can return nil result\n\t// REVU: check if this is actually conformant\n\tcase \"AllKeys\":\n\t\tspec.NoNilResultValue = false\n\t}\n\n\treturn spec\n}", "func (o PriorityLevelConfigurationOutput) Spec() PriorityLevelConfigurationSpecOutput {\n\treturn o.ApplyT(func(v *PriorityLevelConfiguration) PriorityLevelConfigurationSpecOutput { return v.Spec }).(PriorityLevelConfigurationSpecOutput)\n}", "func (o *TeamConfiguration) GetSpecOk() (*TeamConfigurationSpec, bool) {\n\tif o == nil {\n\t\treturn nil, false\n\t}\n\treturn &o.Spec, true\n}", "func (o *V1VolumeClaim) GetSpecOk() (*V1VolumeClaimSpec, bool) {\n\tif o == nil || o.Spec == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Spec, true\n}", "func (o PriorityLevelConfigurationPatchOutput) Spec() PriorityLevelConfigurationSpecPatchPtrOutput {\n\treturn o.ApplyT(func(v *PriorityLevelConfigurationPatch) PriorityLevelConfigurationSpecPatchPtrOutput { return v.Spec }).(PriorityLevelConfigurationSpecPatchPtrOutput)\n}", "func (o LookupPolicyResultOutput) Spec() GoogleCloudOrgpolicyV2PolicySpecResponseOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) GoogleCloudOrgpolicyV2PolicySpecResponse { return v.Spec }).(GoogleCloudOrgpolicyV2PolicySpecResponseOutput)\n}", "func (o ApplicationTypeOutput) Spec() ApplicationSpecOutput {\n\treturn o.ApplyT(func(v ApplicationType) ApplicationSpec { return v.Spec }).(ApplicationSpecOutput)\n}", "func (s *BasePlSqlParserListener) ExitFunction_spec(ctx *Function_specContext) {}", "func GetSpec(ctx echo.Context) error {\n\tspec, err := api.GetSwagger()\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, err.Error())\n\t}\n\treturn ctx.JSON(http.StatusOK, spec)\n}", "func (s *BasecluListener) ExitType_spec(ctx *Type_specContext) {}", "func (cc *ChaincodeEnv) getChaincodeSpec(args [][]byte) *pb.ChaincodeSpec {\r\n\tspec := &pb.ChaincodeSpec{}\r\n\tfuncname := cc.Function\r\n\tinput := &pb.ChaincodeInput{}\r\n\tinput.Args = append(input.Args, []byte(funcname))\r\n\r\n\tfor _, arg := range args {\r\n\t\tinput.Args = append(input.Args, arg)\r\n\t}\r\n\r\n\tlogger.Debug(\"ChaincodeSpec input :\", input, \" funcname:\", funcname)\r\n\tvar golang = pb.ChaincodeSpec_Type_name[1]\r\n\tspec = &pb.ChaincodeSpec{\r\n\t\tType: pb.ChaincodeSpec_Type(pb.ChaincodeSpec_Type_value[golang]),\r\n\t\t// ChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName, Version: cc.ChaincodeVersion},\r\n\t\tChaincodeId: &pb.ChaincodeID{Name: cc.ChaincodeName},\r\n\t\tInput: input,\r\n\t}\r\n\treturn spec\r\n}", "func TestSpec_MustGetValidTypeObject(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ttestGet := func(s *Spec, v string) (r string) {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tr = fmt.Sprintf(\"%s\", err)\n\t\t\t}\n\t\t}()\n\t\ts.MustGetValidTypeObject(v)\n\t\treturn\n\t}\n\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif testGet(s, \"bool\") == \"find <bool> in code <\"+code+\"> failed\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.MustGetValidTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ttestGet(s, \"fmt\") == \"find <fmt> in code <\"+code+\"> failed\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ttestGet(s, \"b\") == \"find <b> in code <\"+code+\"> failed\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.MustGetValidTypeObject(\"bool\").String() == \"type bool\" &&\n\t\ts.MustGetValidTypeObject(\"fmt\").String() == \"package fmt\" &&\n\t\ts.MustGetValidTypeObject(\"a\").String() == \"const haha.a untyped int\" &&\n\t\ts.MustGetValidTypeObject(\"b\").String() == \"var b float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func (s *BaseConcertoListener) ExitFuncCallSpec(ctx *FuncCallSpecContext) {}", "func (o LookupPolicyResultOutput) DryRunSpec() GoogleCloudOrgpolicyV2PolicySpecResponseOutput {\n\treturn o.ApplyT(func(v LookupPolicyResult) GoogleCloudOrgpolicyV2PolicySpecResponse { return v.DryRunSpec }).(GoogleCloudOrgpolicyV2PolicySpecResponseOutput)\n}", "func TestSpec_GetType(t *testing.T) {\n\tcode := `\npackage haha\nimport \"fmt\"\nconst a = 1\nfunc main() {\n var b = 2.0\n type c struct {\n d string\n }\n fmt.Println(a, b)\n}`\n\ts := NewSpec(code)\n\ts.SearchKind = SearchOnlyPackage\n\tif s.GetType(\"bool\") == nil &&\n\t\ts.GetType(\"fmt\") == nil &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchPackageAndUniverse\n\tif s.GetType(\"bool\").String() == \"bool\" &&\n\t\ts.GetType(\"fmt\") == nil &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\") == nil {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n\ts.SearchKind = SearchAll\n\tif s.GetType(\"bool\").String() == \"bool\" &&\n\t\ts.GetType(\"fmt\").String() == \"invalid type\" &&\n\t\ts.GetType(\"a\").String() == \"untyped int\" &&\n\t\ts.GetType(\"b\").String() == \"float64\" {\n\t} else {\n\t\tt.Error(`test failed`)\n\t}\n}", "func checkSpec(spec *pb.ChaincodeSpec) error {\n\t// Don't allow nil value\n\tif spec == nil {\n\t\tfmt.Printf(\"Expected chaincode specification, nil received\")\n\t}\n\n\tplatform, err := platforms.Find(spec.Type)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to determine platform type: %s\", err)\n\t}\n\n\treturn platform.ValidateSpec(spec)\n}", "func (o ClusterTrustBundleOutput) Spec() ClusterTrustBundleSpecOutput {\n\treturn o.ApplyT(func(v *ClusterTrustBundle) ClusterTrustBundleSpecOutput { return v.Spec }).(ClusterTrustBundleSpecOutput)\n}", "func (s *BasevhdlListener) ExitFunction_specification(ctx *Function_specificationContext) {}", "func DefaultSpec() specs.Spec {\n\ts := specs.Spec{}\n\treturn s\n}", "func (o VirtualGatewayOutput) Spec() VirtualGatewaySpecOutput {\n\treturn o.ApplyT(func(v *VirtualGateway) VirtualGatewaySpecOutput { return v.Spec }).(VirtualGatewaySpecOutput)\n}", "func DefaultSpec() specs.Spec {\n\ts := specs.Spec{\n\t\tVersion: \"0.6.0\",\n\t\tPlatform: specs.Platform{\n\t\t\tOS: \"SunOS\",\n\t\t\tArch: runtime.GOARCH,\n\t\t},\n\t}\n\ts.Solaris = &specs.Solaris{}\n\treturn s\n}", "func (f Func) Specialize(b, l int) Func {\n\tif f == FuncNone {\n\t\treturn FuncNone\n\t}\n\tif b != -1 {\n\t\tparts := strings.SplitN(string(f), \"_\", 2)\n\t\tif len(parts) == 1 {\n\t\t\treturn FuncNone\n\t\t}\n\t\tf = Func(parts[0] + strconv.Itoa(b) + \"_\" + parts[1])\n\t}\n\tif l != -1 {\n\t\tf += Func(strconv.Itoa(l))\n\t}\n\treturn f\n}", "func (s *BaseConcertoListener) ExitTypeSpec(ctx *TypeSpecContext) {}", "func (o FioTypeOutput) Spec() FioSpecPtrOutput {\n\treturn o.ApplyT(func(v FioType) *FioSpec { return v.Spec }).(FioSpecPtrOutput)\n}", "func (g *Generator) Spec() *rspec.Spec {\n\treturn g.spec\n}", "func differentSCTypesTest(driver testsuites.TestDriver) {\n\tvar (\n\t\tpod *corev1.Pod\n\t\tpvcs []*corev1.PersistentVolumeClaim\n\t\tk8sSC *storagev1.StorageClass\n\t\tdriverCleanup func()\n\t\tns string\n\t\tf = framework.NewDefaultFramework(\"different-scs\")\n\t)\n\n\tinit := func(scType string) {\n\t\tvar (\n\t\t\tperTestConf *testsuites.PerTestConfig\n\t\t\terr error\n\t\t)\n\t\tns = f.Namespace.Name\n\t\tif scType == \"SSD\" {\n\t\t\tnodes, err := e2enode.GetReadySchedulableNodesOrDie(f.ClientSet)\n\t\t\tframework.ExpectNoError(err)\n\t\t\tvar nodeNames []string\n\t\t\tfor _, item := range nodes.Items {\n\t\t\t\tnodeNames = append(nodeNames, item.Name)\n\t\t\t}\n\t\t\t_, err = f.ClientSet.CoreV1().ConfigMaps(ns).Create(constructLoopbackConfigWithDriveType(ns, nodeNames, scType))\n\t\t\tframework.ExpectNoError(err)\n\t\t}\n\t\tperTestConf, driverCleanup = driver.PrepareTest(f)\n\n\t\tk8sSC = driver.(*baremetalDriver).GetStorageClassWithStorageType(perTestConf, scType)\n\t\tk8sSC, err = f.ClientSet.StorageV1().StorageClasses().Create(k8sSC)\n\t\tframework.ExpectNoError(err)\n\t}\n\n\tcleanup := func() {\n\t\te2elog.Logf(\"Starting cleanup for test DriveHealthChange\")\n\t\tcommon.CleanupAfterCustomTest(f, driverCleanup, []*corev1.Pod{pod}, pvcs)\n\t}\n\n\tginkgo.It(\"should create Pod with PVC with SSD type\", func() {\n\t\tscType := \"SSD\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = createPVCs(f, 3, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n\n\tginkgo.It(\"should create Pod with PVC with ANY type\", func() {\n\t\tscType := \"ANY\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = createPVCs(f, 3, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n\n\tginkgo.It(\"should create Pod with PVC with HDD type\", func() {\n\t\tscType := \"HDD\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = createPVCs(f, 3, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n\n\t// test for logical volume group storage class\n\tginkgo.It(\"should create Pod with PVC with HDDLVG type\", func() {\n\t\tscType := \"HDDLVG\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = createPVCs(f, 3, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n\t// test for raw block volumes\n\tginkgo.It(\"should create Pod with raw block volume HDD\", func() {\n\t\tscType := \"HDD\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = []*corev1.PersistentVolumeClaim{createBlockPVC(\n\t\t\tf, 1, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)}\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n\n\tginkgo.It(\"should create Pod with raw block volume HDDLVG\", func() {\n\t\tscType := \"HDDLVG\"\n\t\tinit(scType)\n\t\tdefer cleanup()\n\t\tpvcs = []*corev1.PersistentVolumeClaim{createBlockPVC(\n\t\t\tf, 1, driver.(testsuites.DynamicPVTestDriver).GetClaimSize(), k8sSC.Name, ns)}\n\t\tpod = startAndWaitForPodWithPVCRunning(f, ns, pvcs)\n\t})\n}", "func (o LookupSharedImageResultOutput) Specialized() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v LookupSharedImageResult) bool { return v.Specialized }).(pulumi.BoolOutput)\n}", "func (o QperfTypeOutput) Spec() QperfSpecPtrOutput {\n\treturn o.ApplyT(func(v QperfType) *QperfSpec { return v.Spec }).(QperfSpecPtrOutput)\n}", "func (o SysbenchTypeOutput) Spec() SysbenchSpecPtrOutput {\n\treturn o.ApplyT(func(v SysbenchType) *SysbenchSpec { return v.Spec }).(SysbenchSpecPtrOutput)\n}", "func (o LookupEntryResultOutput) FilesetSpec() GoogleCloudDatacatalogV1FilesetSpecResponseOutput {\n\treturn o.ApplyT(func(v LookupEntryResult) GoogleCloudDatacatalogV1FilesetSpecResponse { return v.FilesetSpec }).(GoogleCloudDatacatalogV1FilesetSpecResponseOutput)\n}", "func resolveFSTypeSpec(spec *api.VolumeSpec, req *csi.CreateVolumeRequest) (*api.VolumeSpec, error) {\n\tvar csiFsType string\n\tfor _, cap := range req.GetVolumeCapabilities() {\n\t\tif cap.GetBlock() != nil {\n\t\t\tspec.Format = api.FSType_FS_TYPE_NONE\n\t\t\treturn spec, nil\n\t\t}\n\n\t\t// Get FsType according to CSI spec\n\t\tif mount := cap.GetMount(); mount != nil {\n\t\t\tcsiFsType = mount.FsType\n\t\t}\n\t}\n\n\t// if we have the FileSystemSpec option not set, this means the user didn't intend to\n\t// set the filesystem type based on the \"PX way\". In this case, we can safely\n\t// apply the fsType from the CSI request.\n\tif !isFilesystemSpecSet(req.GetParameters()) && csiFsType != \"\" {\n\t\tformat, err := api.FSTypeSimpleValueOf(csiFsType)\n\t\tif err != nil {\n\t\t\treturn spec, err\n\t\t}\n\t\tspec.Format = format\n\t}\n\n\treturn spec, nil\n}", "func TestMilpaToK8sVolume(t *testing.T) {\n\ti32 := int32(rand.Intn(math.MaxInt32))\n\tbTrue := true\n\ttestCases := []struct {\n\t\tvolume api.Volume\n\t}{\n\t\t{\n\t\t\tvolume: api.Volume{\n\t\t\t\tName: rand.String(16),\n\t\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\t\tEmptyDir: &api.EmptyDir{\n\t\t\t\t\t\tMedium: api.StorageMediumMemory,\n\t\t\t\t\t\tSizeLimit: int64(rand.Intn(math.MaxInt64)),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tvolume: api.Volume{\n\t\t\t\tName: rand.String(16),\n\t\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\t\tConfigMap: &api.ConfigMapVolumeSource{\n\t\t\t\t\t\tItems: []api.KeyToPath{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey: rand.String(8),\n\t\t\t\t\t\t\t\tPath: fmt.Sprintf(\"/var/run/%s\", rand.String(8)),\n\t\t\t\t\t\t\t\tMode: &i32,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDefaultMode: &i32,\n\t\t\t\t\t\tOptional: &bTrue,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tvolume: api.Volume{\n\t\t\t\tName: rand.String(16),\n\t\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\t\tSecret: &api.SecretVolumeSource{\n\t\t\t\t\t\tSecretName: rand.String(16),\n\t\t\t\t\t\tItems: []api.KeyToPath{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey: rand.String(8),\n\t\t\t\t\t\t\t\tPath: fmt.Sprintf(\"/var/run/%s\", rand.String(8)),\n\t\t\t\t\t\t\t\tMode: &i32,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDefaultMode: &i32,\n\t\t\t\t\t\tOptional: &bTrue,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tvolume: api.Volume{\n\t\t\t\tName: rand.String(16),\n\t\t\t\tVolumeSource: api.VolumeSource{\n\t\t\t\t\tHostPath: &api.HostPathVolumeSource{\n\t\t\t\t\t\tPath: rand.String(16),\n\t\t\t\t\t\tType: hostPathTypePtr(api.HostPathDirectoryOrCreate),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tc := range testCases {\n\t\tvol := milpaToK8sVolume(tc.volume)\n\t\tassert.NotNil(t, vol)\n\t\tassert.Equal(t, tc.volume.Name, vol.Name)\n\t\tif tc.volume.EmptyDir != nil {\n\t\t\tassert.NotNil(t, vol.EmptyDir)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tstring(tc.volume.EmptyDir.Medium),\n\t\t\t\tstring(vol.EmptyDir.Medium),\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.EmptyDir.SizeLimit,\n\t\t\t\tvol.EmptyDir.SizeLimit.Value(),\n\t\t\t)\n\t\t}\n\t\tif tc.volume.ConfigMap != nil {\n\t\t\tassert.NotNil(t, vol.ConfigMap)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.ConfigMap.Name,\n\t\t\t\tvol.ConfigMap.Name,\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.ConfigMap.DefaultMode,\n\t\t\t\tvol.ConfigMap.DefaultMode,\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.ConfigMap.Optional,\n\t\t\t\tvol.ConfigMap.Optional,\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tlen(tc.volume.ConfigMap.Items),\n\t\t\t\tlen(vol.ConfigMap.Items),\n\t\t\t)\n\t\t\tfor _, item := range tc.volume.ConfigMap.Items {\n\t\t\t\tktp := v1.KeyToPath{\n\t\t\t\t\tKey: item.Key,\n\t\t\t\t\tPath: item.Path,\n\t\t\t\t\tMode: item.Mode,\n\t\t\t\t}\n\t\t\t\tassert.Contains(t, vol.ConfigMap.Items, ktp)\n\t\t\t}\n\t\t}\n\t\tif tc.volume.Secret != nil {\n\t\t\tassert.NotNil(t, vol.Secret)\n\t\t\tassert.Equal(t, tc.volume.Secret.SecretName, vol.Secret.SecretName)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.Secret.DefaultMode,\n\t\t\t\tvol.Secret.DefaultMode,\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\ttc.volume.Secret.Optional,\n\t\t\t\tvol.Secret.Optional,\n\t\t\t)\n\t\t\tassert.Equal(\n\t\t\t\tt,\n\t\t\t\tlen(tc.volume.Secret.Items),\n\t\t\t\tlen(vol.Secret.Items),\n\t\t\t)\n\t\t\tfor _, item := range tc.volume.Secret.Items {\n\t\t\t\tktp := v1.KeyToPath{\n\t\t\t\t\tKey: item.Key,\n\t\t\t\t\tPath: item.Path,\n\t\t\t\t\tMode: item.Mode,\n\t\t\t\t}\n\t\t\t\tassert.Contains(t, vol.Secret.Items, ktp)\n\t\t\t}\n\t\t}\n\t\tif tc.volume.HostPath != nil {\n\t\t\tassert.NotNil(t, vol.HostPath)\n\t\t\tassert.Equal(t, tc.volume.HostPath.Path, vol.HostPath.Path)\n\t\t\tif tc.volume.HostPath.Type != nil {\n\t\t\t\tassert.NotNil(t, vol.HostPath.Type)\n\t\t\t\tassert.Equal(\n\t\t\t\t\tt,\n\t\t\t\t\tstring(*tc.volume.HostPath.Type),\n\t\t\t\t\tstring(*vol.HostPath.Type))\n\t\t\t} else {\n\t\t\t\tassert.Nil(t, vol.HostPath.Type)\n\t\t\t}\n\t\t}\n\t\tmilpaVolume := k8sToMilpaVolume(*vol)\n\t\tassert.Equal(t, tc.volume, *milpaVolume)\n\t}\n}", "func DecodeGrpcRespWorkloadIntfSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func (ctl *Ctl) SwitchSpec(createOpsSightSpecType string) error {\n\tswitch createOpsSightSpecType {\n\tcase \"empty\":\n\t\tctl.Spec = &opssightv1.OpsSightSpec{}\n\tcase \"disabledBlackduck\":\n\t\tctl.Spec = crddefaults.GetOpsSightDefaultValueWithDisabledHub()\n\tcase \"default\":\n\t\tctl.Spec = crddefaults.GetOpsSightDefaultValue()\n\tdefault:\n\t\treturn fmt.Errorf(\"OpsSight Spec Type %s does not match: empty, disabledBlackduck, default\", createOpsSightSpecType)\n\t}\n\treturn nil\n}", "func HelpForExitCodes() ExitCode {\n\tlog.Logf(`bytemark exit code list:\n\nExit code ranges:\n All these ranges are inclusive (i.e. 0-99 means numbers from 0 to 99, including 0 and 99.)\n\n 0- 49: local problems\n 50-149: problem talking to auth.\n 150-249: problem talking to Bytemark.\n 250-255: interrupts & signals\n\n Exit codes between 50 and 249 with the same tens and units have the same meaning but for a different endpoint\n\n 0 - 49 Exit codes:\n\n 0\n\tNothing went wrong and I feel great!\n 1\n \tProblem with the client itself\n 3\n\tCouldn't read a file from config directory\n 4\n\tCouldn't write a file to config directory\n 5\n\tThe user caused the program to exit (usually by saying \"no\" to Yes/no prompts)\t\n 6\n\tThe user requested a non-empty group be deleted\n 7\n\tThe program was called with malformed arguments\n 8\n\tAttempting to execute a subprocess failed\n\n 50 - 249 Exit codes:\n\n 50 / 150\n Unable to establish a connection to auth/API endpoint\n \n 51 / 151\n Auth endpoint reported an internal error\n \n 52 / 152\n Unable to parse output from auth endpoint (probably implies a protocol mismatch - try updating bytemark)\n\n 53\n\tYour credentials were rejected for containing invalid characters or fields.\n\n 54\n\tYour credentials did not match any user on file - check you entered them correctly\n\n 155\n\tYour user account doesn't have authorisation to perform that action\n\n 156\n Something couldn't be found by the API server. This could be due to the following reasons:\n * It doesn't exist\n\t * Your user account doesn't have authorisation to see it\n\t * Protocol mismatch between the Bytemark endpoint and our client (i.e. client out of date).\n\n 149 / 249\n\n An unknown error fell out of the auth / API library.\n\n250 - 255 Exit codes:\n\n 255\n\tTrapped an interrupt signal, so exited.\n`)\n\treturn ExitCodeUsageDisplayed\n}", "func (o *Onpar) Spec(name string, f interface{}) {\n\t_, fileName, lineNumber, _ := runtime.Caller(o.callCount)\n\tv := reflect.ValueOf(f)\n\tspec := specInfo{\n\t\tname: name,\n\t\tf: &v,\n\t\tft: reflect.TypeOf(f),\n\t\tfileName: fileName,\n\t\tlineNumber: lineNumber,\n\t}\n\to.current.specs = append(o.current.specs, spec)\n}", "func (o PodSecurityPolicyPatchOutput) Spec() PodSecurityPolicySpecPatchPtrOutput {\n\treturn o.ApplyT(func(v *PodSecurityPolicyPatch) PodSecurityPolicySpecPatchPtrOutput { return v.Spec }).(PodSecurityPolicySpecPatchPtrOutput)\n}", "func (o MachineInstanceTypeOutput) Spec() MachineInstanceSpecPtrOutput {\n\treturn o.ApplyT(func(v MachineInstanceType) *MachineInstanceSpec { return v.Spec }).(MachineInstanceSpecPtrOutput)\n}", "func specPlatform(p *regpkg.Platform) *spec.Platform {\n\treturn &spec.Platform{\n\t\tArchitecture: p.Architecture,\n\t\tOS: p.OS,\n\t\tOSVersion: p.OSVersion,\n\t\tOSFeatures: p.OSFeatures,\n\t\tVariant: p.Variant,\n\t}\n}", "func TestSomething(t *testing.T) {\n\tfSys := filesys.MakeFsInMemory()\n\tb := krusty.MakeKustomizer(fSys, krusty.MakeDefaultOptions())\n\t_, err := b.Run(\"noSuchThing\")\n\tif err == nil {\n\t\tt.Fatalf(\"expected error\")\n\t}\n\tif err.Error() != \"'noSuchThing' doesn't exist\" {\n\t\tt.Fatalf(\"unexpected error: %v\", err)\n\t}\n}", "func ReconcileK8SVersionInSpec(rawKluster []byte, current *v1.Kluster, clients config.Clients, factories config.Factories) (err error) {\n\n\tif current.Spec.Version != current.Status.ApiserverVersion {\n\t\tif current.Status.ApiserverVersion == \"\" {\n\t\t\treturn errors.New(\"No kubernetes version found in status\")\n\t\t}\n\t\tcurrent.Spec.Version = current.Status.ApiserverVersion\n\t}\n\n\treturn\n}", "func (o LookupEntryResultOutput) ServiceSpec() GoogleCloudDatacatalogV1ServiceSpecResponseOutput {\n\treturn o.ApplyT(func(v LookupEntryResult) GoogleCloudDatacatalogV1ServiceSpecResponse { return v.ServiceSpec }).(GoogleCloudDatacatalogV1ServiceSpecResponseOutput)\n}", "func (s *BasePlSqlParserListener) ExitType_function_spec(ctx *Type_function_specContext) {}", "func platformSpecficStat(name string) (Timespec, error) {\n\treturn Timespec{}, nil\n}", "func (o JupyterlabTypeOutput) Spec() JupyterlabSpecPtrOutput {\n\treturn o.ApplyT(func(v JupyterlabType) *JupyterlabSpec { return v.Spec }).(JupyterlabSpecPtrOutput)\n}", "func tracefsProbe(typ probeType, symbol, path string, offset uint64, pid int, ret bool) (*perfEvent, error) {\n\t// Generate a random string for each trace event we attempt to create.\n\t// This value is used as the 'group' token in tracefs to allow creating\n\t// multiple kprobe trace events with the same name.\n\tgroup, err := randomGroup(\"ebpf\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"randomizing group name: %w\", err)\n\t}\n\n\t// Before attempting to create a trace event through tracefs,\n\t// check if an event with the same group and name already exists.\n\t// Kernels 4.x and earlier don't return os.ErrExist on writing a duplicate\n\t// entry, so we need to rely on reads for detecting uniqueness.\n\t_, err = getTraceEventID(group, symbol)\n\tif err == nil {\n\t\treturn nil, fmt.Errorf(\"trace event already exists: %s/%s\", group, symbol)\n\t}\n\tif err != nil && !errors.Is(err, os.ErrNotExist) {\n\t\treturn nil, fmt.Errorf(\"checking trace event %s/%s: %w\", group, symbol, err)\n\t}\n\n\t// Create the [k,u]probe trace event using tracefs.\n\tif err := createTraceFSProbeEvent(typ, group, symbol, path, offset, ret); err != nil {\n\t\treturn nil, fmt.Errorf(\"creating probe entry on tracefs: %w\", err)\n\t}\n\n\t// Get the newly-created trace event's id.\n\ttid, err := getTraceEventID(group, symbol)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"getting trace event id: %w\", err)\n\t}\n\n\t// Kprobes are ephemeral tracepoints and share the same perf event type.\n\tfd, err := openTracepointPerfEvent(tid, pid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &perfEvent{\n\t\tfd: fd,\n\t\tgroup: group,\n\t\tname: symbol,\n\t\ttracefsID: tid,\n\t\ttyp: typ.PerfEventType(ret),\n\t}, nil\n}", "func returnFsProvider(ctor *ConstructSecret) *provider {\n\tprov := getFsProvider(ctor)\n\treturn &provider{\n\t\tSecret: prov,\n\t\tlogger: prov.logger,\n\t\tprovider: \"go-home\",\n\t}\n}", "func (o KubernetesClusterTypeOutput) Spec() KubernetesClusterSpecPtrOutput {\n\treturn o.ApplyT(func(v KubernetesClusterType) *KubernetesClusterSpec { return v.Spec }).(KubernetesClusterSpecPtrOutput)\n}", "func (r *edgeClusterServiceResolver) Spec(ctx context.Context) (edgecluster.ServiceSpecResolverContract, error) {\n\treturn r.resolverCreator.NewServiceSpecResolver(ctx, r.service.Spec)\n}", "func (o *PutMeInstallationTemplateTemplateNamePartitionSchemeSchemeNamePartitionMountpointDefault) Code() int {\n\treturn o._statusCode\n}", "func DecodeGrpcRespWorkloadSpec(ctx context.Context, response interface{}) (interface{}, error) {\n\treturn response, nil\n}", "func TestAddenda99MakeReturnCodeDict(t *testing.T) {\n\tcodes := makeReturnCodeDict()\n\t// check if known code is present\n\t_, prs := codes[\"R01\"]\n\tif !prs {\n\t\tt.Error(\"Return Code R01 was not found in the ReturnCodeDict\")\n\t}\n\t// check if invalid code is present\n\t_, prs = codes[\"ABC\"]\n\tif prs {\n\t\tt.Error(\"Valid return for an invalid return code key\")\n\t}\n}", "func (f ProberFunc) Probe(ctx context.Context) (Result, string, error) {\n\treturn f(ctx)\n}", "func pmuKprobe(symbol string, ret bool) (*perfEvent, error) {\n\treturn pmuProbe(kprobeType, symbol, \"\", 0, perfAllThreads, ret)\n}", "func (o ReplicaSetPatchOutput) Spec() ReplicaSetSpecPatchPtrOutput {\n\treturn o.ApplyT(func(v *ReplicaSetPatch) ReplicaSetSpecPatchPtrOutput { return v.Spec }).(ReplicaSetSpecPatchPtrOutput)\n}", "func (p Probe) Spec() *v1alpha1.Probe {\n\treturn p.spec\n}", "func (s *Specs) findSpec(metricName string) (SpecDef, error) {\n\tvar spec SpecDef\n\n\tres := strings.SplitN(metricName, \"_\", 2)\n\tif len(res) < 2 {\n\t\treturn spec, fmt.Errorf(\"metric: %s has no suffix to identify the entity\", metricName)\n\t}\n\tserviceName := res[0]\n\n\tvar ok bool\n\tif spec, ok = s.SpecsByName[serviceName]; !ok {\n\t\treturn spec, fmt.Errorf(\"no spec files for service: %s\", serviceName)\n\t}\n\n\treturn spec, nil\n}", "func TestAuthenticatedRequest(t *testing.T) {\n\tvar e error\n\tprivateKey, e = readPrivateKey()\n\tif e != nil {\n\t\tpanic(e)\n\t}\n\tConvey(\"Simple authenticated requests\", t, func() {\n\t\tConvey(\"Authenticated GET to / path should return a 200 response\", func() {\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/\", jwt.MapClaims{\"foo\": \"bar\"}, nil)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is not specified\", func() {\n\t\t\tvar expectedAlgorithm jwt.SigningMethod = nil\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 200 response if expected algorithm is correct\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodHS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusOK)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(responseString, ShouldEqual, `{\"text\":\"bar\"}`)\n\t\t})\n\t\tConvey(\"Authenticated GET to /protected path should return a 401 response if algorithm is not expected one\", func() {\n\t\t\texpectedAlgorithm := jwt.SigningMethodRS256\n\t\t\tw := makeAuthenticatedRequest(\"GET\", \"/protected\", jwt.MapClaims{\"foo\": \"bar\"}, expectedAlgorithm)\n\t\t\tSo(w.Code, ShouldEqual, http.StatusUnauthorized)\n\t\t\tresponseBytes, err := ioutil.ReadAll(w.Body)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tresponseString := string(responseBytes)\n\t\t\t// check that the encoded data in the jwt was properly returned as json\n\t\t\tSo(strings.TrimSpace(responseString), ShouldEqual, \"Expected RS256 signing method but token specified HS256\")\n\t\t})\n\t})\n}", "func createDefaultSpec(app apptypes.AppType, b *troubleshootv1beta2.SupportBundle, opts types.TroubleshootOptions, namespacesToCollect []string, namespacesToAnalyze []string, clientset *kubernetes.Clientset) (*troubleshootv1beta2.SupportBundle, error) {\n\tsupportBundle, err := staticspecs.GetDefaultSpec()\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to load default support bundle spec: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tvar imageName string\n\tvar pullSecret *troubleshootv1beta2.ImagePullSecrets\n\n\tif clientset != nil {\n\t\timageName, pullSecret, err = getImageAndSecret(context.TODO(), clientset)\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Failed to get kotsadm image and secret: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif imageName != \"\" {\n\t\tsupportBundle = populateImages(supportBundle, imageName, pullSecret)\n\t}\n\n\tisKurl, err := kurl.IsKurl(clientset)\n\tif err != nil {\n\t\tlogger.Errorf(\"Failed to check if cluster is kurl: %v\", err)\n\t}\n\n\tif isKurl {\n\t\tkurlSupportBunlde, err := staticspecs.GetKurlSpec()\n\t\tif err != nil {\n\t\t\tlogger.Errorf(\"Failed to load kurl support bundle spec: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\n\t\tsupportBundle.Spec.Collectors = append(supportBundle.Spec.Collectors, kurlSupportBunlde.Spec.Collectors...)\n\t\tsupportBundle.Spec.Analyzers = append(supportBundle.Spec.Analyzers, kurlSupportBunlde.Spec.Analyzers...)\n\t}\n\n\tsupportBundle = addDefaultDynamicTroubleshoot(supportBundle, app, imageName, pullSecret)\n\tsupportBundle = addAfterCollectionSpec(app, supportBundle, opts)\n\tsupportBundle = populateNamespaces(supportBundle, namespacesToCollect, namespacesToAnalyze)\n\n\treturn supportBundle, nil\n}", "func (o AppProjectTypeOutput) Spec() AppProjectSpecOutput {\n\treturn o.ApplyT(func(v AppProjectType) AppProjectSpec { return v.Spec }).(AppProjectSpecOutput)\n}", "func CallK8SFuncByName(module string, params ...string) (models.FnResult, error) {\n\tswitch strings.ToLower(module) {\n\tcase Config:\n\t\tcontext := \"\"\n\t\tif len(params) > 0 && params[0] != \"\" {\n\t\t\tcontext = params[0]\n\t\t}\n\t\tconfig, err := GetK8SConfigFromSystem(context)\n\t\tif err != nil {\n\t\t\tutil.Verbose(\"[k8s] Error while processing function [%s] is: %v\\n\", module, err)\n\t\t\t// handle K8S configuration errors gracefully\n\t\t\treturn &K8SFnResult{}, nil\n\t\t}\n\t\treturn &config, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"%s is not a valid Kubernetes module\", module)\n\t}\n}", "func (o Iperf3TypeOutput) Spec() Iperf3SpecPtrOutput {\n\treturn o.ApplyT(func(v Iperf3Type) *Iperf3Spec { return v.Spec }).(Iperf3SpecPtrOutput)\n}", "func Kerberos(authFn func(context.Context) (Auth, error)) sasl.Mechanism {\n\treturn k(authFn)\n}", "func (o NetworkPolicyOutput) Spec() NetworkPolicySpecOutput {\n\treturn o.ApplyT(func(v *NetworkPolicy) NetworkPolicySpecOutput { return v.Spec }).(NetworkPolicySpecOutput)\n}", "func (self *Platform) ValidateSpec(spec *pb.ChaincodeSpec) error {\n\treturn nil\n}", "func (in *ServiceFence) GetSpec() map[string]interface{} {\n\treturn nil\n}", "func (spec *AliyunInstanceTypeSpec) compareAndGetMinimumInstanceTypeSpec(rival AliyunInstanceTypeSpec) {\n\tspecScore := getInstanceTypeSpecScore(*spec)\n\trivalScore := getInstanceTypeSpecScore(rival)\n\tif rivalScore < specScore || spec.InstanceTypeID == \"\" {\n\t\tspec.CPUCoreCount = rival.CPUCoreCount\n\t\tspec.EniPrivateIPAddressQuantity = rival.EniPrivateIPAddressQuantity\n\t\tspec.EniQuantity = rival.EniQuantity\n\t\tspec.GPUAmount = rival.GPUAmount\n\t\tspec.GPUSpec = rival.GPUSpec\n\t\tspec.InstanceFamilyLevel = rival.InstanceFamilyLevel\n\t\tspec.InstanceTypeFamily = rival.InstanceTypeFamily\n\t\tspec.InstanceTypeID = rival.InstanceTypeID\n\t\tspec.LocalStorageCategory = rival.LocalStorageCategory\n\t\tspec.MemorySize = rival.MemorySize\n\t}\n}", "func SophisticatedResponder(w http.ResponseWriter, httpRequest *http.Request, fakeRequest *Request) {\n\tstatusCode := fakeRequest.Response.StatusCode\n\tbody := fakeRequest.Response.BodyBuffer\n\tresponseHeader := fakeRequest.Response.Header\n\n\tif len(fakeRequest.Header) > 0 {\n\t\ts, b, err := validateHeaders(fakeRequest.Header, httpRequest.Header)\n\t\tif err != nil {\n\t\t\tstatusCode = s\n\t\t\tbody = []byte(b)\n\t\t}\n\t}\n\tif len(fakeRequest.Cookies()) > 0 {\n\t\ts, b, err := validateCookies(fakeRequest.Cookies(), httpRequest.Cookies())\n\t\tif err != nil {\n\t\t\tstatusCode = s\n\t\t\tbody = []byte(b)\n\t\t}\n\t}\n\tif (len(responseHeader)) > 0 {\n\t\tfor k := range fakeRequest.Response.Header {\n\t\t\tw.Header().Add(k, responseHeader.Get(k))\n\t\t}\n\t}\n\tif statusCode > 0 {\n\t\tw.WriteHeader(statusCode)\n\t}\n\tserviceResponses := \"\"\n\tif len(fakeRequest.ServiceEndpoints) > 0 {\n\t\tfor _, uri := range fakeRequest.ServiceEndpoints {\n\t\t\tstatus, body, err := invokeServiceEndpoint(uri, httpRequest.Header)\n\t\t\tif err == nil {\n\t\t\t\tserviceResponses += (uri + \": \")\n\t\t\t\tserviceResponses += (status + \": \")\n\t\t\t\tserviceResponses += (body)\n\t\t\t\tserviceResponses += \"<br>\"\n\t\t\t}\n\t\t}\n\t}\n\tif (len(body)) > 0 {\n\t\tb := string(body)\n\t\tif len(fakeRequest.InjectionKeys) > 0 {\n\t\t\tfor _, k := range fakeRequest.InjectionKeys {\n\t\t\t\tif k == \"path\" {\n\t\t\t\t\tbody = []byte(fmt.Sprintf(b, strings.TrimPrefix(httpRequest.URL.Path, \"/\")))\n\t\t\t\t\tb = string(body)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(serviceResponses) > 0 {\n\t\t\tb += serviceResponses\n\t\t}\n\n\t\tif fakeRequest.RenderHTML {\n\t\t\tb = \"<html><head><title>fakeserver</title></head><body>\" + b + \"</body></html>\"\n\t\t}\n\n\t\tw.Write([]byte(b))\n\t}\n}", "func (o PodSchedulingOutput) Spec() PodSchedulingSpecOutput {\n\treturn o.ApplyT(func(v *PodScheduling) PodSchedulingSpecOutput { return v.Spec }).(PodSchedulingSpecOutput)\n}", "func (c *FakeKconfigs) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1alpha1.Kconfig, err error) {\n\tobj, err := c.Fake.\n\t\tInvokes(testing.NewPatchSubresourceAction(kconfigsResource, c.ns, name, pt, data, subresources...), &v1alpha1.Kconfig{})\n\n\tif obj == nil {\n\t\treturn nil, err\n\t}\n\treturn obj.(*v1alpha1.Kconfig), err\n}", "func defaultFmtFilterErr(f Filter) string {\n\treturn fmt.Sprintf(\"filter fail code '%d'\", f)\n}", "func (o ValidatingAdmissionPolicyPatchTypeOutput) Spec() ValidatingAdmissionPolicySpecPatchPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyPatchType) *ValidatingAdmissionPolicySpecPatch { return v.Spec }).(ValidatingAdmissionPolicySpecPatchPtrOutput)\n}", "func specs(i interface{}) {\n\tfmt.Println(i)\n}", "func testSpec() *specs.Spec {\n\treturn &specs.Spec{\n\t\t// The host filesystem root is the sandbox root.\n\t\tRoot: &specs.Root{\n\t\t\tPath: \"/\",\n\t\t\tReadonly: true,\n\t\t},\n\t\tProcess: &specs.Process{\n\t\t\tArgs: []string{\"/bin/true\"},\n\t\t},\n\t}\n}", "func (s *BasePlSqlParserListener) ExitC_spec(ctx *C_specContext) {}", "func (o ValidatingAdmissionPolicyTypeOutput) Spec() ValidatingAdmissionPolicySpecPtrOutput {\n\treturn o.ApplyT(func(v ValidatingAdmissionPolicyType) *ValidatingAdmissionPolicySpec { return v.Spec }).(ValidatingAdmissionPolicySpecPtrOutput)\n}", "func Failf(code int, tpl string, v ...any) ErrorR {\n\treturn &errorR{code: code, msg: fmt.Sprintf(tpl, v...)}\n}", "func MachinePoolSpec(ctx context.Context, inputGetter func() MachinePoolSpecInput) {\n\tinput := inputGetter()\n\tExpect(input.E2EConfig).ToNot(BeNil(), \"Invalid argument. input.E2EConfig can't be nil\")\n\tExpect(input.ConfigClusterFn).ToNot(BeNil(), \"Invalid argument. input.ConfigClusterFn can't be nil\")\n\tExpect(input.BootstrapClusterProxy).ToNot(BeNil(), \"Invalid argument. input.BootstrapClusterProxy can't be nil\")\n\tExpect(input.AWSSession).ToNot(BeNil(), \"Invalid argument. input.AWSSession can't be nil\")\n\tExpect(input.Namespace).NotTo(BeNil(), \"Invalid argument. input.Namespace can't be nil\")\n\tExpect(input.ClusterName).ShouldNot(BeEmpty(), \"Invalid argument. input.ClusterName can't be empty\")\n\tExpect(input.Flavor).ShouldNot(BeEmpty(), \"Invalid argument. input.Flavor can't be empty\")\n\n\tginkgo.By(fmt.Sprintf(\"getting cluster with name %s\", input.ClusterName))\n\tcluster := framework.GetClusterByName(ctx, framework.GetClusterByNameInput{\n\t\tGetter: input.BootstrapClusterProxy.GetClient(),\n\t\tNamespace: input.Namespace.Name,\n\t\tName: input.ClusterName,\n\t})\n\tExpect(cluster).NotTo(BeNil(), \"couldn't find CAPI cluster\")\n\n\tginkgo.By(fmt.Sprintf(\"creating an applying the %s template\", input.Flavor))\n\tconfigCluster := input.ConfigClusterFn(input.ClusterName, input.Namespace.Name)\n\tconfigCluster.Flavor = input.Flavor\n\tconfigCluster.WorkerMachineCount = pointer.Int64(1)\n\tworkloadClusterTemplate := shared.GetTemplate(ctx, configCluster)\n\tif input.UsesLaunchTemplate {\n\t\tuserDataTemplate := `#!/bin/bash\n/etc/eks/bootstrap.sh %s \\\n --container-runtime containerd\n`\n\t\teksClusterName := getEKSClusterName(input.Namespace.Name, input.ClusterName)\n\t\tuserData := fmt.Sprintf(userDataTemplate, eksClusterName)\n\t\tuserDataEncoded := base64.StdEncoding.EncodeToString([]byte(userData))\n\t\tworkloadClusterTemplate = []byte(strings.ReplaceAll(string(workloadClusterTemplate), \"USER_DATA\", userDataEncoded))\n\t}\n\tginkgo.By(string(workloadClusterTemplate))\n\tginkgo.By(fmt.Sprintf(\"Applying the %s cluster template yaml to the cluster\", configCluster.Flavor))\n\terr := input.BootstrapClusterProxy.Apply(ctx, workloadClusterTemplate)\n\tExpect(err).ShouldNot(HaveOccurred())\n\n\tginkgo.By(\"Waiting for the machine pool to be running\")\n\tmp := framework.DiscoveryAndWaitForMachinePools(ctx, framework.DiscoveryAndWaitForMachinePoolsInput{\n\t\tLister: input.BootstrapClusterProxy.GetClient(),\n\t\tGetter: input.BootstrapClusterProxy.GetClient(),\n\t\tCluster: cluster,\n\t}, input.E2EConfig.GetIntervals(\"\", \"wait-worker-nodes\")...)\n\tExpect(len(mp)).To(Equal(1))\n\n\tginkgo.By(\"Check the status of the node group\")\n\teksClusterName := getEKSClusterName(input.Namespace.Name, input.ClusterName)\n\tif input.ManagedMachinePool {\n\t\tvar nodeGroupName string\n\t\tif input.UsesLaunchTemplate {\n\t\t\tnodeGroupName = getEKSNodegroupWithLaunchTemplateName(input.Namespace.Name, input.ClusterName)\n\t\t} else {\n\t\t\tnodeGroupName = getEKSNodegroupName(input.Namespace.Name, input.ClusterName)\n\t\t}\n\t\tverifyManagedNodeGroup(eksClusterName, nodeGroupName, true, input.AWSSession)\n\t} else {\n\t\tasgName := getASGName(input.ClusterName)\n\t\tverifyASG(eksClusterName, asgName, true, input.AWSSession)\n\t}\n\n\tif input.IncludeScaling { // TODO (richardcase): should this be a separate spec?\n\t\tginkgo.By(\"Scaling the machine pool up\")\n\t\tframework.ScaleMachinePoolAndWait(ctx, framework.ScaleMachinePoolAndWaitInput{\n\t\t\tClusterProxy: input.BootstrapClusterProxy,\n\t\t\tCluster: cluster,\n\t\t\tReplicas: 2,\n\t\t\tMachinePools: mp,\n\t\t\tWaitForMachinePoolToScale: input.E2EConfig.GetIntervals(\"\", \"wait-worker-nodes\"),\n\t\t})\n\n\t\tginkgo.By(\"Scaling the machine pool down\")\n\t\tframework.ScaleMachinePoolAndWait(ctx, framework.ScaleMachinePoolAndWaitInput{\n\t\t\tClusterProxy: input.BootstrapClusterProxy,\n\t\t\tCluster: cluster,\n\t\t\tReplicas: 1,\n\t\t\tMachinePools: mp,\n\t\t\tWaitForMachinePoolToScale: input.E2EConfig.GetIntervals(\"\", \"wait-worker-nodes\"),\n\t\t})\n\t}\n\n\tif input.Cleanup {\n\t\tdeleteMachinePool(ctx, deleteMachinePoolInput{\n\t\t\tDeleter: input.BootstrapClusterProxy.GetClient(),\n\t\t\tMachinePool: mp[0],\n\t\t})\n\n\t\twaitForMachinePoolDeleted(ctx, waitForMachinePoolDeletedInput{\n\t\t\tGetter: input.BootstrapClusterProxy.GetClient(),\n\t\t\tMachinePool: mp[0],\n\t\t}, input.E2EConfig.GetIntervals(\"\", \"wait-delete-machine-pool\")...)\n\t}\n}", "func (o ApplicationSpecSourceOutput) Kustomize() ApplicationSpecSourceKustomizePtrOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSource) *ApplicationSpecSourceKustomize { return v.Kustomize }).(ApplicationSpecSourceKustomizePtrOutput)\n}", "func decodeSpecCached() func() ([]byte, error) {\n\tdata, err := decodeSpec()\n\treturn func() ([]byte, error) {\n\t\treturn data, err\n\t}\n}", "func decodeSpecCached() func() ([]byte, error) {\n\tdata, err := decodeSpec()\n\treturn func() ([]byte, error) {\n\t\treturn data, err\n\t}\n}", "func (f *FaasController) DefaultSpec() interface{} {\n\treturn &spec.Admin{\n\t\tSyncInterval: \"10s\",\n\t\tProvider: spec.ProviderKnative,\n\t\tKnative: &spec.Knative{\n\t\t\tNamespace: \"default\",\n\t\t\tTimeout: \"2s\",\n\t\t},\n\t}\n}", "func (suite *ControllerTestSuite) TestPingWithGenericMimeType() {\n\tm := &v1.ScannerAdapterMetadata{\n\t\tScanner: &v1.Scanner{\n\t\t\tName: \"Trivy\",\n\t\t\tVendor: \"Harbor\",\n\t\t\tVersion: \"0.1.0\",\n\t\t},\n\t\tCapabilities: []*v1.ScannerCapability{{\n\t\t\tConsumesMimeTypes: []string{\n\t\t\t\tv1.MimeTypeOCIArtifact,\n\t\t\t\tv1.MimeTypeDockerArtifact,\n\t\t\t},\n\t\t\tProducesMimeTypes: []string{\n\t\t\t\tv1.MimeTypeGenericVulnerabilityReport,\n\t\t\t\tv1.MimeTypeRawReport,\n\t\t\t},\n\t\t}},\n\t\tProperties: v1.ScannerProperties{\n\t\t\t\"extra\": \"testing\",\n\t\t},\n\t}\n\tmc := &v1testing.Client{}\n\tmc.On(\"GetMetadata\").Return(m, nil)\n\n\tmcp := &v1testing.ClientPool{}\n\tmocktesting.OnAnything(mcp, \"Get\").Return(mc, nil)\n\tsuite.c = &basicController{\n\t\tmanager: suite.mMgr,\n\t\tproMetaMgr: suite.mMeta,\n\t\tclientPool: mcp,\n\t}\n\tmeta, err := suite.c.Ping(context.TODO(), suite.sample)\n\trequire.NoError(suite.T(), err)\n\tsuite.NotNil(meta)\n}", "func (o *PatchHyperflexSoftwareVersionPoliciesMoidDefault) Code() int {\n\treturn o._statusCode\n}", "func (group *ResourceGroup) GetSpec() genruntime.ConvertibleSpec {\n\treturn &group.Spec\n}", "func (group *ResourceGroup) GetSpec() genruntime.ConvertibleSpec {\n\treturn &group.Spec\n}" ]
[ "0.58376807", "0.54041034", "0.530006", "0.51623124", "0.50776535", "0.49678814", "0.49371037", "0.49155542", "0.48339552", "0.48215085", "0.48215085", "0.47773156", "0.47666517", "0.47654554", "0.4759973", "0.47592518", "0.4759031", "0.47582752", "0.47443298", "0.4742957", "0.47205797", "0.46707952", "0.46583176", "0.46428025", "0.46418655", "0.46257752", "0.46047652", "0.45778954", "0.4574188", "0.45420617", "0.4513247", "0.45058227", "0.45038596", "0.45013508", "0.44826669", "0.4482601", "0.4475436", "0.44311413", "0.44107786", "0.4407971", "0.4400045", "0.43987265", "0.4395966", "0.43938065", "0.4393611", "0.43918744", "0.439121", "0.43910748", "0.43830547", "0.4377177", "0.43748704", "0.43704015", "0.43673575", "0.43672013", "0.4363561", "0.4360916", "0.43596956", "0.4351244", "0.4342805", "0.43355554", "0.43351185", "0.43203914", "0.43145743", "0.43118268", "0.42949092", "0.4289581", "0.4286891", "0.42849037", "0.4277477", "0.4276383", "0.42721194", "0.42596364", "0.42498258", "0.42419603", "0.42364973", "0.42345497", "0.422855", "0.42283222", "0.4222081", "0.42204", "0.42169955", "0.42139375", "0.42130938", "0.42104843", "0.4209438", "0.42084607", "0.42049974", "0.42001295", "0.41997498", "0.41992742", "0.41957885", "0.4194726", "0.4191174", "0.41869366", "0.41869366", "0.4185783", "0.4184194", "0.41826993", "0.4182557", "0.4182557" ]
0.83963245
0
String returns the string representation
func (s DeleteSubscriptionDefinitionInput) String() string { return awsutil.Prettify(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (s CreateQuickConnectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponse) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Addshifttraderequest) String() string {\n \n \n \n \n o.AcceptableIntervals = []string{\"\"} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (i Info) String() string {\n\ts, _ := i.toJSON()\n\treturn s\n}", "func (o *Botversionsummary) String() string {\n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (s CreateDataLakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSolutionVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Adjustablelivespeakerdetection) String() string {\n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateRateBasedRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (s RestoreFromRecoveryPointOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateWaveOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponseResult) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienia) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (i *Info) String() string {\n\tb, _ := json.Marshal(i)\n\treturn string(b)\n}", "func (s ProcessingFeatureStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ExportProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r RoomOccupancies) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Coretype) String() string {\n \n \n \n \n \n o.ValidationFields = []string{\"\"} \n \n o.ItemValidationFields = []string{\"\"} \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateLayerOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Limitchangerequestdetails) String() string {\n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s NetworkPathComponentDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t Terms) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (s StartContactEvaluationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Interactionstatsalert) String() string {\n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Digitalcondition) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (r RoomOccupancy) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (d *Diagram) String() string { return toString(d) }", "func (o *Outboundroute) String() string {\n \n \n \n \n o.ClassificationTypes = []string{\"\"} \n \n \n o.ExternalTrunkBases = []Domainentityref{{}} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (p *Parms) String() string {\n\tout, _ := json.MarshalIndent(p, \"\", \"\\t\")\n\treturn string(out)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RUT) String() string {\n\treturn r.Format(DefaultFormatter)\n}", "func (s CreatePatchBaselineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Crossplatformpolicycreate) String() string {\n \n \n \n \n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s BotVersionLocaleDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestInitiated) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteMultiplexProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestReverted) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDocumentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateIntegrationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Commonruleconditions) String() string {\n o.Clauses = []Commonruleconditions{{}} \n o.Predicates = []Commonrulepredicate{{}} \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (t Test1s) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (o *Directrouting) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (s CreateContactFlowOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.7215058", "0.7215058", "0.72000957", "0.7199919", "0.7177383", "0.7166947", "0.7118059", "0.7087492", "0.70870787", "0.7079275", "0.70782894", "0.7067719", "0.7031721", "0.70269966", "0.7026298", "0.70251423", "0.7021565", "0.70164025", "0.701059", "0.7010184", "0.70022964", "0.6997043", "0.6996532", "0.6992619", "0.69909185", "0.69900763", "0.69862556", "0.6985364", "0.6975378", "0.69738907", "0.69624275", "0.6961772", "0.69603413", "0.69507927", "0.6946753", "0.69460964", "0.69460964", "0.6944943", "0.694029", "0.69369334", "0.69332623", "0.69287163", "0.692656", "0.6924643", "0.69216746", "0.69213074", "0.69181406", "0.6917802", "0.6911058", "0.69104654", "0.6909528", "0.690845", "0.690454", "0.6899065", "0.6896141", "0.6894107", "0.6894107", "0.6894107", "0.68921995", "0.68920684", "0.689124", "0.68893504", "0.688871", "0.6884391", "0.6882336", "0.6880731", "0.68767136", "0.68766147", "0.68766147", "0.68751997", "0.68735147", "0.68734384", "0.68731403", "0.6871602", "0.6869421", "0.68684965", "0.68677104", "0.68677104", "0.68677104", "0.68677104", "0.68673396", "0.68622416", "0.6862084", "0.6859391", "0.6857645", "0.6853781", "0.68523467", "0.6851581", "0.6846037", "0.6844023", "0.6843859", "0.68434954", "0.68419206", "0.68416274", "0.684033", "0.6839815", "0.68363225", "0.6835165", "0.68334675", "0.68327725", "0.6832733" ]
0.0
-1
Validate inspects the fields of the type to determine if they are valid.
func (s *DeleteSubscriptionDefinitionInput) Validate() error { invalidParams := aws.ErrInvalidParams{Context: "DeleteSubscriptionDefinitionInput"} if s.SubscriptionDefinitionId == nil { invalidParams.Add(aws.NewErrParamRequired("SubscriptionDefinitionId")) } if invalidParams.Len() > 0 { return invalidParams } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (f *InfoField) Validate() error {\n\tif err := f.BWCls.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif err := f.RLC.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif err := f.Idx.Validate(); err != nil {\n\t\treturn err\n\t}\n\tif err := f.PathType.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (f FieldSpec) Validate() error {\n\tif f.Name == \"\" {\n\t\treturn errors.New(\"Field name required\")\n\t}\n\n\tif f.Type == \"\" {\n\t\treturn errors.New(\"Field type required\")\n\t}\n\n\treturn nil\n}", "func (p *Pass) FieldsValid() bool {\n\tfmt.Printf(\"validating: \")\n\tvalid := true\n\tfor k, v := range *p {\n\t\tfmt.Printf(\"%v...\", k)\n\t\tv := isFieldValid(k, v)\n\t\tvalid = valid && v\n\t\tif v {\n\t\t\tfmt.Printf(\"VALID \")\n\t\t} else {\n\t\t\tfmt.Printf(\"INVALID \")\n\t\t}\n\t}\n\n\tfmt.Println(\"\")\n\treturn valid\n}", "func (m Type) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (m *TestFieldsEx2) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFieldType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateProjectID(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func Validate(instance interface{}) string {\n\tval := unwrap(reflect.ValueOf(instance))\n\ttyp := val.Type()\n\n\tif typ.Kind() != reflect.Struct {\n\t\tcore.DefaultLogger.Panic(\"The provided instance is not a struct\")\n\t}\n\n\tvar result []string\n\n\tfor i := 0; i < typ.NumField(); i++ {\n\t\tfield := typ.Field(i)\n\t\tfieldTag := field.Tag\n\t\tif len(fieldTag) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tfieldVal := val.Field(i)\n\t\tfieldKind := fieldVal.Kind()\n\t\tif !fieldVal.CanInterface() || fieldKind == reflect.Invalid {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar toEval []evalContext\n\t\tvar requiredCtx *evalContext\n\n\t\tfor _, v := range validators {\n\t\t\tif param, found := fieldTag.Lookup(v.key); found {\n\t\t\t\tctx := evalContext{validator: v, param: param}\n\n\t\t\t\tif v.key == required.key {\n\t\t\t\t\trequiredCtx = &ctx\n\t\t\t\t} else {\n\t\t\t\t\ttoEval = append(toEval, ctx)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif len(toEval) == 0 && requiredCtx == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tif requiredCtx == nil {\n\t\t\trequiredCtx = &evalContext{validator: required, param: \"true\"}\n\t\t}\n\n\t\tvar errors []string\n\t\teval := func(ctx evalContext) bool {\n\t\t\tif err := ctx.validator.fn(fieldVal, ctx.param); len(err) > 0 {\n\t\t\t\terrors = append(errors, err)\n\t\t\t\treturn false\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\tif eval(*requiredCtx) {\n\t\t\tfor _, ctx := range toEval {\n\t\t\t\teval(ctx)\n\t\t\t}\n\t\t}\n\n\t\tif len(errors) > 0 {\n\t\t\tresult = append(result, fmt.Sprintf(\"%s: %s\", field.Name, strings.Join(errors, \", \")))\n\t\t}\n\t}\n\n\treturn strings.Join(result, \"; \")\n}", "func (info *structInfo) fieldValid(i int, t reflect.Type) bool {\n\treturn info.field(i).isValid(i, t)\n}", "func (v *ClassValue) Valid() bool {\n\tfor _, f := range v.Fields {\n\t\tif !f.Valid() {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (self *StructFieldDef) Validate() error {\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"StructFieldDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"Identifier\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructFieldDef.name does not contain a valid Identifier (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"StructFieldDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructFieldDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructFieldDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Items != \"\" {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Items)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructFieldDef.items does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Keys != \"\" {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Keys)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructFieldDef.keys does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Validator) Validate(data interface{}) (bool, []string, error) {\n\t//validate and check for any errors, reading explicit validations errors and returning\n\t//a list of fields that failed or the error\n\terr := v.Validator.Struct(data)\n\tif err != nil {\n\t\tvalidationErrs, ok := err.(validator.ValidationErrors)\n\t\tif !ok {\n\t\t\treturn false, nil, errors.Wrap(err, \"validate\")\n\t\t}\n\t\tfields := make([]string, 0)\n\t\tfor _, validationErr := range validationErrs {\n\t\t\tfields = append(fields, validationErr.Field())\n\t\t}\n\t\treturn false, fields, nil\n\t}\n\treturn true, nil, nil\n}", "func validateFields(req *logical.Request, data *framework.FieldData) error {\n\tvar unknownFields []string\n\tfor k := range req.Data {\n\t\tif _, ok := data.Schema[k]; !ok {\n\t\t\tunknownFields = append(unknownFields, k)\n\t\t}\n\t}\n\n\tif len(unknownFields) > 0 {\n\t\t// Sort since this is a human error\n\t\tsort.Strings(unknownFields)\n\n\t\treturn fmt.Errorf(\"unknown fields: %q\", unknownFields)\n\t}\n\n\treturn nil\n}", "func validateFields(req *logical.Request, data *framework.FieldData) error {\n\tvar unknownFields []string\n\tfor k := range req.Data {\n\t\tif _, ok := data.Schema[k]; !ok {\n\t\t\tunknownFields = append(unknownFields, k)\n\t\t}\n\t}\n\n\tif len(unknownFields) > 0 {\n\t\t// Sort since this is a human error\n\t\tsort.Strings(unknownFields)\n\n\t\treturn fmt.Errorf(\"unknown fields: %q\", unknownFields)\n\t}\n\n\treturn nil\n}", "func (s *RecordSchema) Validate(v reflect.Value) bool {\n\tv = dereference(v)\n\tif v.Kind() != reflect.Struct || !v.CanAddr() || !v.CanInterface() {\n\t\treturn false\n\t}\n\trec, ok := v.Interface().(GenericRecord)\n\tif !ok {\n\t\t// This is not a generic record and is likely a specific record. Hence\n\t\t// use the basic check.\n\t\treturn v.Kind() == reflect.Struct\n\t}\n\n\tfieldCount := 0\n\tfor key, val := range rec.fields {\n\t\tfor idx := range s.Fields {\n\t\t\t// key.Name must have rs.Fields[idx].Name as a suffix\n\t\t\tif len(s.Fields[idx].Name) <= len(key) {\n\t\t\t\tlhs := key[len(key)-len(s.Fields[idx].Name):]\n\t\t\t\tif lhs == s.Fields[idx].Name {\n\t\t\t\t\tif !s.Fields[idx].Type.Validate(reflect.ValueOf(val)) {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\tfieldCount++\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// All of the fields set must be accounted for in the union.\n\tif fieldCount < len(rec.fields) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (s StructSpec) Validate() error {\n\tfor _, f := range s.Fields {\n\t\terr := f.Validate()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (cv *CustomValidator) Validate(i interface{}) error {\n\terrorRes, err := cv.Validator.Struct(i).(validator.ValidationErrors)\n\tif !err {\n\t\treturn nil\n\t}\n\terrorFields := []string{}\n\tfor _, k := range errorRes {\n\t\terrorFields = append(errorFields, k.StructField())\n\t}\n\tif len(errorFields) == 1 {\n\t\treturn errors.New(strings.Join(errorFields, \", \") + \" field is invalid or missing.\")\n\t}\n\treturn errors.New(strings.Join(errorFields, \", \") + \" fields are invalid or missing.\")\n}", "func Validate(v interface{}) error {\n\n\t// returns nil or ValidationErrors ( []FieldError )\n\terr := val.Struct(v)\n\tif err != nil {\n\n\t\t// this check is only needed when your code could produce\n\t\t// an invalid value for validation such as interface with nil\n\t\t// value most including myself do not usually have code like this.\n\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn err\n\t}\n\treturn nil\n}", "func ValidateFields(model interface{}) error {\n\terr := validator.Validate(model)\n\tif err != nil {\n\t\terrs, ok := err.(validator.ErrorMap)\n\t\tif ok {\n\t\t\tfor f, _ := range errs {\n\t\t\t\treturn errors.New(ecodes.ValidateField, constant.ValidateFieldErr+\"-\"+f)\n\t\t\t}\n\t\t} else {\n\t\t\treturn errors.New(ecodes.ValidationUnknown, constant.ValidationUnknownErr)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (v *Validator) ValidateFields(input map[string]string) {\n\tfor field, value := range input {\n\t\t_, found := find(requiredFields, field)\n\t\tif !found {\n\t\t\tv.errors[\"errors\"] = append(v.errors[field], fmt.Sprintf(\"%+v is not valid, check docs for valid fields\", field))\n\t\t}\n\t\t(v.model)[field] = value\n\t}\n}", "func (self *TypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"TypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"TypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"TypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"TypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"TypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (mt *EasypostFieldObject) Validate() (err error) {\n\tif mt.Key == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"key\"))\n\t}\n\tif mt.Value == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"value\"))\n\t}\n\tif mt.Visibility == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"visibility\"))\n\t}\n\tif mt.Label == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"label\"))\n\t}\n\n\treturn\n}", "func (ti TypeInfo) Validate() error {\n\tif len(ti.Type) == 0 {\n\t\treturn errors.Wrap(ErrValidatingData, \"TypeInfo requires a type\")\n\t}\n\treturn nil\n}", "func ValidateStructFields(in interface{}, requiredFieldIDs []string) (err error) {\n\tvar inAsMap map[string]interface{}\n\ttemp, err := json.Marshal(in)\n\tif err != nil {\n\t\treturn errors.New(\"error validating input struct\")\n\t}\n\terr = json.Unmarshal(temp, &inAsMap)\n\tif err != nil {\n\t\treturn errors.New(\"error validating input struct\")\n\t}\n\n\tfor _, requiredFieldID := range requiredFieldIDs {\n\t\t// Make sure the field is in the data.\n\t\tif val, ok := inAsMap[requiredFieldID]; !ok || len(fmt.Sprintf(\"%v\", val)) == 0 {\n\t\t\treturn errors.New(\"required input field \" + requiredFieldID + \" not specified\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func Validate(value interface{}) error {\n\tv := reflect.Indirect(reflect.ValueOf(value))\n\tt := v.Type()\n\n\t// Look for an IsValid method on value. To check that this IsValid method\n\t// exists, we need to retrieve it with MethodByName, which returns a\n\t// reflect.Value. This reflect.Value, m, has a method that is called\n\t// IsValid as well, which tells us whether v actually represents the\n\t// function we're looking for. But they're two completely different IsValid\n\t// methods. Yes, this is confusing.\n\tm := reflect.ValueOf(value).MethodByName(\"IsValid\")\n\tif m.IsValid() {\n\t\te := m.Call([]reflect.Value{})\n\t\terr, ok := e[0].Interface().(error)\n\t\tif ok && err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// For non-struct values, we cannot do much, as there's no associated tags\n\t// to lookup to decide how to validate, so we have to assume they're valid.\n\tif t.Kind() != reflect.Struct {\n\t\treturn nil\n\t}\n\n\t// For struct values, iterate through the fields and use the type of field\n\t// along with its validate tags to decide next steps\n\tfor i := 0; i < v.NumField(); i++ {\n\t\tfield := v.Field(i)\n\n\t\tswitch field.Type().Kind() {\n\t\tcase reflect.Struct:\n\t\t\tdv := field.Interface()\n\t\t\tif err := Validate(dv); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase reflect.Slice:\n\t\t\tdv := reflect.ValueOf(field.Interface())\n\t\t\tif tag, ok := t.Field(i).Tag.Lookup(\"validate\"); ok {\n\t\t\t\tif err := validate(tag, t.Field(i).Name, v, v.Field(i)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor j := 0; j < dv.Len(); j++ {\n\t\t\t\tif err := Validate(dv.Index(j).Interface()); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Map:\n\t\t\tif tag, ok := t.Field(i).Tag.Lookup(\"validate\"); ok {\n\t\t\t\tif err := validate(tag, t.Field(i).Name, v, v.Field(i)); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Bool, reflect.Int, reflect.Int64, reflect.Float64, reflect.String:\n\t\t\ttag, ok := t.Field(i).Tag.Lookup(\"validate\")\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := validate(tag, t.Field(i).Name, v, v.Field(i)); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase reflect.Chan:\n\t\t\treturn nil\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"unimplemented struct field type: %s\", t.Field(i).Name)\n\t\t}\n\t}\n\treturn nil\n}", "func (m *Type1) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (u *Usecase) validFields(d *Device) error {\n\tif d.Name == \"\" {\n\t\treturn &InvalidError{\"attribute `Name` must not be empty\"}\n\t}\n\n\tif d.User == 0 {\n\t\treturn &InvalidError{\"invalid user\"}\n\t}\n\n\treturn nil\n}", "func Validate(schema interface{}, errors []map[string]interface{}) {\n\t/**\n\t * create validator instance\n\t */\n\tvalidate := validator.New()\n\n\tif err := validate.Struct(schema); err != nil {\n\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\n\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\terrors = append(errors, map[string]interface{}{\n\t\t\t\t\"message\": fmt.Sprint(err), \"flag\": \"INVALID_BODY\"},\n\t\t\t)\n\t\t}\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n\tif errors != nil {\n\t\texception.BadRequest(\"Validation error\", errors)\n\t}\n}", "func (s *FieldStatsService) Validate() error {\n\tvar invalid []string\n\tif s.level != \"\" && (s.level != FieldStatsIndicesLevel && s.level != FieldStatsClusterLevel) {\n\t\tinvalid = append(invalid, \"Level\")\n\t}\n\tif len(invalid) != 0 {\n\t\treturn fmt.Errorf(\"missing or invalid required fields: %v\", invalid)\n\t}\n\treturn nil\n}", "func (t Type) Validate() error {\n\tswitch t {\n\tcase git:\n\t\treturn nil\n\tcase nop:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrInvalidType\n\t}\n}", "func (time Time) Validate() bool {\n\tret := true\n\tif ret == true && time.hours != (Hours{}) {\n\t\tret = time.hours.Validate()\n\t}\n\n\tif ret == true && time.minutes != (Minutes{}) {\n\t\tret = time.minutes.Validate()\n\t}\n\n\tif ret == true && time.seconds != (Seconds{}) {\n\t\tret = time.seconds.Validate()\n\t}\n\n\tif ret == true && time.delay != (Delay{}) {\n\t\tret = time.delay.Validate()\n\t}\n\n\tif ret != true {\n\t\tlog.Println(\"Failed to validate time '\" + time.value + \"'\")\n\t}\n\treturn ret\n}", "func (p *Publication) IsValidFields() error {\n\tif p.Content != \"\" {\n\t\treturn nil\n\t}\n\treturn errorstatus.ErrorBadInfo\n\n}", "func (a Relayer) Validate() error {\n\treturn validation.ValidateStruct(&a,\n\t\tvalidation.Field(&a.Address, validation.Required),\n\t)\n}", "func (builder *Builder) ValidateFields() error {\n\tvmImageRefFields := []string{\"ImageSku\", \"ImageVersion\"}\n\tcustomVMIMageRefFields := []string{\"Image\", \"ImageResourceGroup\", \"ImageStorageAccount\", \"ImageContainer\"}\n\n\tif !builder.hasMarketplaceVMImageRef() && !builder.hasCustomVMIMageRef() {\n\t\treturn fmt.Errorf(\n\t\t\t\"missing fields: you must provide values for either %s fields or %s fields\",\n\t\t\tstrings.Join(vmImageRefFields, \", \"),\n\t\t\tstrings.Join(customVMIMageRefFields, \", \"),\n\t\t)\n\t}\n\n\tif builder.hasMarketplaceVMImageRef() && builder.hasCustomVMIMageRef() {\n\t\treturn fmt.Errorf(\n\t\t\t\"confilicting fields: you must provide values for either %s fields or %s fields\",\n\t\t\tstrings.Join(vmImageRefFields, \", \"),\n\t\t\tstrings.Join(customVMIMageRefFields, \", \"),\n\t\t)\n\t}\n\n\treturn nil\n}", "func (self *NumberTypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"NumberTypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"NumberTypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"NumberTypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"NumberTypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"NumberTypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (mt *EasypostCarrierTypes) Validate() (err error) {\n\tif mt.Type == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"type\"))\n\t}\n\tif mt.Object == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"object\"))\n\t}\n\tif mt.Fields == nil {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`response`, \"fields\"))\n\t}\n\n\tif ok := goa.ValidatePattern(`^CarrierType$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^CarrierType$`))\n\t}\n\treturn\n}", "func (t *Transform) Validate() *field.Error {\n\tswitch t.Type {\n\tcase TransformTypeMath:\n\t\tif t.Math == nil {\n\t\t\treturn field.Required(field.NewPath(\"math\"), \"given transform type math requires configuration\")\n\t\t}\n\t\treturn verrors.WrapFieldError(t.Math.Validate(), field.NewPath(\"math\"))\n\tcase TransformTypeMap:\n\t\tif t.Map == nil {\n\t\t\treturn field.Required(field.NewPath(\"map\"), \"given transform type map requires configuration\")\n\t\t}\n\t\treturn verrors.WrapFieldError(t.Map.Validate(), field.NewPath(\"map\"))\n\tcase TransformTypeMatch:\n\t\tif t.Match == nil {\n\t\t\treturn field.Required(field.NewPath(\"match\"), \"given transform type match requires configuration\")\n\t\t}\n\t\treturn verrors.WrapFieldError(t.Match.Validate(), field.NewPath(\"match\"))\n\tcase TransformTypeString:\n\t\tif t.String == nil {\n\t\t\treturn field.Required(field.NewPath(\"string\"), \"given transform type string requires configuration\")\n\t\t}\n\t\treturn verrors.WrapFieldError(t.String.Validate(), field.NewPath(\"string\"))\n\tcase TransformTypeConvert:\n\t\tif t.Convert == nil {\n\t\t\treturn field.Required(field.NewPath(\"convert\"), \"given transform type convert requires configuration\")\n\t\t}\n\t\tif err := t.Convert.Validate(); err != nil {\n\t\t\treturn verrors.WrapFieldError(err, field.NewPath(\"convert\"))\n\t\t}\n\tdefault:\n\t\t// Should never happen\n\t\treturn field.Invalid(field.NewPath(\"type\"), t.Type, \"unknown transform type\")\n\t}\n\n\treturn nil\n}", "func (strategy UpdateScatterStrategy) FieldsValidation() error {\n\tif len(strategy) == 0 {\n\t\treturn nil\n\t}\n\n\tm := make(map[string]struct{}, len(strategy))\n\tfor _, term := range strategy {\n\t\tif term.Key == \"\" {\n\t\t\treturn fmt.Errorf(\"key should not be empty\")\n\t\t}\n\t\tid := term.Key + \":\" + term.Value\n\t\tif _, ok := m[id]; !ok {\n\t\t\tm[id] = struct{}{}\n\t\t} else {\n\t\t\treturn fmt.Errorf(\"duplicated key=%v value=%v\", term.Key, term.Value)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (self *StructTypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"StructTypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructTypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"StructTypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructTypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"StructTypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Fields == nil {\n\t\treturn fmt.Errorf(\"StructTypeDef: Missing required field: fields\")\n\t}\n\treturn nil\n}", "func (self *MapTypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"MapTypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"MapTypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"MapTypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"MapTypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"MapTypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Keys == \"\" {\n\t\treturn fmt.Errorf(\"MapTypeDef.keys is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Keys)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"MapTypeDef.keys does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Items == \"\" {\n\t\treturn fmt.Errorf(\"MapTypeDef.items is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Items)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"MapTypeDef.items does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (s StructInCustom) Validate() []string {\n\tvar errs []string\n\tif s.Name == \"\" {\n\t\terrs = append(errs, \"name::is_required\")\n\t}\n\n\treturn errs\n}", "func (cv Validator) Validate(i interface{}) error {\n\treturn cv.Validator.Struct(i)\n}", "func Validate(v interface{}) (error, bool) {\n\tresult, err := govalidator.ValidateStruct(v)\n\tif err != nil {\n\t\tlog.Println(\"Invalid data\", err)\n\t}\n\treturn err, result\n}", "func validateFieldDurations(fl validator.FieldLevel) bool {\n\tv := fl.Field().Bool()\n\tif v {\n\t\t//read the parameter and extract the other fields that were specified\n\t\tparam := fl.Param()\n\t\tfields := strings.Fields(param)\n\t\tfor _, field := range fields {\n\t\t\t//check if the field is set\n\t\t\tstructField, _, _, ok := fl.GetStructFieldOKAdvanced2(fl.Parent(), field)\n\t\t\tif !ok || structField.IsZero() {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func (h *HazardType) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\terrors := validate.Validate(\n\t\t&validators.StringIsPresent{Name: \"Label\", Field: h.Label, Message: \"A label is required.\"},\n\t\t&validators.StringIsPresent{Name: \"Description\", Field: h.Description, Message: \"Please provide a brief description.\"},\n\t)\n\n\treturn errors, nil\n}", "func (tS *testAInfo) Validate(msg actor.Msg) bool {\n\tswitch m := msg[0].(type) {\n\tcase int:\n\t\tif m > 0 && m < 10 {\n\t\t\treturn true\n\t\t}\n\tdefault:\n\t\tfor _, datum := range tS.allowed {\n\t\t\tif reflect.TypeOf(msg[0]) ==\n\t\t\t\treflect.TypeOf(datum) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\t// Does not match a valid type\n\treturn false\n}", "func (ut *RegisterPayload) Validate() (err error) {\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Password == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"password\"))\n\t}\n\tif ut.FirstName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"first_name\"))\n\t}\n\tif ut.LastName == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"last_name\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif utf8.RuneCountInString(ut.Email) < 6 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 6, true))\n\t}\n\tif utf8.RuneCountInString(ut.Email) > 150 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.email`, ut.Email, utf8.RuneCountInString(ut.Email), 150, false))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.FirstName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.first_name`, ut.FirstName, utf8.RuneCountInString(ut.FirstName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) < 1 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 1, true))\n\t}\n\tif utf8.RuneCountInString(ut.LastName) > 200 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.last_name`, ut.LastName, utf8.RuneCountInString(ut.LastName), 200, false))\n\t}\n\tif utf8.RuneCountInString(ut.Password) < 5 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 5, true))\n\t}\n\tif utf8.RuneCountInString(ut.Password) > 100 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.password`, ut.Password, utf8.RuneCountInString(ut.Password), 100, false))\n\t}\n\treturn\n}", "func (u Phone) Validate() error {\n\treturn nil\n\t// return validation.ValidateStruct(&u,\n\t// \tvalidation.Field(&u.Name, validation.Required),\n\t// \tvalidation.Field(&u.Created, validation.Required))\n}", "func (r *InfoReq) Validate() error {\n\treturn validate.Struct(r)\n}", "func (r *RouteSpecFields) Validate(ctx context.Context) (errs *apis.FieldError) {\n\n\tif r.Domain == \"\" {\n\t\terrs = errs.Also(apis.ErrMissingField(\"domain\"))\n\t}\n\n\tif r.Hostname == \"www\" {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"hostname\", r.Hostname))\n\t}\n\n\tif _, err := BuildPathRegexp(r.Path); err != nil {\n\t\terrs = errs.Also(apis.ErrInvalidValue(\"path\", r.Path))\n\t}\n\n\treturn errs\n}", "func (mt *EasypostScanform) Validate() (err error) {\n\tif mt.Address != nil {\n\t\tif err2 := mt.Address.Validate(); err2 != nil {\n\t\t\terr = goa.MergeErrors(err, err2)\n\t\t}\n\t}\n\tif mt.ID != nil {\n\t\tif ok := goa.ValidatePattern(`^sf_`, *mt.ID); !ok {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.id`, *mt.ID, `^sf_`))\n\t\t}\n\t}\n\tif ok := goa.ValidatePattern(`^ScanForm$`, mt.Object); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`response.object`, mt.Object, `^ScanForm$`))\n\t}\n\tif mt.Status != nil {\n\t\tif !(*mt.Status == \"creating\" || *mt.Status == \"created\" || *mt.Status == \"failed\") {\n\t\t\terr = goa.MergeErrors(err, goa.InvalidEnumValueError(`response.status`, *mt.Status, []interface{}{\"creating\", \"created\", \"failed\"}))\n\t\t}\n\t}\n\treturn\n}", "func Validate(schema interface{}) {\n\tvalidate := validator.New()\n\n\tif err := validate.Struct(schema); err != nil {\n\t\tif _, ok := err.(*validator.InvalidValidationError); ok {\n\t\t\texception.BadRequest(fmt.Sprint(err), \"INVALID_BODY\")\n\t\t}\n\n\t\tfor _, err := range err.(validator.ValidationErrors) {\n\t\t\texception.BadRequest(fmt.Sprint(err), \"INVALID_BODY\")\n\t\t}\n\t}\n}", "func (v *Validation) Validate(i interface{}) ValidationErrors {\n\terrs := v.validate.Struct(i)\n\tif errs == nil {\n\t\treturn nil\n\t}\n\n\tvar returnErrs ValidationErrors\n\tfor _, err := range errs.(validator.ValidationErrors) {\n\t\t// cast the FieldError into our ValidationError and append to the slice\n\t\tve := ValidationError{err.(validator.FieldError)}\n\t\treturnErrs = append(returnErrs, ve)\n\t}\n\treturn returnErrs\n}", "func (s *MemberDefinition) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"MemberDefinition\"}\n\tif s.CognitoMemberDefinition != nil {\n\t\tif err := s.CognitoMemberDefinition.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"CognitoMemberDefinition\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.OidcMemberDefinition != nil {\n\t\tif err := s.OidcMemberDefinition.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"OidcMemberDefinition\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (m *MeasurementType) Validate(formats strfmt.Registry) error {\n\treturn nil\n}", "func (s *UnionSchema) Validate(v reflect.Value) bool {\n\tv = dereference(v)\n\tfor i := range s.Types {\n\t\tif t := s.Types[i]; t.Validate(v) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func (u *User) Validate() *errors.RestError {\n\tif err := validators.ValidateStruct(u); err != nil {\n\t\treturn err\n\t}\n\t// Sanitize Structure\n\tu.FirstName = strings.TrimSpace(u.FirstName)\n\tu.LastName = strings.TrimSpace(u.LastName)\n\tu.Email = strings.TrimSpace(u.Email)\n\tu.Username = strings.TrimSpace(u.Username)\n\tu.Password = strings.TrimSpace(u.Password)\n\t// Check password\n\tif err := u.validatePassword(); err != nil {\n\t\treturn err\n\t}\n\t// Check uniqueness\n\tif err := u.checkUniqueness(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (DirectorBindStrategy) Validate(ctx request.Context, obj runtime.Object) field.ErrorList {\n\to := obj.(*bind.DirectorBind)\n\tlog.Printf(\"Validating fields for DirectorBind %s\\n\", o.Name)\n\terrors := field.ErrorList{}\n\t// perform validation here and add to errors using field.Invalid\n\treturn errors\n}", "func (t *Test1) Validate(tx *pop.Connection) (*validate.Errors, error) {\n\treturn validate.Validate(\n\t\t&validators.IntIsPresent{Field: t.Field1, Name: \"Field1\"},\n\t), nil\n}", "func (t ConvertTransform) Validate() *field.Error {\n\tif !t.GetFormat().IsValid() {\n\t\treturn field.Invalid(field.NewPath(\"format\"), t.Format, \"invalid format\")\n\t}\n\tif !t.ToType.IsValid() {\n\t\treturn field.Invalid(field.NewPath(\"toType\"), t.ToType, \"invalid type\")\n\t}\n\treturn nil\n}", "func (conf TypeConfig) Validate() error {\n\tfor _, rule := range conf.Rules {\n\t\td, ok := conf.Descriptors[rule.Descriptor]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"rule %s=%s uses descriptor %s that does not exist\", rule.Name, rule.Value, rule.Descriptor)\n\t\t}\n\t\tif !hasField(rule.Name, d) {\n\t\t\treturn fmt.Errorf(\"rule %s refers to field %s that is not present in descriptor\", rule.Descriptor, rule.Name)\n\t\t}\n\n\t}\n\tfor name, desc := range conf.Descriptors {\n\t\tfor i, d := range desc {\n\t\t\tcol, ok := d.(map[string]interface{})\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"descriptor %s has invalid structure in element %d\", name, i)\n\t\t\t}\n\t\t\tif col[\"name\"] == \"ts\" && col[\"type\"] != \"time\" {\n\t\t\t\treturn fmt.Errorf(\"descriptor %s has field ts with wrong type %s\", name, col[\"type\"])\n\t\t\t}\n\t\t}\n\t\tcol := desc[0].(map[string]interface{})\n\t\tif col[\"name\"] != \"_path\" {\n\t\t\treturn fmt.Errorf(\"descriptor %s does not have _path as first column\", name)\n\t\t}\n\t}\n\treturn nil\n}", "func (m APIStepType) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// value enum\n\tif err := m.validateAPIStepTypeEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (r *Version) Validate() error {\n\n\tR := *r\n\tif len(R) > 4 {\n\t\treturn errors.New(\"Version field may not contain more than 4 fields\")\n\t}\n\tif len(R) < 3 {\n\t\treturn errors.New(\"Version field must contain at least 3 fields\")\n\t}\n\tfor i, x := range R[:3] {\n\t\tn, ok := x.(int)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"Version field %d is not an integer: %d\", i, n)\n\t\t}\n\t\tif n > 99 {\n\t\t\treturn fmt.Errorf(\"Version field %d value is over 99: %d\", i, n)\n\t\t}\n\t}\n\tif len(R) > 3 {\n\t\ts, ok := R[3].(string)\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"optional field 4 of Version is not a string\")\n\t\t} else {\n\t\t\tfor i, x := range s {\n\t\t\t\tif !(unicode.IsLetter(x) || unicode.IsDigit(x)) {\n\t\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\t\"optional field 4 of Version contains other than letters and numbers at position %d: '%v,\", i, x)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (s *ListAggregatedUtterancesInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"ListAggregatedUtterancesInput\"}\n\tif s.AggregationDuration == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"AggregationDuration\"))\n\t}\n\tif s.BotAliasId != nil && len(*s.BotAliasId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasId\", 10))\n\t}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 1))\n\t}\n\tif s.Filters != nil && len(s.Filters) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Filters\", 1))\n\t}\n\tif s.LocaleId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"LocaleId\"))\n\t}\n\tif s.MaxResults != nil && *s.MaxResults < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinValue(\"MaxResults\", 1))\n\t}\n\tif s.AggregationDuration != nil {\n\t\tif err := s.AggregationDuration.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"AggregationDuration\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.Filters != nil {\n\t\tfor i, v := range s.Filters {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Filters\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.SortBy != nil {\n\t\tif err := s.SortBy.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"SortBy\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (s *CreateSlotTypeInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"CreateSlotTypeInput\"}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotVersion\"))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 5 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 5))\n\t}\n\tif s.LocaleId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"LocaleId\"))\n\t}\n\tif s.LocaleId != nil && len(*s.LocaleId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"LocaleId\", 1))\n\t}\n\tif s.SlotTypeName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"SlotTypeName\"))\n\t}\n\tif s.SlotTypeName != nil && len(*s.SlotTypeName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SlotTypeName\", 1))\n\t}\n\tif s.SlotTypeValues != nil && len(s.SlotTypeValues) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SlotTypeValues\", 1))\n\t}\n\tif s.CompositeSlotTypeSetting != nil {\n\t\tif err := s.CompositeSlotTypeSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"CompositeSlotTypeSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.ExternalSourceSetting != nil {\n\t\tif err := s.ExternalSourceSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ExternalSourceSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.SlotTypeValues != nil {\n\t\tfor i, v := range s.SlotTypeValues {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"SlotTypeValues\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.ValueSelectionSetting != nil {\n\t\tif err := s.ValueSelectionSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ValueSelectionSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (s *OrderBy) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"OrderBy\"}\n\tif s.PropertyName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"PropertyName\"))\n\t}\n\tif s.PropertyName != nil && len(*s.PropertyName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"PropertyName\", 1))\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (m *StripeRefundSpecificFields) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (m ModelErrorDatumType) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\t// value enum\n\tif err := m.validateModelErrorDatumTypeEnum(\"\", \"body\", m); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *CreateBotAliasInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"CreateBotAliasInput\"}\n\tif s.BotAliasLocaleSettings != nil && len(s.BotAliasLocaleSettings) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasLocaleSettings\", 1))\n\t}\n\tif s.BotAliasName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotAliasName\"))\n\t}\n\tif s.BotAliasName != nil && len(*s.BotAliasName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasName\", 1))\n\t}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 1))\n\t}\n\tif s.BotAliasLocaleSettings != nil {\n\t\tfor i, v := range s.BotAliasLocaleSettings {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"BotAliasLocaleSettings\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.ConversationLogSettings != nil {\n\t\tif err := s.ConversationLogSettings.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ConversationLogSettings\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.SentimentAnalysisSettings != nil {\n\t\tif err := s.SentimentAnalysisSettings.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"SentimentAnalysisSettings\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func Validate(ctx http.IContext, vld *validator.Validate, arg interface{}) bool {\n\n\tif err := ctx.GetRequest().GetBodyAs(arg); err != nil {\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\tswitch err := vld.Struct(arg); err.(type) {\n\tcase validator.ValidationErrors:\n\t\thttp.FailedValidationException(ctx, err.(validator.ValidationErrors))\n\t\treturn false\n\n\tcase nil:\n\t\tbreak\n\n\tdefault:\n\t\thttp.InternalServerException(ctx)\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (a *Account) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(a)\n}", "func (s *CreateMemberInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"CreateMemberInput\"}\n\tif s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ClientRequestToken\", 1))\n\t}\n\tif s.InvitationId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"InvitationId\"))\n\t}\n\tif s.InvitationId != nil && len(*s.InvitationId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"InvitationId\", 1))\n\t}\n\tif s.MemberConfiguration == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"MemberConfiguration\"))\n\t}\n\tif s.NetworkId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"NetworkId\"))\n\t}\n\tif s.NetworkId != nil && len(*s.NetworkId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"NetworkId\", 1))\n\t}\n\tif s.MemberConfiguration != nil {\n\t\tif err := s.MemberConfiguration.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"MemberConfiguration\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (ut *UpdateUserPayload) Validate() (err error) {\n\tif ut.Name == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"name\"))\n\t}\n\tif ut.Email == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"email\"))\n\t}\n\tif ut.Bio == \"\" {\n\t\terr = goa.MergeErrors(err, goa.MissingAttributeError(`type`, \"bio\"))\n\t}\n\tif err2 := goa.ValidateFormat(goa.FormatEmail, ut.Email); err2 != nil {\n\t\terr = goa.MergeErrors(err, goa.InvalidFormatError(`type.email`, ut.Email, goa.FormatEmail, err2))\n\t}\n\tif ok := goa.ValidatePattern(`\\S`, ut.Name); !ok {\n\t\terr = goa.MergeErrors(err, goa.InvalidPatternError(`type.name`, ut.Name, `\\S`))\n\t}\n\tif utf8.RuneCountInString(ut.Name) > 256 {\n\t\terr = goa.MergeErrors(err, goa.InvalidLengthError(`type.name`, ut.Name, utf8.RuneCountInString(ut.Name), 256, false))\n\t}\n\treturn\n}", "func (o *Virtualserver) validate(dbRecord *common.DbRecord) (ok bool, err error) {\n\t////////////////////////////////////////////////////////////////////////////\n\t// Marshal data interface.\n\t////////////////////////////////////////////////////////////////////////////\n\tvar data virtualserver.Data\n\terr = shared.MarshalInterface(dbRecord.Data, &data)\n\tif err != nil {\n\t\treturn\n\t}\n\t////////////////////////////////////////////////////////////////////////////\n\t// Test required fields.\n\t////////////////////////////////////////////////////////////////////////////\n\tok = true\n\trequired := make(map[string]bool)\n\trequired[\"ProductCode\"] = false\n\trequired[\"IP\"] = false\n\trequired[\"Port\"] = false\n\trequired[\"LoadBalancerIP\"] = false\n\trequired[\"Name\"] = false\n\t////////////////////////////////////////////////////////////////////////////\n\tif data.ProductCode != 0 {\n\t\trequired[\"ProductCode\"] = true\n\t}\n\tif len(dbRecord.LoadBalancerIP) > 0 {\n\t\trequired[\"LoadBalancerIP\"] = true\n\t}\n\tif len(data.Ports) != 0 {\n\t\trequired[\"Port\"] = true\n\t}\n\tif data.IP != \"\" {\n\t\trequired[\"IP\"] = true\n\t}\n\tif data.Name != \"\" {\n\t\trequired[\"Name\"] = true\n\t}\n\tfor _, val := range required {\n\t\tif val == false {\n\t\t\tok = false\n\t\t}\n\t}\n\tif !ok {\n\t\terr = fmt.Errorf(\"missing required fields - %+v\", required)\n\t}\n\treturn\n}", "func Validate(t interface{}) error {\n\treturn validator.Struct(t)\n}", "func (m *ColumnDetails) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateKeyType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateSortOrder(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateValueType(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (cv *CustomValidator) Validate(i interface{}) error {\n\treturn cv.Validator.Struct(i)\n}", "func (cv *CustomValidator) Validate(i interface{}) error {\n\treturn cv.Validator.Struct(i)\n}", "func (s *WriteRecordsInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"WriteRecordsInput\"}\n\tif s.DatabaseName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"DatabaseName\"))\n\t}\n\tif s.Records == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"Records\"))\n\t}\n\tif s.Records != nil && len(s.Records) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Records\", 1))\n\t}\n\tif s.TableName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"TableName\"))\n\t}\n\tif s.CommonAttributes != nil {\n\t\tif err := s.CommonAttributes.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"CommonAttributes\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.Records != nil {\n\t\tfor i, v := range s.Records {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Records\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (m *HashType) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateFunction(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateMethod(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModifier(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (s *CognitoMemberDefinition) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"CognitoMemberDefinition\"}\n\tif s.ClientId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"ClientId\"))\n\t}\n\tif s.ClientId != nil && len(*s.ClientId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ClientId\", 1))\n\t}\n\tif s.UserGroup == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"UserGroup\"))\n\t}\n\tif s.UserGroup != nil && len(*s.UserGroup) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"UserGroup\", 1))\n\t}\n\tif s.UserPool == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"UserPool\"))\n\t}\n\tif s.UserPool != nil && len(*s.UserPool) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"UserPool\", 1))\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (recipe *Recipe) Validate() error {\n\tvalidate := validator.New()\n\treturn validate.Struct(recipe)\n}", "func (s *CreateInferenceExperimentInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"CreateInferenceExperimentInput\"}\n\tif s.EndpointName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"EndpointName\"))\n\t}\n\tif s.ModelVariants == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"ModelVariants\"))\n\t}\n\tif s.ModelVariants != nil && len(s.ModelVariants) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ModelVariants\", 1))\n\t}\n\tif s.Name == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"Name\"))\n\t}\n\tif s.Name != nil && len(*s.Name) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Name\", 1))\n\t}\n\tif s.RoleArn == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"RoleArn\"))\n\t}\n\tif s.RoleArn != nil && len(*s.RoleArn) < 20 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"RoleArn\", 20))\n\t}\n\tif s.ShadowModeConfig == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"ShadowModeConfig\"))\n\t}\n\tif s.Type == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"Type\"))\n\t}\n\tif s.DataStorageConfig != nil {\n\t\tif err := s.DataStorageConfig.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"DataStorageConfig\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.ModelVariants != nil {\n\t\tfor i, v := range s.ModelVariants {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"ModelVariants\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.ShadowModeConfig != nil {\n\t\tif err := s.ShadowModeConfig.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ShadowModeConfig\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.Tags != nil {\n\t\tfor i, v := range s.Tags {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Tags\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (s *UpdateSlotTypeInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"UpdateSlotTypeInput\"}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotVersion\"))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 5 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 5))\n\t}\n\tif s.LocaleId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"LocaleId\"))\n\t}\n\tif s.LocaleId != nil && len(*s.LocaleId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"LocaleId\", 1))\n\t}\n\tif s.SlotTypeId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"SlotTypeId\"))\n\t}\n\tif s.SlotTypeId != nil && len(*s.SlotTypeId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SlotTypeId\", 10))\n\t}\n\tif s.SlotTypeName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"SlotTypeName\"))\n\t}\n\tif s.SlotTypeName != nil && len(*s.SlotTypeName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SlotTypeName\", 1))\n\t}\n\tif s.SlotTypeValues != nil && len(s.SlotTypeValues) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SlotTypeValues\", 1))\n\t}\n\tif s.CompositeSlotTypeSetting != nil {\n\t\tif err := s.CompositeSlotTypeSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"CompositeSlotTypeSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.ExternalSourceSetting != nil {\n\t\tif err := s.ExternalSourceSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ExternalSourceSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.SlotTypeValues != nil {\n\t\tfor i, v := range s.SlotTypeValues {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"SlotTypeValues\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.ValueSelectionSetting != nil {\n\t\tif err := s.ValueSelectionSetting.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ValueSelectionSetting\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func Validate(obj interface{}) (map[string]interface{}, bool) {\n\n\trules := govalidator.MapData{\n\t\t\"name\": []string{\"required\", \"between:3,150\"},\n\t\t//\"email\": []string{\"required\", \"min:4\", \"max:20\", \"email\"},\n\t\t//\"web\": []string{\"url\"},\n\t\t//\"age\": []string{\"numeric_between:18,56\"},\n\t}\n\n\treturn validate.Validate(rules, obj)\n}", "func (u *User) Validate() ([]app.Invalid, error) {\n\tvar inv []app.Invalid\n\n\tif u.UserType == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"UserType\", Err: \"The value of UserType cannot be 0.\"})\n\t}\n\n\tif u.FirstName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"FirstName\", Err: \"A value of FirstName cannot be empty.\"})\n\t}\n\n\tif u.LastName == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"LastName\", Err: \"A value of LastName cannot be empty.\"})\n\t}\n\n\tif u.Email == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Email\", Err: \"A value of Email cannot be empty.\"})\n\t}\n\n\tif u.Company == \"\" {\n\t\tinv = append(inv, app.Invalid{Fld: \"Company\", Err: \"A value of Company cannot be empty.\"})\n\t}\n\n\tif len(u.Addresses) == 0 {\n\t\tinv = append(inv, app.Invalid{Fld: \"Addresses\", Err: \"There must be at least one address.\"})\n\t} else {\n\t\tfor _, ua := range u.Addresses {\n\t\t\tif va, err := ua.Validate(); err != nil {\n\t\t\t\tinv = append(inv, va...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(inv) > 0 {\n\t\treturn inv, errors.New(\"Validation failures identified\")\n\t}\n\n\treturn nil, nil\n}", "func (s *GetPropertyValueHistoryInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"GetPropertyValueHistoryInput\"}\n\tif s.ComponentName != nil && len(*s.ComponentName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ComponentName\", 1))\n\t}\n\tif s.ComponentTypeId != nil && len(*s.ComponentTypeId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ComponentTypeId\", 1))\n\t}\n\tif s.EndTime != nil && len(*s.EndTime) < 20 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"EndTime\", 20))\n\t}\n\tif s.EntityId != nil && len(*s.EntityId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"EntityId\", 1))\n\t}\n\tif s.PropertyFilters != nil && len(s.PropertyFilters) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"PropertyFilters\", 1))\n\t}\n\tif s.SelectedProperties == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"SelectedProperties\"))\n\t}\n\tif s.SelectedProperties != nil && len(s.SelectedProperties) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"SelectedProperties\", 1))\n\t}\n\tif s.StartTime != nil && len(*s.StartTime) < 20 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"StartTime\", 20))\n\t}\n\tif s.WorkspaceId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"WorkspaceId\"))\n\t}\n\tif s.WorkspaceId != nil && len(*s.WorkspaceId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"WorkspaceId\", 1))\n\t}\n\tif s.PropertyFilters != nil {\n\t\tfor i, v := range s.PropertyFilters {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"PropertyFilters\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (v *validator) Validate(val interface{}) (bool, *domain.NuxError) {\n\tif l, ok := val.(int); ok {\n\t\treturn v.validateInt(l)\n\t}\n\n\tif l, ok := val.(int64); ok {\n\t\treturn v.validateInt64(l)\n\t}\n\n\tif l, ok := val.(float64); ok {\n\t\treturn v.validateFloat64(l)\n\t}\n\n\tif l, ok := val.(float32); ok {\n\t\treturn v.validateFloat32(l)\n\t}\n\n\treturn true, nil\n}", "func (d *Definition) Validate() (bool, error) {\n\treturn govalidator.ValidateStruct(d)\n}", "func (s *ServiceCatalogProvisioningDetails) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"ServiceCatalogProvisioningDetails\"}\n\tif s.PathId != nil && len(*s.PathId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"PathId\", 1))\n\t}\n\tif s.ProductId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"ProductId\"))\n\t}\n\tif s.ProductId != nil && len(*s.ProductId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ProductId\", 1))\n\t}\n\tif s.ProvisioningArtifactId != nil && len(*s.ProvisioningArtifactId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"ProvisioningArtifactId\", 1))\n\t}\n\tif s.ProvisioningParameters != nil {\n\t\tfor i, v := range s.ProvisioningParameters {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"ProvisioningParameters\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (self *AliasTypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"AliasTypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"AliasTypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"AliasTypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"AliasTypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"AliasTypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *ListSlotTypesInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"ListSlotTypesInput\"}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotVersion\"))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 1))\n\t}\n\tif s.Filters != nil && len(s.Filters) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Filters\", 1))\n\t}\n\tif s.LocaleId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"LocaleId\"))\n\t}\n\tif s.LocaleId != nil && len(*s.LocaleId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"LocaleId\", 1))\n\t}\n\tif s.MaxResults != nil && *s.MaxResults < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinValue(\"MaxResults\", 1))\n\t}\n\tif s.Filters != nil {\n\t\tfor i, v := range s.Filters {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Filters\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.SortBy != nil {\n\t\tif err := s.SortBy.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"SortBy\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (s *UpdateBotAliasInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"UpdateBotAliasInput\"}\n\tif s.BotAliasId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotAliasId\"))\n\t}\n\tif s.BotAliasId != nil && len(*s.BotAliasId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasId\", 10))\n\t}\n\tif s.BotAliasLocaleSettings != nil && len(s.BotAliasLocaleSettings) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasLocaleSettings\", 1))\n\t}\n\tif s.BotAliasName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotAliasName\"))\n\t}\n\tif s.BotAliasName != nil && len(*s.BotAliasName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotAliasName\", 1))\n\t}\n\tif s.BotId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"BotId\"))\n\t}\n\tif s.BotId != nil && len(*s.BotId) < 10 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotId\", 10))\n\t}\n\tif s.BotVersion != nil && len(*s.BotVersion) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"BotVersion\", 1))\n\t}\n\tif s.BotAliasLocaleSettings != nil {\n\t\tfor i, v := range s.BotAliasLocaleSettings {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"BotAliasLocaleSettings\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\tif s.ConversationLogSettings != nil {\n\t\tif err := s.ConversationLogSettings.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"ConversationLogSettings\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.SentimentAnalysisSettings != nil {\n\t\tif err := s.SentimentAnalysisSettings.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"SentimentAnalysisSettings\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (v *Validator) Validate(i interface{}) error {\n\treturn v.validator.Struct(i)\n}", "func (s *CreateProfileInput) Validate() error {\n\tinvalidParams := aws.ErrInvalidParams{Context: \"CreateProfileInput\"}\n\n\tif s.Address == nil {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"Address\"))\n\t}\n\tif s.Address != nil && len(*s.Address) < 1 {\n\t\tinvalidParams.Add(aws.NewErrParamMinLen(\"Address\", 1))\n\t}\n\tif s.ClientRequestToken != nil && len(*s.ClientRequestToken) < 10 {\n\t\tinvalidParams.Add(aws.NewErrParamMinLen(\"ClientRequestToken\", 10))\n\t}\n\tif len(s.DistanceUnit) == 0 {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"DistanceUnit\"))\n\t}\n\tif s.Locale != nil && len(*s.Locale) < 1 {\n\t\tinvalidParams.Add(aws.NewErrParamMinLen(\"Locale\", 1))\n\t}\n\n\tif s.ProfileName == nil {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"ProfileName\"))\n\t}\n\tif s.ProfileName != nil && len(*s.ProfileName) < 1 {\n\t\tinvalidParams.Add(aws.NewErrParamMinLen(\"ProfileName\", 1))\n\t}\n\tif len(s.TemperatureUnit) == 0 {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"TemperatureUnit\"))\n\t}\n\n\tif s.Timezone == nil {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"Timezone\"))\n\t}\n\tif s.Timezone != nil && len(*s.Timezone) < 1 {\n\t\tinvalidParams.Add(aws.NewErrParamMinLen(\"Timezone\", 1))\n\t}\n\tif len(s.WakeWord) == 0 {\n\t\tinvalidParams.Add(aws.NewErrParamRequired(\"WakeWord\"))\n\t}\n\tif s.MeetingRoomConfiguration != nil {\n\t\tif err := s.MeetingRoomConfiguration.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"MeetingRoomConfiguration\", err.(aws.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.Tags != nil {\n\t\tfor i, v := range s.Tags {\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Tags\", i), err.(aws.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (l *logger) Validate() error {\n\tif l == nil {\n\t\treturn nil\n\t}\n\tif err := l.Console.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"`Console` field: %s\", err.Error())\n\t}\n\tif err := l.File.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"`File` field: %s\", err.Error())\n\t}\n\treturn nil\n}", "func (self *ArrayTypeDef) Validate() error {\n\tif self.Type == \"\" {\n\t\treturn fmt.Errorf(\"ArrayTypeDef.type is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Type)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"ArrayTypeDef.type does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Name == \"\" {\n\t\treturn fmt.Errorf(\"ArrayTypeDef.name is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeName\", self.Name)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"ArrayTypeDef.name does not contain a valid TypeName (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Comment != \"\" {\n\t\tval := Validate(RdlSchema(), \"String\", self.Comment)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"ArrayTypeDef.comment does not contain a valid String (%v)\", val.Error)\n\t\t}\n\t}\n\tif self.Items == \"\" {\n\t\treturn fmt.Errorf(\"ArrayTypeDef.items is missing but is a required field\")\n\t} else {\n\t\tval := Validate(RdlSchema(), \"TypeRef\", self.Items)\n\t\tif !val.Valid {\n\t\t\treturn fmt.Errorf(\"ArrayTypeDef.items does not contain a valid TypeRef (%v)\", val.Error)\n\t\t}\n\t}\n\treturn nil\n}", "func (s *RegexMatchTuple) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"RegexMatchTuple\"}\n\tif s.FieldToMatch == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"FieldToMatch\"))\n\t}\n\tif s.RegexPatternSetId == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"RegexPatternSetId\"))\n\t}\n\tif s.RegexPatternSetId != nil && len(*s.RegexPatternSetId) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"RegexPatternSetId\", 1))\n\t}\n\tif s.TextTransformation == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"TextTransformation\"))\n\t}\n\tif s.FieldToMatch != nil {\n\t\tif err := s.FieldToMatch.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"FieldToMatch\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (r *RecordValidator) Validate(i interface{}) error {\r\n\treturn r.validator.Struct(i)\r\n}", "func (s *Service) Validate() error {\n\tnonEmptyFields := map[string]checker{\n\t\t\"Name\": checker{s.Name, true},\n\t\t\"Type\": checker{s.Type.String(), false}, // Type is a enum, no need to check\n\t\t\"Owner\": checker{s.Owner, true},\n\t\t\"ClusterType\": checker{s.ClusterType, true},\n\t\t\"InstanceName\": checker{s.InstanceName.String(), true},\n\t}\n\n\tfor label, field := range nonEmptyFields {\n\t\tif field.val == \"\" {\n\t\t\treturn fmt.Errorf(errorTmpl, label+\" is empty\")\n\t\t} else if field.checkSeparator && strings.Contains(field.val, keyPartSeparator) {\n\t\t\treturn fmt.Errorf(errorTmpl, label+separatorErrorMsg)\n\t\t}\n\t}\n\n\tswitch {\n\tcase len([]rune(s.Name)) > maxServiceNameLen:\n\t\treturn fmt.Errorf(errorTmpl, fmt.Sprintf(\"Name %q is too long, max len is %d symbols\", s.Name, maxServiceNameLen))\n\tcase !reRolloutType.MatchString(s.RolloutType):\n\t\treturn fmt.Errorf(errorTmpl, \"RolloutType is invalid\")\n\t}\n\treturn nil\n}", "func (t *Visibility_Visibility) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"Visibility_Visibility\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *UpdateWorkteamInput) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"UpdateWorkteamInput\"}\n\tif s.Description != nil && len(*s.Description) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Description\", 1))\n\t}\n\tif s.MemberDefinitions != nil && len(s.MemberDefinitions) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"MemberDefinitions\", 1))\n\t}\n\tif s.WorkteamName == nil {\n\t\tinvalidParams.Add(request.NewErrParamRequired(\"WorkteamName\"))\n\t}\n\tif s.WorkteamName != nil && len(*s.WorkteamName) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"WorkteamName\", 1))\n\t}\n\tif s.MemberDefinitions != nil {\n\t\tfor i, v := range s.MemberDefinitions {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"MemberDefinitions\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}", "func (s *SlotTypeValue) Validate() error {\n\tinvalidParams := request.ErrInvalidParams{Context: \"SlotTypeValue\"}\n\tif s.Synonyms != nil && len(s.Synonyms) < 1 {\n\t\tinvalidParams.Add(request.NewErrParamMinLen(\"Synonyms\", 1))\n\t}\n\tif s.SampleValue != nil {\n\t\tif err := s.SampleValue.Validate(); err != nil {\n\t\t\tinvalidParams.AddNested(\"SampleValue\", err.(request.ErrInvalidParams))\n\t\t}\n\t}\n\tif s.Synonyms != nil {\n\t\tfor i, v := range s.Synonyms {\n\t\t\tif v == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif err := v.Validate(); err != nil {\n\t\t\t\tinvalidParams.AddNested(fmt.Sprintf(\"%s[%v]\", \"Synonyms\", i), err.(request.ErrInvalidParams))\n\t\t\t}\n\t\t}\n\t}\n\n\tif invalidParams.Len() > 0 {\n\t\treturn invalidParams\n\t}\n\treturn nil\n}" ]
[ "0.6366166", "0.6255708", "0.62440985", "0.6219268", "0.6205969", "0.6186602", "0.61787015", "0.6151207", "0.6135345", "0.6129121", "0.61265224", "0.61265224", "0.60985357", "0.60598147", "0.60547787", "0.60132855", "0.5993056", "0.5990731", "0.59752667", "0.59422064", "0.59114707", "0.59090024", "0.5889592", "0.58741313", "0.5829609", "0.58170855", "0.58096683", "0.58095896", "0.58095545", "0.58024305", "0.5794755", "0.57862866", "0.57858443", "0.57791334", "0.5764243", "0.57606256", "0.57459706", "0.5732621", "0.5724816", "0.5721725", "0.5710794", "0.57104737", "0.5704633", "0.5703819", "0.5702953", "0.56983054", "0.56940216", "0.5690886", "0.5657812", "0.5649313", "0.56480217", "0.564582", "0.563624", "0.5627615", "0.5625255", "0.5619124", "0.5613144", "0.56088334", "0.5605432", "0.56024873", "0.55947214", "0.55911726", "0.5589795", "0.5585938", "0.55821085", "0.5582017", "0.5581614", "0.55808634", "0.5580246", "0.5574314", "0.5568627", "0.55618674", "0.5560738", "0.55515087", "0.5550786", "0.5550786", "0.5541505", "0.5539938", "0.55395836", "0.5536529", "0.5532453", "0.5530356", "0.55274034", "0.5516386", "0.55141157", "0.551397", "0.5513621", "0.5507534", "0.55044377", "0.5499806", "0.5497794", "0.5496284", "0.5494955", "0.5485755", "0.54851174", "0.5484035", "0.54840046", "0.5483409", "0.5483303", "0.5483193", "0.5481435" ]
0.0
-1
MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s DeleteSubscriptionDefinitionInput) MarshalFields(e protocol.FieldEncoder) error { e.SetValue(protocol.HeaderTarget, "Content-Type", protocol.StringValue("application/json"), protocol.Metadata{}) if s.SubscriptionDefinitionId != nil { v := *s.SubscriptionDefinitionId metadata := protocol.Metadata{} e.SetValue(protocol.PathTarget, "SubscriptionDefinitionId", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService9TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s OutputService6TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRestApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.ApiKeySource) > 0 {\n\t\tv := s.ApiKeySource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.BinaryMediaTypes != nil {\n\t\tv := s.BinaryMediaTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"binaryMediaTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EndpointConfiguration != nil {\n\t\tv := s.EndpointConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"endpointConfiguration\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MinimumCompressionSize != nil {\n\t\tv := *s.MinimumCompressionSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"minimumCompressionSize\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Policy != nil {\n\t\tv := *s.Policy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateCanaryInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ArtifactS3Location != nil {\n\t\tv := *s.ArtifactS3Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ArtifactS3Location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Code != nil {\n\t\tv := s.Code\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Code\", v, metadata)\n\t}\n\tif s.ExecutionRoleArn != nil {\n\t\tv := *s.ExecutionRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExecutionRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FailureRetentionPeriodInDays != nil {\n\t\tv := *s.FailureRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FailureRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RunConfig != nil {\n\t\tv := s.RunConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RunConfig\", v, metadata)\n\t}\n\tif s.RuntimeVersion != nil {\n\t\tv := *s.RuntimeVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RuntimeVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schedule != nil {\n\t\tv := s.Schedule\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Schedule\", v, metadata)\n\t}\n\tif s.SuccessRetentionPeriodInDays != nil {\n\t\tv := *s.SuccessRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"SuccessRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"Tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcConfig != nil {\n\t\tv := s.VpcConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"VpcConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewayRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAccessPointInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ClientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FileSystemId != nil {\n\t\tv := *s.FileSystemId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FileSystemId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PosixUser != nil {\n\t\tv := s.PosixUser\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PosixUser\", v, metadata)\n\t}\n\tif s.RootDirectory != nil {\n\t\tv := s.RootDirectory\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RootDirectory\", v, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CorsConfiguration != nil {\n\t\tv := s.CorsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"corsConfiguration\", v, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImportInfo != nil {\n\t\tv := s.ImportInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"importInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService15TestShapeItemDetailShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ID != nil {\n\t\tv := *s.ID\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ID\", protocol.StringValue(v), metadata)\n\t}\n\t// Skipping Type XML Attribute.\n\treturn nil\n}", "func (s CreateProxySessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Capabilities != nil {\n\t\tv := s.Capabilities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Capabilities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ExpiryMinutes != nil {\n\t\tv := *s.ExpiryMinutes\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExpiryMinutes\", protocol.Int64Value(v), metadata)\n\t}\n\tif len(s.GeoMatchLevel) > 0 {\n\t\tv := s.GeoMatchLevel\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GeoMatchLevel\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.GeoMatchParams != nil {\n\t\tv := s.GeoMatchParams\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"GeoMatchParams\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.NumberSelectionBehavior) > 0 {\n\t\tv := s.NumberSelectionBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"NumberSelectionBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.ParticipantPhoneNumbers != nil {\n\t\tv := s.ParticipantPhoneNumbers\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"ParticipantPhoneNumbers\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.VoiceConnectorId != nil {\n\t\tv := *s.VoiceConnectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"voiceConnectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewaySpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.KeyValue != nil {\n\t\tv := *s.KeyValue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"keyValue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateSignalingChannelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChannelARN != nil {\n\t\tv := *s.ChannelARN\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ChannelARN\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CurrentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SingleMasterConfiguration != nil {\n\t\tv := s.SingleMasterConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SingleMasterConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateThingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AttributePayload != nil {\n\t\tv := s.AttributePayload\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"attributePayload\", v, metadata)\n\t}\n\tif s.BillingGroupName != nil {\n\t\tv := *s.BillingGroupName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingGroupName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingTypeName != nil {\n\t\tv := *s.ThingTypeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"thingTypeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingName != nil {\n\t\tv := *s.ThingName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"thingName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func encodeSchema(w io.Writer, s *schema.Schema) (err error) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tew := errWriter{w: w}\n\tif s.Description != \"\" {\n\t\tew.writeFormat(`\"description\": %q, `, s.Description)\n\t}\n\tew.writeString(`\"type\": \"object\", `)\n\tew.writeString(`\"additionalProperties\": false, `)\n\tew.writeString(`\"properties\": {`)\n\tvar required []string\n\tvar notFirst bool\n\tfor _, key := range sortedFieldNames(s.Fields) {\n\t\tfield := s.Fields[key]\n\t\tif notFirst {\n\t\t\tew.writeString(\", \")\n\t\t}\n\t\tnotFirst = true\n\t\tif field.Required {\n\t\t\trequired = append(required, fmt.Sprintf(\"%q\", key))\n\t\t}\n\t\tew.err = encodeField(ew, key, field)\n\t\tif ew.err != nil {\n\t\t\treturn ew.err\n\t\t}\n\t}\n\tew.writeString(\"}\")\n\tif s.MinLen > 0 {\n\t\tew.writeFormat(`, \"minProperties\": %s`, strconv.FormatInt(int64(s.MinLen), 10))\n\t}\n\tif s.MaxLen > 0 {\n\t\tew.writeFormat(`, \"maxProperties\": %s`, strconv.FormatInt(int64(s.MaxLen), 10))\n\t}\n\n\tif len(required) > 0 {\n\t\tew.writeFormat(`, \"required\": [%s]`, strings.Join(required, \", \"))\n\t}\n\treturn ew.err\n}", "func (s OutputService15TestShapeItemShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ItemDetail != nil {\n\t\tv := s.ItemDetail\n\t\tattrs := make([]protocol.Attribute, 0, 1)\n\n\t\tif len(s.ItemDetail.Type) > 0 {\n\n\t\t\tv := s.ItemDetail.Type\n\t\t\tattrs = append(attrs, protocol.Attribute{Name: \"xsi:type\", Value: v, Meta: protocol.Metadata{}})\n\t\t}\n\t\tmetadata := protocol.Metadata{Attributes: attrs, XMLNamespacePrefix: \"xsi\", XMLNamespaceURI: \"http://www.w3.org/2001/XMLSchema-instance\"}\n\t\te.SetFields(protocol.BodyTarget, \"ItemDetail\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIPSetInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Activate != nil {\n\t\tv := *s.Activate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"activate\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Location != nil {\n\t\tv := *s.Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorId != nil {\n\t\tv := *s.DetectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IpSetId != nil {\n\t\tv := *s.IpSetId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"ipSetId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Robot) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.FleetArn != nil {\n\t\tv := *s.FleetArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"fleetArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.GreenGrassGroupId != nil {\n\t\tv := *s.GreenGrassGroupId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"greenGrassGroupId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentJob != nil {\n\t\tv := *s.LastDeploymentJob\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentJob\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentTime != nil {\n\t\tv := *s.LastDeploymentTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentTime\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Status) > 0 {\n\t\tv := s.Status\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"status\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAliasInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FunctionVersion != nil {\n\t\tv := *s.FunctionVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FunctionVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RoutingConfig != nil {\n\t\tv := s.RoutingConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RoutingConfig\", v, metadata)\n\t}\n\tif s.FunctionName != nil {\n\t\tv := *s.FunctionName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"FunctionName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeInputDeviceOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionState) > 0 {\n\t\tv := s.ConnectionState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.DeviceSettingsSyncState) > 0 {\n\t\tv := s.DeviceSettingsSyncState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deviceSettingsSyncState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.HdDeviceSettings != nil {\n\t\tv := s.HdDeviceSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"hdDeviceSettings\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MacAddress != nil {\n\t\tv := *s.MacAddress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"macAddress\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.NetworkSettings != nil {\n\t\tv := s.NetworkSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"networkSettings\", v, metadata)\n\t}\n\tif s.SerialNumber != nil {\n\t\tv := *s.SerialNumber\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"serialNumber\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateImageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DistributionConfigurationArn != nil {\n\t\tv := *s.DistributionConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"distributionConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnhancedImageMetadataEnabled != nil {\n\t\tv := *s.EnhancedImageMetadataEnabled\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enhancedImageMetadataEnabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImageRecipeArn != nil {\n\t\tv := *s.ImageRecipeArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"imageRecipeArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ImageTestsConfiguration != nil {\n\t\tv := s.ImageTestsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"imageTestsConfiguration\", v, metadata)\n\t}\n\tif s.InfrastructureConfigurationArn != nil {\n\t\tv := *s.InfrastructureConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"infrastructureConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s VpcLink) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SecurityGroupIds != nil {\n\t\tv := s.SecurityGroupIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"securityGroupIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.SubnetIds != nil {\n\t\tv := s.SubnetIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"subnetIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcLinkId != nil {\n\t\tv := *s.VpcLinkId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkStatus) > 0 {\n\t\tv := s.VpcLinkStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.VpcLinkStatusMessage != nil {\n\t\tv := *s.VpcLinkStatusMessage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatusMessage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkVersion) > 0 {\n\t\tv := s.VpcLinkVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkVersion\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.AuthorizationScopes != nil {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestModels != nil {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PayloadFormatVersion != nil {\n\t\tv := *s.PayloadFormatVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"payloadFormatVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestTemplates != nil {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.TlsConfig != nil {\n\t\tv := s.TlsConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"tlsConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateOTAUpdateInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Files != nil {\n\t\tv := s.Files\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"files\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiKeyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Expires != nil {\n\t\tv := *s.Expires\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"expires\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.BackendEnvironmentArn != nil {\n\t\tv := *s.BackendEnvironmentArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"backendEnvironmentArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnablePullRequestPreview != nil {\n\t\tv := *s.EnablePullRequestPreview\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enablePullRequestPreview\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnvironmentVariables != nil {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PullRequestEnvironmentName != nil {\n\t\tv := *s.PullRequestEnvironmentName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"pullRequestEnvironmentName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseId != nil {\n\t\tv := *s.RouteResponseId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeResponseId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePackageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PackageDescription != nil {\n\t\tv := *s.PackageDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageName != nil {\n\t\tv := *s.PackageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageSource != nil {\n\t\tv := s.PackageSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PackageSource\", v, metadata)\n\t}\n\tif len(s.PackageType) > 0 {\n\t\tv := s.PackageType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdatePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (s OutputService11TestShapeOutputService11TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-false-bool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Integer != nil {\n\t\tv := *s.Integer\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-int\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.RFC822TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-true-bool\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OauthToken != nil {\n\t\tv := *s.OauthToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"oauthToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Repository != nil {\n\t\tv := *s.Repository\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"repository\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualNodeSpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Backends != nil {\n\t\tv := s.Backends\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"backends\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\tif s.ServiceDiscovery != nil {\n\t\tv := s.ServiceDiscovery\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"serviceDiscovery\", v, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s NetworkPathComponent) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ComponentId != nil {\n\t\tv := *s.ComponentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ComponentType != nil {\n\t\tv := *s.ComponentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Egress != nil {\n\t\tv := s.Egress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Egress\", v, metadata)\n\t}\n\tif s.Ingress != nil {\n\t\tv := s.Ingress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Ingress\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService13TestShapeTimeContainer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Bar != nil {\n\t\tv := *s.Bar\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"bar\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"unixTimestamp\", QuotedFormatTime: false}, metadata)\n\t}\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\treturn nil\n}", "func (s ImportComponentInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChangeDescription != nil {\n\t\tv := *s.ChangeDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"changeDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Data != nil {\n\t\tv := *s.Data\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"data\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.KmsKeyId != nil {\n\t\tv := *s.KmsKeyId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"kmsKeyId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.SemanticVersion != nil {\n\t\tv := *s.SemanticVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"semanticVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Uri != nil {\n\t\tv := *s.Uri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"uri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CodeReview) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CodeReviewArn != nil {\n\t\tv := *s.CodeReviewArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeReviewArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedTimeStamp != nil {\n\t\tv := *s.CreatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CreatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedTimeStamp != nil {\n\t\tv := *s.LastUpdatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"LastUpdatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Metrics != nil {\n\t\tv := s.Metrics\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Metrics\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Owner != nil {\n\t\tv := *s.Owner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Owner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProviderType) > 0 {\n\t\tv := s.ProviderType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProviderType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PullRequestId != nil {\n\t\tv := *s.PullRequestId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PullRequestId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RepositoryName != nil {\n\t\tv := *s.RepositoryName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RepositoryName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SourceCodeType != nil {\n\t\tv := s.SourceCodeType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SourceCodeType\", v, metadata)\n\t}\n\tif len(s.State) > 0 {\n\t\tv := s.State\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"State\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.StateReason != nil {\n\t\tv := *s.StateReason\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StateReason\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s PutObjectOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentSHA256 != nil {\n\t\tv := *s.ContentSHA256\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ContentSHA256\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ETag != nil {\n\t\tv := *s.ETag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ETag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StorageClass) > 0 {\n\t\tv := s.StorageClass\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StorageClass\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s GetRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation2Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceBackend) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ClientPolicy != nil {\n\t\tv := s.ClientPolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"clientPolicy\", v, metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PolicyDocument != nil {\n\t\tv := *s.PolicyDocument\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policyDocument\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBucketInput) MarshalFields(e protocol.FieldEncoder) error {\n\n\tif len(s.ACL) > 0 {\n\t\tv := s.ACL\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-acl\", v, metadata)\n\t}\n\tif s.GrantFullControl != nil {\n\t\tv := *s.GrantFullControl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-full-control\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantRead != nil {\n\t\tv := *s.GrantRead\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantReadACP != nil {\n\t\tv := *s.GrantReadACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWrite != nil {\n\t\tv := *s.GrantWrite\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWriteACP != nil {\n\t\tv := *s.GrantWriteACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ObjectLockEnabledForBucket != nil {\n\t\tv := *s.ObjectLockEnabledForBucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-bucket-object-lock-enabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Bucket != nil {\n\t\tv := *s.Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"Bucket\", protocol.StringValue(v), metadata)\n\t}\n\tif s.CreateBucketConfiguration != nil {\n\t\tv := s.CreateBucketConfiguration\n\n\t\tmetadata := protocol.Metadata{XMLNamespaceURI: \"http://s3.amazonaws.com/doc/2006-03-01/\"}\n\t\te.SetFields(protocol.PayloadTarget, \"CreateBucketConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Pipeline) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Activities) > 0 {\n\t\tv := s.Activities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"activities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreationTime != nil {\n\t\tv := *s.CreationTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.LastUpdateTime != nil {\n\t\tv := *s.LastUpdateTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdateTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ReprocessingSummaries) > 0 {\n\t\tv := s.ReprocessingSummaries\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"reprocessingSummaries\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s VirtualNodeRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualNodeName != nil {\n\t\tv := *s.VirtualNodeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualNodeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetIntrospectionSchemaInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IncludeDirectives != nil {\n\t\tv := *s.IncludeDirectives\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"includeDirectives\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s Source) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Etag != nil {\n\t\tv := *s.Etag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"etag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Bucket != nil {\n\t\tv := *s.S3Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Bucket\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Key != nil {\n\t\tv := *s.S3Key\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Key\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OTAUpdateInfo) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsIotJobArn != nil {\n\t\tv := *s.AwsIotJobArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsIotJobId != nil {\n\t\tv := *s.AwsIotJobId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.CreationDate != nil {\n\t\tv := *s.CreationDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ErrorInfo != nil {\n\t\tv := s.ErrorInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"errorInfo\", v, metadata)\n\t}\n\tif s.LastModifiedDate != nil {\n\t\tv := *s.LastModifiedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastModifiedDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.OtaUpdateArn != nil {\n\t\tv := *s.OtaUpdateArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OtaUpdateFiles != nil {\n\t\tv := s.OtaUpdateFiles\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"otaUpdateFiles\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.OtaUpdateStatus) > 0 {\n\t\tv := s.OtaUpdateStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateModelOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateJobInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.HopDestinations != nil {\n\t\tv := s.HopDestinations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"hopDestinations\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\t}\n\tif s.AccelerationSettings != nil {\n\t\tv := s.AccelerationSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accelerationSettings\", v, metadata)\n\t}\n\tif len(s.BillingTagsSource) > 0 {\n\t\tv := s.BillingTagsSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingTagsSource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tvar ClientRequestToken string\n\tif s.ClientRequestToken != nil {\n\t\tClientRequestToken = *s.ClientRequestToken\n\t} else {\n\t\tClientRequestToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientRequestToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientRequestToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.JobTemplate != nil {\n\t\tv := *s.JobTemplate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"jobTemplate\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Priority != nil {\n\t\tv := *s.Priority\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"priority\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Queue != nil {\n\t\tv := *s.Queue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"queue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Role != nil {\n\t\tv := *s.Role\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"role\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Settings != nil {\n\t\tv := s.Settings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"settings\", v, metadata)\n\t}\n\tif len(s.SimulateReservedQueue) > 0 {\n\t\tv := s.SimulateReservedQueue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"simulateReservedQueue\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.StatusUpdateInterval) > 0 {\n\t\tv := s.StatusUpdateInterval\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"statusUpdateInterval\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.UserMetadata != nil {\n\t\tv := s.UserMetadata\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"userMetadata\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateBrokerStorageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"currentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TargetBrokerEBSVolumeInfo != nil {\n\t\tv := s.TargetBrokerEBSVolumeInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targetBrokerEBSVolumeInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ClusterArn != nil {\n\t\tv := *s.ClusterArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"clusterArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CustomCodeSigning) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CertificateChain != nil {\n\t\tv := s.CertificateChain\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"certificateChain\", v, metadata)\n\t}\n\tif s.HashAlgorithm != nil {\n\t\tv := *s.HashAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"hashAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Signature != nil {\n\t\tv := s.Signature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signature\", v, metadata)\n\t}\n\tif s.SignatureAlgorithm != nil {\n\t\tv := *s.SignatureAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"signatureAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetMacieSessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\treturn nil\n}", "func (s MeshRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s Resource) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Attributes) > 0 {\n\t\tv := s.Attributes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"attributes\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Feature != nil {\n\t\tv := *s.Feature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"feature\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Type != nil {\n\t\tv := *s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GatewayRouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.GatewayRouteName != nil {\n\t\tv := *s.GatewayRouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"gatewayRouteName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s RouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteName != nil {\n\t\tv := *s.RouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualRouterName != nil {\n\t\tv := *s.VirtualRouterName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualRouterName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorModelVersion != nil {\n\t\tv := *s.DetectorModelVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AttachPolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Category) > 0 {\n\t\tv := s.Category\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"category\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MaxSizeInMB != nil {\n\t\tv := *s.MaxSizeInMB\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"maxSizeInMB\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Partner != nil {\n\t\tv := *s.Partner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"partner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SigningConfiguration != nil {\n\t\tv := s.SigningConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingConfiguration\", v, metadata)\n\t}\n\tif s.SigningImageFormat != nil {\n\t\tv := s.SigningImageFormat\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingImageFormat\", v, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (v *Service) Encode(sw stream.Writer) error {\n\tif err := sw.WriteStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 7, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 1, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.ThriftName); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.ParentID != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 4, Type: wire.TI32}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := v.ParentID.Encode(sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 5, Type: wire.TList}); err != nil {\n\t\treturn err\n\t}\n\tif err := _List_Function_Encode(v.Functions, sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 6, Type: wire.TI32}); err != nil {\n\t\treturn err\n\t}\n\tif err := v.ModuleID.Encode(sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.Annotations != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 8, Type: wire.TMap}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := _Map_String_String_Encode(v.Annotations, sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn sw.WriteStructEnd()\n}", "func (s Product) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ActivationUrl != nil {\n\t\tv := *s.ActivationUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ActivationUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Categories != nil {\n\t\tv := s.Categories\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Categories\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CompanyName != nil {\n\t\tv := *s.CompanyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CompanyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationTypes != nil {\n\t\tv := s.IntegrationTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"IntegrationTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.MarketplaceUrl != nil {\n\t\tv := *s.MarketplaceUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"MarketplaceUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductArn != nil {\n\t\tv := *s.ProductArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductName != nil {\n\t\tv := *s.ProductName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductSubscriptionResourcePolicy != nil {\n\t\tv := *s.ProductSubscriptionResourcePolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductSubscriptionResourcePolicy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AwsLambdaFunctionLayer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CodeSize != nil {\n\t\tv := *s.CodeSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeSize\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s HttpAuthorization) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Sigv4 != nil {\n\t\tv := s.Sigv4\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"sigv4\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PipelineName != nil {\n\t\tv := *s.PipelineName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"pipelineName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}" ]
[ "0.63479704", "0.6247795", "0.6195172", "0.61806905", "0.61683095", "0.61200184", "0.6099719", "0.6069325", "0.6064495", "0.60124534", "0.6009836", "0.59606516", "0.59526104", "0.5935234", "0.5928707", "0.59224474", "0.5910614", "0.59063023", "0.58990103", "0.5884719", "0.58780664", "0.58758223", "0.58740026", "0.5870821", "0.58704156", "0.58583754", "0.5851065", "0.5847724", "0.584571", "0.5837251", "0.583382", "0.5820691", "0.5819901", "0.58150333", "0.5815032", "0.58111376", "0.5804827", "0.5802364", "0.5802092", "0.578717", "0.5780785", "0.57765293", "0.5774867", "0.5773512", "0.57650334", "0.5761848", "0.5759235", "0.5758919", "0.5750916", "0.5749155", "0.5746686", "0.574606", "0.5741942", "0.5740067", "0.57334137", "0.57329136", "0.57288283", "0.5720536", "0.57199717", "0.5709697", "0.57026315", "0.57025653", "0.57011104", "0.56961375", "0.5694661", "0.569277", "0.56852376", "0.568256", "0.5678673", "0.56765914", "0.5675795", "0.56648564", "0.5661323", "0.5660928", "0.56593114", "0.5657954", "0.56536096", "0.565022", "0.5645035", "0.56447184", "0.56441903", "0.56391424", "0.56385344", "0.56368303", "0.5635701", "0.5635248", "0.56317043", "0.5625839", "0.5625511", "0.56232154", "0.56216896", "0.56216896", "0.56204224", "0.5616888", "0.56134516", "0.5612859", "0.56120634", "0.56104606", "0.56095034", "0.56052333", "0.5590397" ]
0.0
-1
String returns the string representation
func (s DeleteSubscriptionDefinitionOutput) String() string { return awsutil.Prettify(s) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (s CreateQuickConnectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponse) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Addshifttraderequest) String() string {\n \n \n \n \n o.AcceptableIntervals = []string{\"\"} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (i Info) String() string {\n\ts, _ := i.toJSON()\n\treturn s\n}", "func (o *Botversionsummary) String() string {\n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (s CreateDataLakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSolutionVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Adjustablelivespeakerdetection) String() string {\n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateRateBasedRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (s RestoreFromRecoveryPointOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateWaveOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponseResult) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (z Zamowienia) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (i *Info) String() string {\n\tb, _ := json.Marshal(i)\n\treturn string(b)\n}", "func (s ProcessingFeatureStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ExportProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r RoomOccupancies) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Coretype) String() string {\n \n \n \n \n \n o.ValidationFields = []string{\"\"} \n \n o.ItemValidationFields = []string{\"\"} \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateLayerOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Limitchangerequestdetails) String() string {\n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s NetworkPathComponentDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (t Terms) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (s StartContactEvaluationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Interactionstatsalert) String() string {\n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Digitalcondition) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (r RoomOccupancy) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (d *Diagram) String() string { return toString(d) }", "func (o *Outboundroute) String() string {\n \n \n \n \n o.ClassificationTypes = []string{\"\"} \n \n \n o.ExternalTrunkBases = []Domainentityref{{}} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateCodeRepositoryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (p *Parms) String() string {\n\tout, _ := json.MarshalIndent(p, \"\", \"\\t\")\n\treturn string(out)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RUT) String() string {\n\treturn r.Format(DefaultFormatter)\n}", "func (s CreatePatchBaselineOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Crossplatformpolicycreate) String() string {\n \n \n \n \n \n \n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s BotVersionLocaleDetails) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestInitiated) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s DeleteMultiplexProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s LifeCycleLastTestReverted) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDocumentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateIntegrationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Commonruleconditions) String() string {\n o.Clauses = []Commonruleconditions{{}} \n o.Predicates = []Commonrulepredicate{{}} \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (t Test1s) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (o *Directrouting) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (s CreateContactFlowOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.7215058", "0.7215058", "0.72000957", "0.7199919", "0.7177383", "0.7166947", "0.7118059", "0.7087492", "0.70870787", "0.7079275", "0.70782894", "0.7067719", "0.7031721", "0.70269966", "0.7026298", "0.70251423", "0.7021565", "0.70164025", "0.701059", "0.7010184", "0.70022964", "0.6997043", "0.6996532", "0.6992619", "0.69909185", "0.69900763", "0.69862556", "0.6985364", "0.6975378", "0.69738907", "0.69624275", "0.6961772", "0.69603413", "0.69507927", "0.6946753", "0.69460964", "0.69460964", "0.6944943", "0.694029", "0.69369334", "0.69332623", "0.69287163", "0.692656", "0.6924643", "0.69216746", "0.69213074", "0.69181406", "0.6917802", "0.6911058", "0.69104654", "0.6909528", "0.690845", "0.690454", "0.6899065", "0.6896141", "0.6894107", "0.6894107", "0.6894107", "0.68921995", "0.68920684", "0.689124", "0.68893504", "0.688871", "0.6884391", "0.6882336", "0.6880731", "0.68767136", "0.68766147", "0.68766147", "0.68751997", "0.68735147", "0.68734384", "0.68731403", "0.6871602", "0.6869421", "0.68684965", "0.68677104", "0.68677104", "0.68677104", "0.68677104", "0.68673396", "0.68622416", "0.6862084", "0.6859391", "0.6857645", "0.6853781", "0.68523467", "0.6851581", "0.6846037", "0.6844023", "0.6843859", "0.68434954", "0.68419206", "0.68416274", "0.684033", "0.6839815", "0.68363225", "0.6835165", "0.68334675", "0.68327725", "0.6832733" ]
0.0
-1
MarshalFields encodes the AWS API shape using the passed in protocol encoder.
func (s DeleteSubscriptionDefinitionOutput) MarshalFields(e protocol.FieldEncoder) error { return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s CreateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService9TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s OutputService6TestShapeSingleStructure) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Warnings) > 0 {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRestApiOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.ApiKeySource) > 0 {\n\t\tv := s.ApiKeySource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.BinaryMediaTypes != nil {\n\t\tv := s.BinaryMediaTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"binaryMediaTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EndpointConfiguration != nil {\n\t\tv := s.EndpointConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"endpointConfiguration\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MinimumCompressionSize != nil {\n\t\tv := *s.MinimumCompressionSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"minimumCompressionSize\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Policy != nil {\n\t\tv := *s.Policy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateCanaryInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ArtifactS3Location != nil {\n\t\tv := *s.ArtifactS3Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ArtifactS3Location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Code != nil {\n\t\tv := s.Code\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Code\", v, metadata)\n\t}\n\tif s.ExecutionRoleArn != nil {\n\t\tv := *s.ExecutionRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExecutionRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FailureRetentionPeriodInDays != nil {\n\t\tv := *s.FailureRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FailureRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RunConfig != nil {\n\t\tv := s.RunConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RunConfig\", v, metadata)\n\t}\n\tif s.RuntimeVersion != nil {\n\t\tv := *s.RuntimeVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RuntimeVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schedule != nil {\n\t\tv := s.Schedule\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Schedule\", v, metadata)\n\t}\n\tif s.SuccessRetentionPeriodInDays != nil {\n\t\tv := *s.SuccessRetentionPeriodInDays\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"SuccessRetentionPeriodInDays\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"Tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcConfig != nil {\n\t\tv := s.VpcConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"VpcConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewayRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAccessPointInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ClientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FileSystemId != nil {\n\t\tv := *s.FileSystemId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FileSystemId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PosixUser != nil {\n\t\tv := s.PosixUser\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PosixUser\", v, metadata)\n\t}\n\tif s.RootDirectory != nil {\n\t\tv := s.RootDirectory\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RootDirectory\", v, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Api) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiEndpoint != nil {\n\t\tv := *s.ApiEndpoint\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiEndpoint\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CorsConfiguration != nil {\n\t\tv := s.CorsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"corsConfiguration\", v, metadata)\n\t}\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImportInfo != nil {\n\t\tv := s.ImportInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"importInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProtocolType) > 0 {\n\t\tv := s.ProtocolType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"protocolType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Warnings != nil {\n\t\tv := s.Warnings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"warnings\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s OutputService15TestShapeItemDetailShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ID != nil {\n\t\tv := *s.ID\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ID\", protocol.StringValue(v), metadata)\n\t}\n\t// Skipping Type XML Attribute.\n\treturn nil\n}", "func (s CreateProxySessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Capabilities != nil {\n\t\tv := s.Capabilities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Capabilities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ExpiryMinutes != nil {\n\t\tv := *s.ExpiryMinutes\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ExpiryMinutes\", protocol.Int64Value(v), metadata)\n\t}\n\tif len(s.GeoMatchLevel) > 0 {\n\t\tv := s.GeoMatchLevel\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"GeoMatchLevel\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.GeoMatchParams != nil {\n\t\tv := s.GeoMatchParams\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"GeoMatchParams\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.NumberSelectionBehavior) > 0 {\n\t\tv := s.NumberSelectionBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"NumberSelectionBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.ParticipantPhoneNumbers != nil {\n\t\tv := s.ParticipantPhoneNumbers\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"ParticipantPhoneNumbers\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.VoiceConnectorId != nil {\n\t\tv := *s.VoiceConnectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"voiceConnectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualGatewaySpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiKeySelectionExpression != nil {\n\t\tv := *s.ApiKeySelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeySelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisableSchemaValidation != nil {\n\t\tv := *s.DisableSchemaValidation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"disableSchemaValidation\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteSelectionExpression != nil {\n\t\tv := *s.RouteSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.KeyValue != nil {\n\t\tv := *s.KeyValue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"keyValue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateSignalingChannelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChannelARN != nil {\n\t\tv := *s.ChannelARN\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ChannelARN\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CurrentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SingleMasterConfiguration != nil {\n\t\tv := s.SingleMasterConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SingleMasterConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateThingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AttributePayload != nil {\n\t\tv := s.AttributePayload\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"attributePayload\", v, metadata)\n\t}\n\tif s.BillingGroupName != nil {\n\t\tv := *s.BillingGroupName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingGroupName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingTypeName != nil {\n\t\tv := *s.ThingTypeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"thingTypeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ThingName != nil {\n\t\tv := *s.ThingName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"thingName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func encodeSchema(w io.Writer, s *schema.Schema) (err error) {\n\tif s == nil {\n\t\treturn\n\t}\n\n\tew := errWriter{w: w}\n\tif s.Description != \"\" {\n\t\tew.writeFormat(`\"description\": %q, `, s.Description)\n\t}\n\tew.writeString(`\"type\": \"object\", `)\n\tew.writeString(`\"additionalProperties\": false, `)\n\tew.writeString(`\"properties\": {`)\n\tvar required []string\n\tvar notFirst bool\n\tfor _, key := range sortedFieldNames(s.Fields) {\n\t\tfield := s.Fields[key]\n\t\tif notFirst {\n\t\t\tew.writeString(\", \")\n\t\t}\n\t\tnotFirst = true\n\t\tif field.Required {\n\t\t\trequired = append(required, fmt.Sprintf(\"%q\", key))\n\t\t}\n\t\tew.err = encodeField(ew, key, field)\n\t\tif ew.err != nil {\n\t\t\treturn ew.err\n\t\t}\n\t}\n\tew.writeString(\"}\")\n\tif s.MinLen > 0 {\n\t\tew.writeFormat(`, \"minProperties\": %s`, strconv.FormatInt(int64(s.MinLen), 10))\n\t}\n\tif s.MaxLen > 0 {\n\t\tew.writeFormat(`, \"maxProperties\": %s`, strconv.FormatInt(int64(s.MaxLen), 10))\n\t}\n\n\tif len(required) > 0 {\n\t\tew.writeFormat(`, \"required\": [%s]`, strings.Join(required, \", \"))\n\t}\n\treturn ew.err\n}", "func (s OutputService15TestShapeItemShape) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ItemDetail != nil {\n\t\tv := s.ItemDetail\n\t\tattrs := make([]protocol.Attribute, 0, 1)\n\n\t\tif len(s.ItemDetail.Type) > 0 {\n\n\t\t\tv := s.ItemDetail.Type\n\t\t\tattrs = append(attrs, protocol.Attribute{Name: \"xsi:type\", Value: v, Meta: protocol.Metadata{}})\n\t\t}\n\t\tmetadata := protocol.Metadata{Attributes: attrs, XMLNamespacePrefix: \"xsi\", XMLNamespaceURI: \"http://www.w3.org/2001/XMLSchema-instance\"}\n\t\te.SetFields(protocol.BodyTarget, \"ItemDetail\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DomainName != nil {\n\t\tv := *s.DomainName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"domainName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIPSetInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Activate != nil {\n\t\tv := *s.Activate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"activate\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Location != nil {\n\t\tv := *s.Location\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"location\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorId != nil {\n\t\tv := *s.DetectorId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IpSetId != nil {\n\t\tv := *s.IpSetId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"ipSetId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.AccessLogSettings != nil {\n\t\tv := s.AccessLogSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accessLogSettings\", v, metadata)\n\t}\n\tif s.ClientCertificateId != nil {\n\t\tv := *s.ClientCertificateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientCertificateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DefaultRouteSettings != nil {\n\t\tv := s.DefaultRouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"defaultRouteSettings\", v, metadata)\n\t}\n\tif s.DeploymentId != nil {\n\t\tv := *s.DeploymentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deploymentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RouteSettings) > 0 {\n\t\tv := s.RouteSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"routeSettings\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StageVariables) > 0 {\n\t\tv := s.StageVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"stageVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetSigningPlatformInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Robot) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.FleetArn != nil {\n\t\tv := *s.FleetArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"fleetArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.GreenGrassGroupId != nil {\n\t\tv := *s.GreenGrassGroupId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"greenGrassGroupId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentJob != nil {\n\t\tv := *s.LastDeploymentJob\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentJob\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastDeploymentTime != nil {\n\t\tv := *s.LastDeploymentTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastDeploymentTime\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Status) > 0 {\n\t\tv := s.Status\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"status\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeInputDeviceOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionState) > 0 {\n\t\tv := s.ConnectionState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.DeviceSettingsSyncState) > 0 {\n\t\tv := s.DeviceSettingsSyncState\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deviceSettingsSyncState\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.HdDeviceSettings != nil {\n\t\tv := s.HdDeviceSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"hdDeviceSettings\", v, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MacAddress != nil {\n\t\tv := *s.MacAddress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"macAddress\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.NetworkSettings != nil {\n\t\tv := s.NetworkSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"networkSettings\", v, metadata)\n\t}\n\tif s.SerialNumber != nil {\n\t\tv := *s.SerialNumber\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"serialNumber\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAliasInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.FunctionVersion != nil {\n\t\tv := *s.FunctionVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FunctionVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RoutingConfig != nil {\n\t\tv := s.RoutingConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"RoutingConfig\", v, metadata)\n\t}\n\tif s.FunctionName != nil {\n\t\tv := *s.FunctionName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"FunctionName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateImageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DistributionConfigurationArn != nil {\n\t\tv := *s.DistributionConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"distributionConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnhancedImageMetadataEnabled != nil {\n\t\tv := *s.EnhancedImageMetadataEnabled\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enhancedImageMetadataEnabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImageRecipeArn != nil {\n\t\tv := *s.ImageRecipeArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"imageRecipeArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ImageTestsConfiguration != nil {\n\t\tv := s.ImageTestsConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"imageTestsConfiguration\", v, metadata)\n\t}\n\tif s.InfrastructureConfigurationArn != nil {\n\t\tv := *s.InfrastructureConfigurationArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"infrastructureConfigurationArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s VpcLink) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CreatedDate != nil {\n\t\tv := *s.CreatedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SecurityGroupIds != nil {\n\t\tv := s.SecurityGroupIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"securityGroupIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.SubnetIds != nil {\n\t\tv := s.SubnetIds\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"subnetIds\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.VpcLinkId != nil {\n\t\tv := *s.VpcLinkId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkStatus) > 0 {\n\t\tv := s.VpcLinkStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.VpcLinkStatusMessage != nil {\n\t\tv := *s.VpcLinkStatusMessage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkStatusMessage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.VpcLinkVersion) > 0 {\n\t\tv := s.VpcLinkVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"vpcLinkVersion\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.AuthorizationScopes != nil {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestModels != nil {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiGatewayManaged != nil {\n\t\tv := *s.ApiGatewayManaged\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiGatewayManaged\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PayloadFormatVersion != nil {\n\t\tv := *s.PayloadFormatVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"payloadFormatVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RequestParameters != nil {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RequestTemplates != nil {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.TlsConfig != nil {\n\t\tv := s.TlsConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"tlsConfig\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateOTAUpdateInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Files != nil {\n\t\tv := s.Files\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"files\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.RoleArn != nil {\n\t\tv := *s.RoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"roleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"tags\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateIntegrationInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiKeyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Expires != nil {\n\t\tv := *s.Expires\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"expires\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.BackendEnvironmentArn != nil {\n\t\tv := *s.BackendEnvironmentArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"backendEnvironmentArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnablePullRequestPreview != nil {\n\t\tv := *s.EnablePullRequestPreview\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enablePullRequestPreview\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnvironmentVariables != nil {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PullRequestEnvironmentName != nil {\n\t\tv := *s.PullRequestEnvironmentName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"pullRequestEnvironmentName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseId != nil {\n\t\tv := *s.RouteResponseId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeResponseId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePackageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PackageDescription != nil {\n\t\tv := *s.PackageDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageName != nil {\n\t\tv := *s.PackageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PackageSource != nil {\n\t\tv := s.PackageSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"PackageSource\", v, metadata)\n\t}\n\tif len(s.PackageType) > 0 {\n\t\tv := s.PackageType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PackageType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdatePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (s OutputService11TestShapeOutputService11TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-false-bool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Integer != nil {\n\t\tv := *s.Integer\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-int\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.RFC822TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-true-bool\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s CreateRouteResponseInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ResponseModels) > 0 {\n\t\tv := s.ResponseModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.ResponseParameters) > 0 {\n\t\tv := s.ResponseParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"responseParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteResponseKey != nil {\n\t\tv := *s.RouteResponseKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OauthToken != nil {\n\t\tv := *s.OauthToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"oauthToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Repository != nil {\n\t\tv := *s.Repository\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"repository\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s GetApiInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.Tags) > 0 {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s VirtualNodeSpec) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.BackendDefaults != nil {\n\t\tv := s.BackendDefaults\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"backendDefaults\", v, metadata)\n\t}\n\tif s.Backends != nil {\n\t\tv := s.Backends\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"backends\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Listeners != nil {\n\t\tv := s.Listeners\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"listeners\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Logging != nil {\n\t\tv := s.Logging\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"logging\", v, metadata)\n\t}\n\tif s.ServiceDiscovery != nil {\n\t\tv := s.ServiceDiscovery\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"serviceDiscovery\", v, metadata)\n\t}\n\treturn nil\n}", "func (s Integration) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s NetworkPathComponent) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ComponentId != nil {\n\t\tv := *s.ComponentId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ComponentType != nil {\n\t\tv := *s.ComponentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ComponentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Egress != nil {\n\t\tv := s.Egress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Egress\", v, metadata)\n\t}\n\tif s.Ingress != nil {\n\t\tv := s.Ingress\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Ingress\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateBranchInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableAutoBuild != nil {\n\t\tv := *s.EnableAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableNotification != nil {\n\t\tv := *s.EnableNotification\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableNotification\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Framework != nil {\n\t\tv := *s.Framework\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"framework\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Stage) > 0 {\n\t\tv := s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Ttl != nil {\n\t\tv := *s.Ttl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ttl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BranchName != nil {\n\t\tv := *s.BranchName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"branchName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService13TestShapeTimeContainer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Bar != nil {\n\t\tv := *s.Bar\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"bar\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"unixTimestamp\", QuotedFormatTime: false}, metadata)\n\t}\n\tif s.Foo != nil {\n\t\tv := *s.Foo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"foo\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\treturn nil\n}", "func (s ImportComponentInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ChangeDescription != nil {\n\t\tv := *s.ChangeDescription\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"changeDescription\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tvar ClientToken string\n\tif s.ClientToken != nil {\n\t\tClientToken = *s.ClientToken\n\t} else {\n\t\tClientToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Data != nil {\n\t\tv := *s.Data\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"data\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.KmsKeyId != nil {\n\t\tv := *s.KmsKeyId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"kmsKeyId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.SemanticVersion != nil {\n\t\tv := *s.SemanticVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"semanticVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Uri != nil {\n\t\tv := *s.Uri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"uri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Route) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CodeReview) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CodeReviewArn != nil {\n\t\tv := *s.CodeReviewArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeReviewArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedTimeStamp != nil {\n\t\tv := *s.CreatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CreatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedTimeStamp != nil {\n\t\tv := *s.LastUpdatedTimeStamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"LastUpdatedTimeStamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Metrics != nil {\n\t\tv := s.Metrics\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"Metrics\", v, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Owner != nil {\n\t\tv := *s.Owner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Owner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ProviderType) > 0 {\n\t\tv := s.ProviderType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProviderType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.PullRequestId != nil {\n\t\tv := *s.PullRequestId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"PullRequestId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RepositoryName != nil {\n\t\tv := *s.RepositoryName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"RepositoryName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SourceCodeType != nil {\n\t\tv := s.SourceCodeType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"SourceCodeType\", v, metadata)\n\t}\n\tif len(s.State) > 0 {\n\t\tv := s.State\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"State\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.StateReason != nil {\n\t\tv := *s.StateReason\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StateReason\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Type) > 0 {\n\t\tv := s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Type\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s PutObjectOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentSHA256 != nil {\n\t\tv := *s.ContentSHA256\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ContentSHA256\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ETag != nil {\n\t\tv := *s.ETag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ETag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.StorageClass) > 0 {\n\t\tv := s.StorageClass\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"StorageClass\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\treturn nil\n}", "func (s GetRouteOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiKeyRequired != nil {\n\t\tv := *s.ApiKeyRequired\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiKeyRequired\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.AuthorizationScopes) > 0 {\n\t\tv := s.AuthorizationScopes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"authorizationScopes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.AuthorizationType) > 0 {\n\t\tv := s.AuthorizationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AuthorizerId != nil {\n\t\tv := *s.AuthorizerId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"authorizerId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelSelectionExpression != nil {\n\t\tv := *s.ModelSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OperationName != nil {\n\t\tv := *s.OperationName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"operationName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.RequestModels) > 0 {\n\t\tv := s.RequestModels\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestModels\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetFields(k1, v1)\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.RouteId != nil {\n\t\tv := *s.RouteId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteKey != nil {\n\t\tv := *s.RouteKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteResponseSelectionExpression != nil {\n\t\tv := *s.RouteResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation1Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetStageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.StageName != nil {\n\t\tv := *s.StageName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"stageName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateAppInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.BasicAuthCredentials != nil {\n\t\tv := *s.BasicAuthCredentials\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"basicAuthCredentials\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.BuildSpec != nil {\n\t\tv := *s.BuildSpec\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"buildSpec\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.CustomRules) > 0 {\n\t\tv := s.CustomRules\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"customRules\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.EnableBasicAuth != nil {\n\t\tv := *s.EnableBasicAuth\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBasicAuth\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.EnableBranchAutoBuild != nil {\n\t\tv := *s.EnableBranchAutoBuild\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"enableBranchAutoBuild\", protocol.BoolValue(v), metadata)\n\t}\n\tif len(s.EnvironmentVariables) > 0 {\n\t\tv := s.EnvironmentVariables\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"environmentVariables\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.IamServiceRoleArn != nil {\n\t\tv := *s.IamServiceRoleArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"iamServiceRoleArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Platform) > 0 {\n\t\tv := s.Platform\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platform\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.AppId != nil {\n\t\tv := *s.AppId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"appId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OutputService1TestShapeOutputService1TestCaseOperation2Output) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Char != nil {\n\t\tv := *s.Char\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Char\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Double != nil {\n\t\tv := *s.Double\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Double\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.FalseBool != nil {\n\t\tv := *s.FalseBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FalseBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Float != nil {\n\t\tv := *s.Float\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Float\", protocol.Float64Value(v), metadata)\n\t}\n\tif s.Float64s != nil {\n\t\tv := s.Float64s\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Float64s\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Float64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Long != nil {\n\t\tv := *s.Long\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Long\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Num != nil {\n\t\tv := *s.Num\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"FooNum\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Str != nil {\n\t\tv := *s.Str\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Str\", protocol.StringValue(v), metadata)\n\t}\n\tif s.Timestamp != nil {\n\t\tv := *s.Timestamp\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Timestamp\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.ISO8601TimeFormatName, QuotedFormatTime: false}, metadata)\n\t}\n\tif s.TrueBool != nil {\n\t\tv := *s.TrueBool\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"TrueBool\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.ImaHeader != nil {\n\t\tv := *s.ImaHeader\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"ImaHeader\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ImaHeaderLocation != nil {\n\t\tv := *s.ImaHeaderLocation\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"X-Foo\", protocol.StringValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s GetIntegrationOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ConnectionId != nil {\n\t\tv := *s.ConnectionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ConnectionType) > 0 {\n\t\tv := s.ConnectionType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"connectionType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.ContentHandlingStrategy) > 0 {\n\t\tv := s.ContentHandlingStrategy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentHandlingStrategy\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.CredentialsArn != nil {\n\t\tv := *s.CredentialsArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"credentialsArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationId != nil {\n\t\tv := *s.IntegrationId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationMethod != nil {\n\t\tv := *s.IntegrationMethod\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationMethod\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationResponseSelectionExpression != nil {\n\t\tv := *s.IntegrationResponseSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationResponseSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.IntegrationType) > 0 {\n\t\tv := s.IntegrationType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationType\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IntegrationUri != nil {\n\t\tv := *s.IntegrationUri\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"integrationUri\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.PassthroughBehavior) > 0 {\n\t\tv := s.PassthroughBehavior\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"passthroughBehavior\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.RequestParameters) > 0 {\n\t\tv := s.RequestParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif len(s.RequestTemplates) > 0 {\n\t\tv := s.RequestTemplates\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"requestTemplates\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.TemplateSelectionExpression != nil {\n\t\tv := *s.TemplateSelectionExpression\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"templateSelectionExpression\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TimeoutInMillis != nil {\n\t\tv := *s.TimeoutInMillis\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"timeoutInMillis\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s VirtualServiceBackend) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ClientPolicy != nil {\n\t\tv := s.ClientPolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"clientPolicy\", v, metadata)\n\t}\n\tif s.VirtualServiceName != nil {\n\t\tv := *s.VirtualServiceName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualServiceName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreatePolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PolicyDocument != nil {\n\t\tv := *s.PolicyDocument\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"policyDocument\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateBucketInput) MarshalFields(e protocol.FieldEncoder) error {\n\n\tif len(s.ACL) > 0 {\n\t\tv := s.ACL\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-acl\", v, metadata)\n\t}\n\tif s.GrantFullControl != nil {\n\t\tv := *s.GrantFullControl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-full-control\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantRead != nil {\n\t\tv := *s.GrantRead\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantReadACP != nil {\n\t\tv := *s.GrantReadACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-read-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWrite != nil {\n\t\tv := *s.GrantWrite\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write\", protocol.StringValue(v), metadata)\n\t}\n\tif s.GrantWriteACP != nil {\n\t\tv := *s.GrantWriteACP\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-grant-write-acp\", protocol.StringValue(v), metadata)\n\t}\n\tif s.ObjectLockEnabledForBucket != nil {\n\t\tv := *s.ObjectLockEnabledForBucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.HeaderTarget, \"x-amz-bucket-object-lock-enabled\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Bucket != nil {\n\t\tv := *s.Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"Bucket\", protocol.StringValue(v), metadata)\n\t}\n\tif s.CreateBucketConfiguration != nil {\n\t\tv := s.CreateBucketConfiguration\n\n\t\tmetadata := protocol.Metadata{XMLNamespaceURI: \"http://s3.amazonaws.com/doc/2006-03-01/\"}\n\t\te.SetFields(protocol.PayloadTarget, \"CreateBucketConfiguration\", v, metadata)\n\t}\n\treturn nil\n}", "func (s UpdateApiMappingOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingId != nil {\n\t\tv := *s.ApiMappingId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ApiMappingKey != nil {\n\t\tv := *s.ApiMappingKey\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"apiMappingKey\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Stage != nil {\n\t\tv := *s.Stage\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"stage\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Pipeline) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Activities) > 0 {\n\t\tv := s.Activities\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"activities\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreationTime != nil {\n\t\tv := *s.CreationTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.LastUpdateTime != nil {\n\t\tv := *s.LastUpdateTime\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdateTime\", protocol.TimeValue{V: v, Format: protocol.UnixTimeFormat}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.ReprocessingSummaries) > 0 {\n\t\tv := s.ReprocessingSummaries\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"reprocessingSummaries\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s VirtualNodeRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualNodeName != nil {\n\t\tv := *s.VirtualNodeName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualNodeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetIntrospectionSchemaInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Format) > 0 {\n\t\tv := s.Format\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"format\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.IncludeDirectives != nil {\n\t\tv := *s.IncludeDirectives\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"includeDirectives\", protocol.BoolValue(v), metadata)\n\t}\n\treturn nil\n}", "func (s Source) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Architecture) > 0 {\n\t\tv := s.Architecture\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"architecture\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Etag != nil {\n\t\tv := *s.Etag\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"etag\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Bucket != nil {\n\t\tv := *s.S3Bucket\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Bucket\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.S3Key != nil {\n\t\tv := *s.S3Key\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"s3Key\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s OTAUpdateInfo) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.AdditionalParameters != nil {\n\t\tv := s.AdditionalParameters\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"additionalParameters\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.AwsIotJobArn != nil {\n\t\tv := *s.AwsIotJobArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsIotJobId != nil {\n\t\tv := *s.AwsIotJobId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"awsIotJobId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.AwsJobExecutionsRolloutConfig != nil {\n\t\tv := s.AwsJobExecutionsRolloutConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobExecutionsRolloutConfig\", v, metadata)\n\t}\n\tif s.AwsJobPresignedUrlConfig != nil {\n\t\tv := s.AwsJobPresignedUrlConfig\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"awsJobPresignedUrlConfig\", v, metadata)\n\t}\n\tif s.CreationDate != nil {\n\t\tv := *s.CreationDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"creationDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ErrorInfo != nil {\n\t\tv := s.ErrorInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"errorInfo\", v, metadata)\n\t}\n\tif s.LastModifiedDate != nil {\n\t\tv := *s.LastModifiedDate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastModifiedDate\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.OtaUpdateArn != nil {\n\t\tv := *s.OtaUpdateArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.OtaUpdateFiles != nil {\n\t\tv := s.OtaUpdateFiles\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"otaUpdateFiles\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.OtaUpdateId != nil {\n\t\tv := *s.OtaUpdateId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.OtaUpdateStatus) > 0 {\n\t\tv := s.OtaUpdateStatus\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"otaUpdateStatus\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Protocols != nil {\n\t\tv := s.Protocols\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"protocols\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif len(s.TargetSelection) > 0 {\n\t\tv := s.TargetSelection\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"targetSelection\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Targets != nil {\n\t\tv := s.Targets\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targets\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (s CreateModelOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ContentType != nil {\n\t\tv := *s.ContentType\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"contentType\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Schema != nil {\n\t\tv := *s.Schema\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"schema\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s CreateJobInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.HopDestinations != nil {\n\t\tv := s.HopDestinations\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"hopDestinations\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\t}\n\tif s.AccelerationSettings != nil {\n\t\tv := s.AccelerationSettings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"accelerationSettings\", v, metadata)\n\t}\n\tif len(s.BillingTagsSource) > 0 {\n\t\tv := s.BillingTagsSource\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"billingTagsSource\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tvar ClientRequestToken string\n\tif s.ClientRequestToken != nil {\n\t\tClientRequestToken = *s.ClientRequestToken\n\t} else {\n\t\tClientRequestToken = protocol.GetIdempotencyToken()\n\t}\n\t{\n\t\tv := ClientRequestToken\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"clientRequestToken\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.JobTemplate != nil {\n\t\tv := *s.JobTemplate\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"jobTemplate\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Priority != nil {\n\t\tv := *s.Priority\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"priority\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Queue != nil {\n\t\tv := *s.Queue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"queue\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Role != nil {\n\t\tv := *s.Role\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"role\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Settings != nil {\n\t\tv := s.Settings\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"settings\", v, metadata)\n\t}\n\tif len(s.SimulateReservedQueue) > 0 {\n\t\tv := s.SimulateReservedQueue\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"simulateReservedQueue\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif len(s.StatusUpdateInterval) > 0 {\n\t\tv := s.StatusUpdateInterval\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"statusUpdateInterval\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.Tags != nil {\n\t\tv := s.Tags\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"tags\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.UserMetadata != nil {\n\t\tv := s.UserMetadata\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"userMetadata\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\treturn nil\n}", "func (s UpdateBrokerStorageInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.CurrentVersion != nil {\n\t\tv := *s.CurrentVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"currentVersion\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.TargetBrokerEBSVolumeInfo != nil {\n\t\tv := s.TargetBrokerEBSVolumeInfo\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"targetBrokerEBSVolumeInfo\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.ClusterArn != nil {\n\t\tv := *s.ClusterArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"clusterArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetMacieSessionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\treturn nil\n}", "func (s CustomCodeSigning) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.CertificateChain != nil {\n\t\tv := s.CertificateChain\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"certificateChain\", v, metadata)\n\t}\n\tif s.HashAlgorithm != nil {\n\t\tv := *s.HashAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"hashAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Signature != nil {\n\t\tv := s.Signature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signature\", v, metadata)\n\t}\n\tif s.SignatureAlgorithm != nil {\n\t\tv := *s.SignatureAlgorithm\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"signatureAlgorithm\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s MeshRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s Resource) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif len(s.Attributes) > 0 {\n\t\tv := s.Attributes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tms0 := e.Map(protocol.BodyTarget, \"attributes\", metadata)\n\t\tms0.Start()\n\t\tfor k1, v1 := range v {\n\t\t\tms0.MapSetValue(k1, protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tms0.End()\n\n\t}\n\tif s.Feature != nil {\n\t\tv := *s.Feature\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"feature\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Type != nil {\n\t\tv := *s.Type\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"type\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GatewayRouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.GatewayRouteName != nil {\n\t\tv := *s.GatewayRouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"gatewayRouteName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualGatewayName != nil {\n\t\tv := *s.VirtualGatewayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualGatewayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s RouteRef) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.LastUpdatedAt != nil {\n\t\tv := *s.LastUpdatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"lastUpdatedAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: protocol.UnixTimeFormatName, QuotedFormatTime: true}, metadata)\n\t}\n\tif s.MeshName != nil {\n\t\tv := *s.MeshName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MeshOwner != nil {\n\t\tv := *s.MeshOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"meshOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ResourceOwner != nil {\n\t\tv := *s.ResourceOwner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"resourceOwner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.RouteName != nil {\n\t\tv := *s.RouteName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"routeName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Version != nil {\n\t\tv := *s.Version\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"version\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.VirtualRouterName != nil {\n\t\tv := *s.VirtualRouterName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"virtualRouterName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Pipeline != nil {\n\t\tv := s.Pipeline\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"pipeline\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribeDetectorModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.DetectorModelName != nil {\n\t\tv := *s.DetectorModelName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"detectorModelName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.DetectorModelVersion != nil {\n\t\tv := *s.DetectorModelVersion\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.QueryTarget, \"version\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AttachPolicyInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PolicyName != nil {\n\t\tv := *s.PolicyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"policyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (v *Service) Encode(sw stream.Writer) error {\n\tif err := sw.WriteStructBegin(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 7, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.Name); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 1, Type: wire.TBinary}); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteString(v.ThriftName); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.ParentID != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 4, Type: wire.TI32}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := v.ParentID.Encode(sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 5, Type: wire.TList}); err != nil {\n\t\treturn err\n\t}\n\tif err := _List_Function_Encode(v.Functions, sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 6, Type: wire.TI32}); err != nil {\n\t\treturn err\n\t}\n\tif err := v.ModuleID.Encode(sw); err != nil {\n\t\treturn err\n\t}\n\tif err := sw.WriteFieldEnd(); err != nil {\n\t\treturn err\n\t}\n\n\tif v.Annotations != nil {\n\t\tif err := sw.WriteFieldBegin(stream.FieldHeader{ID: 8, Type: wire.TMap}); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := _Map_String_String_Encode(v.Annotations, sw); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := sw.WriteFieldEnd(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn sw.WriteStructEnd()\n}", "func (s GetSigningPlatformOutput) MarshalFields(e protocol.FieldEncoder) error {\n\tif len(s.Category) > 0 {\n\t\tv := s.Category\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"category\", protocol.QuotedValue{ValueMarshaler: v}, metadata)\n\t}\n\tif s.DisplayName != nil {\n\t\tv := *s.DisplayName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"displayName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.MaxSizeInMB != nil {\n\t\tv := *s.MaxSizeInMB\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"maxSizeInMB\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Partner != nil {\n\t\tv := *s.Partner\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"partner\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.PlatformId != nil {\n\t\tv := *s.PlatformId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"platformId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.SigningConfiguration != nil {\n\t\tv := s.SigningConfiguration\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingConfiguration\", v, metadata)\n\t}\n\tif s.SigningImageFormat != nil {\n\t\tv := s.SigningImageFormat\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"signingImageFormat\", v, metadata)\n\t}\n\tif s.Target != nil {\n\t\tv := *s.Target\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"target\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s Product) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.ActivationUrl != nil {\n\t\tv := *s.ActivationUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ActivationUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Categories != nil {\n\t\tv := s.Categories\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"Categories\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.CompanyName != nil {\n\t\tv := *s.CompanyName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CompanyName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.IntegrationTypes != nil {\n\t\tv := s.IntegrationTypes\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"IntegrationTypes\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.MarketplaceUrl != nil {\n\t\tv := *s.MarketplaceUrl\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"MarketplaceUrl\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductArn != nil {\n\t\tv := *s.ProductArn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductArn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductName != nil {\n\t\tv := *s.ProductName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ProductSubscriptionResourcePolicy != nil {\n\t\tv := *s.ProductSubscriptionResourcePolicy\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"ProductSubscriptionResourcePolicy\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s AwsLambdaFunctionLayer) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"Arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CodeSize != nil {\n\t\tv := *s.CodeSize\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"CodeSize\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (s HttpAuthorization) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Sigv4 != nil {\n\t\tv := s.Sigv4\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetFields(protocol.BodyTarget, \"sigv4\", v, metadata)\n\t}\n\treturn nil\n}", "func (s DescribePipelineInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.PipelineName != nil {\n\t\tv := *s.PipelineName\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"pipelineName\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s GetModelInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/x-amz-json-1.1\"), protocol.Metadata{})\n\n\tif s.ApiId != nil {\n\t\tv := *s.ApiId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"apiId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.ModelId != nil {\n\t\tv := *s.ModelId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"modelId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}" ]
[ "0.6348559", "0.6248897", "0.6195551", "0.6180413", "0.61684614", "0.61208856", "0.6100623", "0.6070698", "0.606548", "0.6012609", "0.60108584", "0.5961231", "0.5953864", "0.5934938", "0.5929273", "0.5922881", "0.5910155", "0.59065044", "0.59003735", "0.58856225", "0.58790755", "0.5875828", "0.5874432", "0.5872241", "0.58716893", "0.5858529", "0.5851449", "0.58507365", "0.5844942", "0.5837428", "0.5833994", "0.58214754", "0.5820069", "0.58158517", "0.58149785", "0.58125305", "0.580506", "0.5803897", "0.5803712", "0.578714", "0.57817864", "0.5777309", "0.57750463", "0.57733595", "0.5765925", "0.5761909", "0.57602566", "0.5759691", "0.5752248", "0.5750325", "0.57488763", "0.5747476", "0.57432723", "0.5740528", "0.5733633", "0.5733325", "0.57294506", "0.5721927", "0.5720165", "0.571053", "0.570292", "0.5702867", "0.57019335", "0.56969184", "0.56954247", "0.5693915", "0.5686742", "0.56838375", "0.5679277", "0.56771725", "0.56763923", "0.5665559", "0.5661512", "0.56612706", "0.5660435", "0.56588036", "0.56538945", "0.5650536", "0.5646301", "0.56446356", "0.5644526", "0.5639443", "0.5637914", "0.56363106", "0.5635751", "0.5635708", "0.5631697", "0.5626627", "0.56260794", "0.56240636", "0.5623764", "0.5623764", "0.56213856", "0.56168675", "0.561474", "0.56128246", "0.56114304", "0.561078", "0.5609868", "0.56065774", "0.5589743" ]
0.0
-1
Send marshals and sends the DeleteSubscriptionDefinition API request.
func (r DeleteSubscriptionDefinitionRequest) Send(ctx context.Context) (*DeleteSubscriptionDefinitionResponse, error) { r.Request.SetContext(ctx) err := r.Request.Send() if err != nil { return nil, err } resp := &DeleteSubscriptionDefinitionResponse{ DeleteSubscriptionDefinitionOutput: r.Request.Data.(*DeleteSubscriptionDefinitionOutput), response: &aws.Response{Request: r.Request}, } return resp, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r DeleteResourceDefinitionRequest) Send(ctx context.Context) (*DeleteResourceDefinitionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DeleteResourceDefinitionResponse{\n\t\tDeleteResourceDefinitionOutput: r.Request.Data.(*DeleteResourceDefinitionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (client BaseClient) DeleteSubscription(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result Error, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.DeleteSubscription\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.DeleteSubscriptionPreparer(ctx, subscriptionID, APIVersion, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.DeleteSubscriptionSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.DeleteSubscriptionResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (client BaseClient) DeleteSubscriptionResponder(resp *http.Response) (result Error, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusBadRequest,http.StatusForbidden,http.StatusNotFound,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (client *KeyVaultClient) deleteSasDefinitionCreateRequest(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, options *KeyVaultClientDeleteSasDefinitionOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/storage/{storage-account-name}/sas/{sas-definition-name}\"\n\tif storageAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter storageAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{storage-account-name}\", url.PathEscape(storageAccountName))\n\tif sasDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sasDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sas-definition-name}\", url.PathEscape(sasDefinitionName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *SchemaRegistryClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, schemaGroupName string, options *SchemaRegistryClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventHub/namespaces/{namespaceName}/schemagroups/{schemaGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif schemaGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter schemaGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{schemaGroupName}\", url.PathEscape(schemaGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-10-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client NotificationDataPlaneClient) deleteSubscription(ctx context.Context, request common.OCIRequest) (common.OCIResponse, error) {\n\thttpRequest, err := request.HTTPRequest(http.MethodDelete, \"/subscriptions/{subscriptionId}\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response DeleteSubscriptionResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func DeleteSubscription(c *gin.Context) {\n\tsubscriptionId := c.Param(\"subscriptionId\")\n\tself := context.AMF_Self()\n\tproblem := producer.DeleteAMFEventSubscription(self, subscriptionId)\n\tif problem.Cause != \"\" {\n\t\tc.JSON(int(problem.Status), problem)\n\t} else {\n\t\tc.JSON(http.StatusOK, gin.H{})\n\t}\n}", "func (client *RegistrationDefinitionsClient) deleteCreateRequest(ctx context.Context, registrationDefinitionID string, scope string, options *RegistrationDefinitionsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.ManagedServices/registrationDefinitions/{registrationDefinitionId}\"\n\tif registrationDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter registrationDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registrationDefinitionId}\", url.PathEscape(registrationDefinitionID))\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (s DeleteSubscriptionDefinitionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.SubscriptionDefinitionId != nil {\n\t\tv := *s.SubscriptionDefinitionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"SubscriptionDefinitionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (client *SubscriptionClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, sid string, ifMatch string, options *SubscriptionClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/subscriptions/{sid}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif sid == \"\" {\n\t\treturn nil, errors.New(\"parameter sid cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sid}\", url.PathEscape(sid))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"If-Match\"] = []string{ifMatch}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *RedfishClient) DeleteSubscriptionDetail(device *RedfishDevice) (*http.Response, error) {\n\treq, err := http.NewRequest(\"DELETE\", device.Location, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Close = true\n\tauth := device.Username + \":\" + string(device.Password)\n\tBasicauth := \"Basic \" + base64.StdEncoding.EncodeToString([]byte(auth))\n\treq.Header.Add(\"Authorization\", Basicauth)\n\treq.Header.Add(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Close = true\n\n\tlutilconf.TLSConfMutex.RLock()\n\tresp, err := client.httpClient.Do(req)\n\tlutilconf.TLSConfMutex.RUnlock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp, nil\n}", "func (client NotificationDataPlaneClient) DeleteSubscription(ctx context.Context, request DeleteSubscriptionRequest) (response DeleteSubscriptionResponse, err error) {\n\tvar ociResponse common.OCIResponse\n\tpolicy := common.NoRetryPolicy()\n\tif request.RetryPolicy() != nil {\n\t\tpolicy = *request.RetryPolicy()\n\t}\n\tociResponse, err = common.Retry(ctx, request, client.deleteSubscription, policy)\n\tif err != nil {\n\t\tif ociResponse != nil {\n\t\t\tresponse = DeleteSubscriptionResponse{RawResponse: ociResponse.HTTPResponse()}\n\t\t}\n\t\treturn\n\t}\n\tif convertedResponse, ok := ociResponse.(DeleteSubscriptionResponse); ok {\n\t\tresponse = convertedResponse\n\t} else {\n\t\terr = fmt.Errorf(\"failed to convert OCIResponse into DeleteSubscriptionResponse\")\n\t}\n\treturn\n}", "func (client BaseClient) DeleteSubscriptionSender(req *http.Request) (*http.Response, error) {\n return client.Send(req, autorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n }", "func (client *subscriptionClient) deleteCreateRequest(ctx context.Context, topicName string, subscriptionName string, options *SubscriptionDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{topicName}/subscriptions/{subscriptionName}\"\n\tif topicName == \"\" {\n\t\treturn nil, errors.New(\"parameter topicName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{topicName}\", url.PathEscape(topicName))\n\tif subscriptionName == \"\" {\n\t\treturn nil, errors.New(\"parameter subscriptionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionName}\", url.PathEscape(subscriptionName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\tif client.apiVersion != nil {\n\t\treqQP.Set(\"api-version\", \"2017_04\")\n\t}\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/xml, application/atom+xml\")\n\treturn req, nil\n}", "func (s DeleteSubscriptionDefinitionOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (client *PolicyDefinitionsClient) deleteCreateRequest(ctx context.Context, policyDefinitionName string, options *PolicyDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.Authorization/policyDefinitions/{policyDefinitionName}\"\n\tif policyDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter policyDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{policyDefinitionName}\", url.PathEscape(policyDefinitionName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *WCFRelaysClient) deleteAuthorizationRuleCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, authorizationRuleName string, options *WCFRelaysClientDeleteAuthorizationRuleOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}/authorizationRules/{authorizationRuleName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif authorizationRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter authorizationRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{authorizationRuleName}\", url.PathEscape(authorizationRuleName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func deleteSubscription(r *http.Request, svc *mirror.Service) string {\n\tcollection := r.FormValue(\"subscriptionId\")\n\n\tif err := svc.Subscriptions.Delete(collection).Do(); err != nil {\n\t\treturn fmt.Sprintf(\"Unable to unsubscribe: %s\", err)\n\t}\n\treturn \"Application has been unsubscribed.\"\n}", "func (s subscriberserver) DeleteSubscription(ctx context.Context, req *metrov1.DeleteSubscriptionRequest) (*emptypb.Empty, error) {\n\tlogger.Ctx(ctx).Infow(\"subscriberserver: received request to delete subscription\", \"name\", req.Subscription)\n\n\tspan, ctx := opentracing.StartSpanFromContext(ctx, \"SubscriberServer.DeleteSubscription\")\n\tdefer span.Finish()\n\n\tm, err := subscription.GetValidatedModelForDelete(ctx, &metrov1.Subscription{Name: req.Subscription})\n\tif err != nil {\n\t\treturn nil, merror.ToGRPCError(err)\n\t}\n\n\terr = s.subscriptionCore.DeleteSubscription(ctx, m)\n\tif err != nil {\n\t\treturn nil, merror.ToGRPCError(err)\n\t}\n\treturn &emptypb.Empty{}, nil\n}", "func (r DeleteLoggerDefinitionRequest) Send(ctx context.Context) (*DeleteLoggerDefinitionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DeleteLoggerDefinitionResponse{\n\t\tDeleteLoggerDefinitionOutput: r.Request.Data.(*DeleteLoggerDefinitionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func SubDelete(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\tprojectUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\n\t// Get Result Object\n\tresults, err := subscriptions.Find(projectUUID, \"\", urlVars[\"subscription\"], \"\", 0, refStr)\n\tif err != nil {\n\t\terr := APIErrGenericBackend()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// If not found\n\tif results.Empty() {\n\t\terr := APIErrorNotFound(\"Subscription\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\terr = subscriptions.RemoveSub(projectUUID, urlVars[\"subscription\"], refStr)\n\tif err != nil {\n\t\tif err.Error() == \"not found\" {\n\t\t\terr := APIErrorNotFound(\"Subscription\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// if it is a push sub and it is also has a verified push endpoint, deactivate it\n\tif results.Subscriptions[0].PushCfg != (subscriptions.PushConfig{}) {\n\t\tif results.Subscriptions[0].PushCfg.Verified {\n\t\t\tpr := make(map[string]string)\n\t\t\tapsc := gorillaContext.Get(r, \"apsc\").(push.Client)\n\t\t\tpr[\"message\"] = apsc.DeactivateSubscription(context.TODO(), results.Subscriptions[0].FullName).Result()\n\t\t\tb, _ := json.Marshal(pr)\n\t\t\toutput = b\n\t\t}\n\t}\n\trespondOK(w, output)\n}", "func (g *smartContractGW) deleteStreamOrSub(res http.ResponseWriter, req *http.Request, params httprouter.Params) {\n\tlog.Infof(\"--> %s %s\", req.Method, req.URL)\n\n\tif g.sm == nil {\n\t\tg.gatewayErrReply(res, req, errors.New(errEventSupportMissing), 405)\n\t\treturn\n\t}\n\n\tvar err error\n\tif strings.HasPrefix(req.URL.Path, events.SubPathPrefix) {\n\t\terr = g.sm.DeleteSubscription(req.Context(), params.ByName(\"id\"))\n\t} else {\n\t\terr = g.sm.DeleteStream(req.Context(), params.ByName(\"id\"))\n\t}\n\tif err != nil {\n\t\tg.gatewayErrReply(res, req, err, 500)\n\t\treturn\n\t}\n\n\tstatus := 204\n\tlog.Infof(\"<-- %s %s [%d]\", req.Method, req.URL, status)\n\tres.Header().Set(\"Content-Type\", \"application/json\")\n\tres.WriteHeader(status)\n}", "func (subscription *Subscription) Delete() error {\n\tclient := NewHTTPClient(subscription.client)\n\t_, err := client.Delete(subscription.endpoint, subscription.config)\n\treturn err\n}", "func (client *SparkJobDefinitionClient) deleteSparkJobDefinitionCreateRequest(ctx context.Context, sparkJobDefinitionName string, options *SparkJobDefinitionBeginDeleteSparkJobDefinitionOptions) (*azcore.Request, error) {\n\turlPath := \"/sparkJobDefinitions/{sparkJobDefinitionName}\"\n\tif sparkJobDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sparkJobDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sparkJobDefinitionName}\", url.PathEscape(sparkJobDefinitionName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2019-06-01-preview\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func DeleteStatisticDefinition(settings *playfab.Settings, postData *DeleteStatisticDefinitionRequestModel, entityToken string) (*EmptyResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/Statistic/DeleteStatisticDefinition\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &EmptyResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func (m *SubscriptionsCompanySubscriptionItemRequestBuilder) Delete(ctx context.Context, requestConfiguration *SubscriptionsCompanySubscriptionItemRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (*DeleteSubscriptionRequest) Descriptor() ([]byte, []int) {\n\treturn file_api_subscription_proto_rawDescGZIP(), []int{2}\n}", "func (client *KeyVaultClient) deleteSasDefinitionHandleResponse(resp *http.Response) (KeyVaultClientDeleteSasDefinitionResponse, error) {\n\tresult := KeyVaultClientDeleteSasDefinitionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.DeletedSasDefinitionBundle); err != nil {\n\t\treturn KeyVaultClientDeleteSasDefinitionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s *SubscriptionLinesEndpoint) Delete(ctx context.Context, division int, id *types.GUID) error {\n\tb, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/subscription/SubscriptionLines\", division) // #nosec\n\tu, err := api.AddOdataKeyToURL(b, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, r, requestError := s.client.NewRequestAndDo(ctx, \"DELETE\", u.String(), nil, nil)\n\tif requestError != nil {\n\t\treturn requestError\n\t}\n\n\tif r.StatusCode != http.StatusNoContent {\n\t\tbody, _ := ioutil.ReadAll(r.Body) // #nosec\n\t\treturn fmt.Errorf(\"Failed with status %v and body %v\", r.StatusCode, body)\n\t}\n\n\treturn nil\n}", "func (client *TriggersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, accountName string, shareSubscriptionName string, triggerName string, options *TriggersClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataShare/accounts/{accountName}/shareSubscriptions/{shareSubscriptionName}/triggers/{triggerName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif shareSubscriptionName == \"\" {\n\t\treturn nil, errors.New(\"parameter shareSubscriptionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{shareSubscriptionName}\", url.PathEscape(shareSubscriptionName))\n\tif triggerName == \"\" {\n\t\treturn nil, errors.New(\"parameter triggerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{triggerName}\", url.PathEscape(triggerName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-09-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *ServersClient) deleteCreateRequest(ctx context.Context, resourceGroup string, fluidRelayServerName string, options *ServersClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroup}/providers/Microsoft.FluidRelay/fluidRelayServers/{fluidRelayServerName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroup == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroup cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroup}\", url.PathEscape(resourceGroup))\n\tif fluidRelayServerName == \"\" {\n\t\treturn nil, errors.New(\"parameter fluidRelayServerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{fluidRelayServerName}\", url.PathEscape(fluidRelayServerName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SQLResourcesClient) deleteSQLRoleDefinitionCreateRequest(ctx context.Context, roleDefinitionID string, resourceGroupName string, accountName string, options *SQLResourcesClientBeginDeleteSQLRoleDefinitionOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlRoleDefinitions/{roleDefinitionId}\"\n\tif roleDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleDefinitionId}\", url.PathEscape(roleDefinitionID))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *RoleDefinitionsClient) deleteCreateRequest(ctx context.Context, scope string, roleDefinitionID string, options *RoleDefinitionsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/{scope}/providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionId}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{scope}\", scope)\n\tif roleDefinitionID == \"\" {\n\t\treturn nil, errors.New(\"parameter roleDefinitionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{roleDefinitionId}\", url.PathEscape(roleDefinitionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (a *FrinxOpenconfigRoutingPolicyApiService) DeleteFrinxOpenconfigRoutingPolicyRoutingPolicyPolicyDefinitionsPolicyDefinition(ctx context.Context, name string, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-routing-policy:routing-policy/frinx-openconfig-routing-policy:policy-definitions/frinx-openconfig-routing-policy:policy-definition/{name}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (client *APIClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, apiID string, ifMatch string, options *APIClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ApiManagement/service/{serviceName}/apis/{apiId}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif apiID == \"\" {\n\t\treturn nil, errors.New(\"parameter apiID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{apiId}\", url.PathEscape(apiID))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\tif options != nil && options.DeleteRevisions != nil {\n\t\treqQP.Set(\"deleteRevisions\", strconv.FormatBool(*options.DeleteRevisions))\n\t}\n\treqQP.Set(\"api-version\", \"2022-08-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"If-Match\"] = []string{ifMatch}\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (r *DeviceManagementSettingDefinitionRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (s *Server) jsTemplateDeleteRequest(sub *subscription, c *client, _ *Account, subject, reply string, rmsg []byte) {\n\tif c == nil {\n\t\treturn\n\t}\n\tci, acc, _, msg, err := s.getRequestInfo(c, rmsg)\n\tif err != nil {\n\t\ts.Warnf(badAPIRequestT, msg)\n\t\treturn\n\t}\n\n\tvar resp = JSApiStreamTemplateDeleteResponse{ApiResponse: ApiResponse{Type: JSApiStreamTemplateDeleteResponseType}}\n\tif !acc.JetStreamEnabled() {\n\t\tresp.Error = NewJSNotEnabledForAccountError()\n\t\ts.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))\n\t\treturn\n\t}\n\tif !isEmptyRequest(msg) {\n\t\tresp.Error = NewJSNotEmptyRequestError()\n\t\ts.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))\n\t\treturn\n\t}\n\tname := templateNameFromSubject(subject)\n\terr = acc.deleteStreamTemplate(name)\n\tif err != nil {\n\t\tresp.Error = NewJSStreamTemplateDeleteError(err, Unless(err))\n\t\ts.sendAPIErrResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(&resp))\n\t\treturn\n\t}\n\tresp.Success = true\n\ts.sendAPIResponse(ci, acc, subject, reply, string(msg), s.jsonResponse(resp))\n}", "func (client BaseClient) DeleteSubscriptionPreparer(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (*http.Request, error) {\n pathParameters := map[string]interface{} {\n \"subscriptionId\": autorest.Encode(\"path\",subscriptionID),\n }\n\n queryParameters := map[string]interface{} {\n \"ApiVersion\": APIVersion,\n }\n\n preparer := autorest.CreatePreparer(\n autorest.AsDelete(),\n autorest.WithBaseURL(client.BaseURI),\n autorest.WithPathParameters(\"/{subscriptionId}\",pathParameters),\n autorest.WithQueryParameters(queryParameters),\n autorest.WithHeader(\"Content-Type\", \"application/json\"))\n if xMsRequestid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-requestid\",autorest.String(xMsRequestid)))\n }\n if xMsCorrelationid != nil {\n preparer = autorest.DecoratePreparer(preparer,\n autorest.WithHeader(\"x-ms-correlationid\",autorest.String(xMsCorrelationid)))\n }\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }", "func (c *DefaultApiService) DeleteSubscription(Sid string) error {\n\tpath := \"/v1/Subscriptions/{Sid}\"\n\tpath = strings.Replace(path, \"{\"+\"Sid\"+\"}\", Sid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Delete(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func (c *Control) handleXAPPSubscriptionDeleteRequest(params *xapp.MsgParams) {\n\txapp.Logger.Info(\"MSG from XAPP: %s\", params.String())\n\n\tsubDelReqMsg, err := c.e2ap.UnpackSubscriptionDeleteRequest(params.Payload)\n\tif err != nil {\n\t\txapp.Logger.Error(\"XAPP-SubDelReq %s\", idstring(err, params))\n\t\treturn\n\t}\n\tEndpoint := msgx.NewKafkaMsgSender(params.Src)\n\ttrans := c.tracker.NewXappTransaction(Endpoint, params.Xid, subDelReqMsg.RequestId.InstanceId, params.Meid)\n\tif trans == nil {\n\t\txapp.Logger.Error(\"XAPP-SubDelReq: %s\", idstring(fmt.Errorf(\"transaction not created\"), params))\n\t\treturn\n\t}\n\tdefer trans.Release()\n\n\terr = c.tracker.Track(trans)\n\tif err != nil {\n\t\txapp.Logger.Error(\"XAPP-SubReq: %s\", idstring(err, trans))\n\t\treturn\n\t}\n\n\tsubs, err := c.registry.GetSubscriptionFirstMatch([]uint32{trans.GetSubId()})\n\tif err != nil {\n\t\txapp.Logger.Error(\"XAPP-SubDelReq: %s\", idstring(err, trans))\n\t\treturn\n\t}\n\n\t//\n\t// Wake subs delete\n\t//\n\tgo c.handleSubscriptionDelete(subs, trans)\n\ttrans.WaitEvent(0) //blocked wait as timeout is handled in subs side\n\n\txapp.Logger.Debug(\"XAPP-SubDelReq: Handling event %s \", idstring(nil, trans, subs))\n\n\t// Whatever is received send ok delete response\n\tsubDelRespMsg := &e2ap.E2APSubscriptionDeleteResponse{}\n\tsubDelRespMsg.RequestId = subs.GetReqId().RequestId\n\tsubDelRespMsg.FunctionId = subs.SubReqMsg.FunctionId\n\ttrans.Mtype, trans.Payload, err = c.e2ap.PackSubscriptionDeleteResponse(subDelRespMsg)\n\tif err == nil {\n\t\tc.msgSendToXapp(\"\", subs, trans)\n\t}\n\n}", "func (client *WebAppsClient) deleteDeploymentCreateRequest(ctx context.Context, resourceGroupName string, name string, id string, options *WebAppsDeleteDeploymentOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/deployments/{id}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif id == \"\" {\n\t\treturn nil, errors.New(\"parameter id cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{id}\", url.PathEscape(id))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *ClientImpl) DeleteSubscription(ctx context.Context, args DeleteSubscriptionArgs) error {\n\trouteValues := make(map[string]string)\n\tif args.SubscriptionId == nil {\n\t\treturn &azuredevops.ArgumentNilError{ArgumentName: \"args.SubscriptionId\"}\n\t}\n\trouteValues[\"subscriptionId\"] = (*args.SubscriptionId).String()\n\n\tlocationId, _ := uuid.Parse(\"fc50d02a-849f-41fb-8af1-0a5216103269\")\n\t_, err := client.Client.Send(ctx, http.MethodDelete, locationId, \"7.1-preview.1\", routeValues, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *WCFRelaysClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, relayName string, options *WCFRelaysClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Relay/namespaces/{namespaceName}/wcfRelays/{relayName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-11-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *SyncGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, databaseName string, syncGroupName string, options *SyncGroupsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/syncGroups/{syncGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\tif databaseName == \"\" {\n\t\treturn nil, errors.New(\"parameter databaseName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{databaseName}\", url.PathEscape(databaseName))\n\tif syncGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter syncGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{syncGroupName}\", url.PathEscape(syncGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2020-11-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (client ModelClient) DeleteSubListSender(req *http.Request) (*http.Response, error) {\n\treturn autorest.SendWithSender(client, req,\n\t\tautorest.DoRetryForStatusCodes(client.RetryAttempts, client.RetryDuration, autorest.StatusCodesForRetry...))\n}", "func (s DeleteSubscriptionDefinitionInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func DeleteCertificate(settings *playfab.Settings, postData *DeleteCertificateRequestModel, entityToken string) (*EmptyResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/MultiplayerServer/DeleteCertificate\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &EmptyResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func RegistrationDelete(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\ttoken := r.URL.Query().Get(\"auth\")\n\n\t// parameters OK ?\n\tif isEmpty(id) == true || isEmpty(token) == true {\n\t\tstatus := http.StatusBadRequest\n\t\tencodeRegistrationResponse(w, status, http.StatusText(status), nil)\n\t\treturn\n\t}\n\n\t// validate the token\n\tif authtoken.Validate(config.Configuration.SharedSecret, token) == false {\n\t\tstatus := http.StatusForbidden\n\t\tencodeRegistrationResponse(w, status, http.StatusText(status), nil)\n\t\treturn\n\t}\n\n\t// get the request details\n\tcount, err := dao.Store.DeleteDepositRequest(id)\n\tif err != nil {\n\t\tlogger.Log(fmt.Sprintf(\"ERROR: %s\", err.Error()))\n\t\tstatus := http.StatusInternalServerError\n\t\tencodeRegistrationResponse(w, status,\n\t\t\tfmt.Sprintf(\"%s (%s)\", http.StatusText(status), err),\n\t\t\tnil)\n\t\treturn\n\t}\n\n\tif count == 0 {\n\t\tstatus := http.StatusNotFound\n\t\tencodeRegistrationResponse(w, status, http.StatusText(status), nil)\n\t\treturn\n\t}\n\n\tstatus := http.StatusOK\n\tencodeRegistrationResponse(w, status, http.StatusText(status), nil)\n}", "func (client *ServersClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, options *ServersClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2022-08-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (client *FirewallRulesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serverName string, firewallRuleName string, options *FirewallRulesBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/firewallRules/{firewallRuleName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serverName == \"\" {\n\t\treturn nil, errors.New(\"parameter serverName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serverName}\", url.PathEscape(serverName))\n\tif firewallRuleName == \"\" {\n\t\treturn nil, errors.New(\"parameter firewallRuleName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{firewallRuleName}\", url.PathEscape(firewallRuleName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2017-12-01\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *DefenderSettingsClient) deleteCreateRequest(ctx context.Context, options *DefenderSettingsClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.IoTSecurity/defenderSettings/default\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func ExampleClient_DeleteReportDefinitionRequest_shared00() {\n\tcfg, err := external.LoadDefaultAWSConfig()\n\tif err != nil {\n\t\tpanic(\"failed to load config, \" + err.Error())\n\t}\n\n\tsvc := costandusagereportservice.New(cfg)\n\tinput := &costandusagereportservice.DeleteReportDefinitionInput{\n\t\tReportName: aws.String(\"ExampleReport\"),\n\t}\n\n\treq := svc.DeleteReportDefinitionRequest(input)\n\tresult, err := req.Send(context.Background())\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\n\t\t\tcase costandusagereportservice.ErrCodeInternalErrorException:\n\t\t\t\tfmt.Println(costandusagereportservice.ErrCodeInternalErrorException, aerr.Error())\n\t\t\tcase costandusagereportservice.ErrCodeValidationException:\n\t\t\t\tfmt.Println(costandusagereportservice.ErrCodeValidationException, aerr.Error())\n\t\t\tdefault:\n\t\t\t\tfmt.Println(aerr.Error())\n\t\t\t}\n\t\t} else {\n\t\t\t// Print the error, cast err to awserr.Error to get the Code and\n\t\t\t// Message from an error.\n\t\t\tfmt.Println(err.Error())\n\t\t}\n\t\treturn\n\t}\n\n\tfmt.Println(result)\n}", "func (client *ClientImpl) DeleteStateDefinition(ctx context.Context, args DeleteStateDefinitionArgs) error {\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\tif args.WitRefName == nil || *args.WitRefName == \"\" {\n\t\treturn &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.WitRefName\"}\n\t}\n\trouteValues[\"witRefName\"] = *args.WitRefName\n\tif args.StateId == nil {\n\t\treturn &azuredevops.ArgumentNilError{ArgumentName: \"args.StateId\"}\n\t}\n\trouteValues[\"stateId\"] = (*args.StateId).String()\n\n\tlocationId, _ := uuid.Parse(\"31015d57-2dff-4a46-adb3-2fb4ee3dcec9\")\n\t_, err := client.Client.Send(ctx, http.MethodDelete, locationId, \"6.0-preview.1\", routeValues, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (client *ReplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsBeginDeleteOptions) (*azcore.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif replicationName == \"\" {\n\t\treturn nil, errors.New(\"parameter replicationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{replicationName}\", url.PathEscape(replicationName))\n\treq, err := azcore.NewRequest(ctx, http.MethodDelete, azcore.JoinPaths(client.con.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Telemetry(telemetryInfo)\n\treqQP := req.URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01-preview\")\n\treq.URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (client VersionsClient) Delete(ctx context.Context, resourceGroupName string, templateSpecName string, templateSpecVersion string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/VersionsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: resourceGroupName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"resourceGroupName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"resourceGroupName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}},\n\t\t{TargetValue: templateSpecName,\n\t\t\tConstraints: []validation.Constraint{{Target: \"templateSpecName\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"templateSpecName\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"templateSpecName\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}},\n\t\t{TargetValue: templateSpecVersion,\n\t\t\tConstraints: []validation.Constraint{{Target: \"templateSpecVersion\", Name: validation.MaxLength, Rule: 90, Chain: nil},\n\t\t\t\t{Target: \"templateSpecVersion\", Name: validation.MinLength, Rule: 1, Chain: nil},\n\t\t\t\t{Target: \"templateSpecVersion\", Name: validation.Pattern, Rule: `^[-\\w\\._\\(\\)]+$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"templatespecs.VersionsClient\", \"Delete\", err.Error())\n\t}\n\n\treq, err := client.DeletePreparer(ctx, resourceGroupName, templateSpecName, templateSpecVersion)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"templatespecs.VersionsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"templatespecs.VersionsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"templatespecs.VersionsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (client *DevicesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, deviceName string, options *DevicesClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.HybridNetwork/devices/{deviceName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif deviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter deviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{deviceName}\", url.PathEscape(deviceName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (c *DeleteCommand) Exec(_ io.Reader, out io.Writer) error {\n\tinput := c.constructInput()\n\n\terr := c.Globals.APIClient.DeleteTLSSubscription(input)\n\tif err != nil {\n\t\tc.Globals.ErrLog.AddWithContext(err, map[string]any{\n\t\t\t\"TLS Subscription ID\": c.id,\n\t\t\t\"Force\": c.force.Value,\n\t\t})\n\t\treturn err\n\t}\n\n\ttext.Success(out, \"Deleted TLS Subscription '%s' (force: %t)\", c.id, c.force.Value)\n\treturn nil\n}", "func (a *HyperflexApiService) DeleteHyperflexHealthCheckDefinitionExecute(r ApiDeleteHyperflexHealthCheckDefinitionRequest) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.DeleteHyperflexHealthCheckDefinition\")\n\tif err != nil {\n\t\treturn nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/HealthCheckDefinitions/{Moid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"Moid\"+\"}\", url.PathEscape(parameterToString(r.moid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func DeleteTrafficInfluenceSubscription(w http.ResponseWriter,\n\tr *http.Request) {\n\n\tnefCtx := r.Context().Value(nefCtxKey(\"nefCtx\")).(*nefContext)\n\tnef := &nefCtx.nef\n\n\tvars := mux.Vars(r)\n\tlog.Infof(\" AFID : %s\", vars[\"afId\"])\n\tlog.Infof(\" SUBSCRIPTION ID : %s\", vars[\"subscriptionId\"])\n\n\taf, err := nef.nefGetAf(vars[\"afId\"])\n\n\tif err != nil {\n\t\tlog.Err(err)\n\t\tsendCustomeErrorRspToAF(w, 404, \"Failed to find AF entry\")\n\t\treturn\n\t}\n\trsp, err := af.afDeleteSubscription(nefCtx, vars[\"subscriptionId\"])\n\n\tif err != nil {\n\t\tlog.Err(err)\n\t\tsendErrorResponseToAF(w, rsp)\n\t\treturn\n\t}\n\n\t// Response should be 204 as per 3GPP 29.522\n\tw.WriteHeader(http.StatusNoContent)\n\n\tEmulator_file := os.Getenv(\"Emulator_path\") + \"/on\"\n\tcmd := exec.Command(\"rm\", Emulator_file)\n\tgo cmd.Run()\n\n\tlog.Infof(\"HTTP Response sent: %d\", http.StatusNoContent)\n\n\tif af.afGetSubCount() == 0 {\n\n\t\t_ = nef.nefDeleteAf(vars[\"afId\"])\n\t}\n\n\tlogNef(nef)\n}", "func (r *OfficeClientConfigurationRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (svc *SubscriptionService) DeleteSubscription(id string) error {\n\tif len(id) == 0 {\n\t\treturn fmt.Errorf(\"DeleteSubscription: invalid parameter specified, %s\", id)\n\t}\n\terr := svc.objectSet.DeleteObject(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *Service) HandleDelete(w http.ResponseWriter, r *http.Request) {\n\terr := s.subscriptionRepository.Delete(r.Context(), s.getResourceID(r), s.getSubscriptionID(r))\n\tif err != nil {\n\t\tstatus := http.StatusInternalServerError\n\t\tif errRepo, ok := err.(flare.SubscriptionRepositoryError); ok && errRepo.NotFound() {\n\t\t\tstatus = http.StatusNotFound\n\t\t}\n\n\t\ts.writer.Error(w, \"error during subscription delete\", err, status)\n\t\treturn\n\t}\n\n\ts.writer.Response(w, nil, http.StatusNoContent, nil)\n}", "func (client *subscriptionClient) deleteHandleResponse(resp *http.Response) (SubscriptionDeleteResponse, error) {\n\tresult := SubscriptionDeleteResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsXML(resp, &result.Object); err != nil {\n\t\treturn SubscriptionDeleteResponse{}, err\n\t}\n\treturn result, nil\n}", "func (client *VendorSKUPreviewClient) deleteCreateRequest(ctx context.Context, vendorName string, skuName string, previewSubscription string, options *VendorSKUPreviewClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/providers/Microsoft.HybridNetwork/vendors/{vendorName}/vendorSkus/{skuName}/previewSubscriptions/{previewSubscription}\"\n\tif vendorName == \"\" {\n\t\treturn nil, errors.New(\"parameter vendorName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{vendorName}\", url.PathEscape(vendorName))\n\tif skuName == \"\" {\n\t\treturn nil, errors.New(\"parameter skuName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{skuName}\", url.PathEscape(skuName))\n\tif previewSubscription == \"\" {\n\t\treturn nil, errors.New(\"parameter previewSubscription cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{previewSubscription}\", url.PathEscape(previewSubscription))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *WebAppsClient) deleteHybridConnectionSlotCreateRequest(ctx context.Context, resourceGroupName string, name string, namespaceName string, relayName string, slot string, options *WebAppsDeleteHybridConnectionSlotOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/hybridConnectionNamespaces/{namespaceName}/relays/{relayName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif slot == \"\" {\n\t\treturn nil, errors.New(\"parameter slot cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{slot}\", url.PathEscape(slot))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (r *DeviceCompliancePolicyAssignmentRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (ss *SubscriptionsService) Delete(ctx context.Context, cID, sID string) (\n\tres *Response,\n\ts *Subscription,\n\terr error,\n) {\n\tu := fmt.Sprintf(\"v2/customers/%s/subscriptions/%s\", cID, sID)\n\n\tres, err = ss.client.delete(ctx, u, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(res.content, &s); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (client *WebAppsClient) deleteHostNameBindingCreateRequest(ctx context.Context, resourceGroupName string, name string, hostName string, options *WebAppsDeleteHostNameBindingOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hostNameBindings/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (r *Base) deleteSubscription(ctx context.Context, ps *v1alpha1.PullSubscription) error {\n\tif ps.Status.SubscriptionID == \"\" {\n\t\treturn nil\n\t}\n\n\t// At this point the project ID should have been populated in the status.\n\t// Querying Pub/Sub as the subscription could have been deleted outside the cluster (e.g, through gcloud).\n\tclient, err := r.CreateClientFn(ctx, ps.Status.ProjectID)\n\tif err != nil {\n\t\tlogging.FromContext(ctx).Desugar().Error(\"Failed to create Pub/Sub client\", zap.Error(err))\n\t\treturn err\n\t}\n\tdefer client.Close()\n\n\t// Load the subscription.\n\tsub := client.Subscription(ps.Status.SubscriptionID)\n\texists, err := sub.Exists(ctx)\n\tif err != nil {\n\t\tlogging.FromContext(ctx).Desugar().Error(\"Failed to verify Pub/Sub subscription exists\", zap.Error(err))\n\t\treturn err\n\t}\n\tif exists {\n\t\tif err := sub.Delete(ctx); err != nil {\n\t\t\tlogging.FromContext(ctx).Desugar().Error(\"Failed to delete Pub/Sub subscription\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (r *DeviceCompliancePolicyRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (*DeleteSubscriptionRequest) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_data_proto_rawDescGZIP(), []int{4}\n}", "func (r *DeviceManagementTemplateRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (client *WebAppsClient) deleteHybridConnectionCreateRequest(ctx context.Context, resourceGroupName string, name string, namespaceName string, relayName string, options *WebAppsDeleteHybridConnectionOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/hybridConnectionNamespaces/{namespaceName}/relays/{relayName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif relayName == \"\" {\n\t\treturn nil, errors.New(\"parameter relayName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{relayName}\", url.PathEscape(relayName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *CustomDomainsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, serviceName string, appName string, domainName string, options *CustomDomainsBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AppPlatform/Spring/{serviceName}/apps/{appName}/domains/{domainName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif serviceName == \"\" {\n\t\treturn nil, errors.New(\"parameter serviceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{serviceName}\", url.PathEscape(serviceName))\n\tif appName == \"\" {\n\t\treturn nil, errors.New(\"parameter appName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{appName}\", url.PathEscape(appName))\n\tif domainName == \"\" {\n\t\treturn nil, errors.New(\"parameter domainName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{domainName}\", url.PathEscape(domainName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-09-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *PermissionBindingsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, namespaceName string, permissionBindingName string, options *PermissionBindingsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.EventGrid/namespaces/{namespaceName}/permissionBindings/{permissionBindingName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif namespaceName == \"\" {\n\t\treturn nil, errors.New(\"parameter namespaceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{namespaceName}\", url.PathEscape(namespaceName))\n\tif permissionBindingName == \"\" {\n\t\treturn nil, errors.New(\"parameter permissionBindingName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{permissionBindingName}\", url.PathEscape(permissionBindingName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-06-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (c *restClient) DeleteDocument(ctx context.Context, req *firestorepb.DeleteDocumentRequest, opts ...gax.CallOption) error {\n\tbaseUrl, err := url.Parse(c.endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbaseUrl.Path += fmt.Sprintf(\"/v1/%v\", req.GetName())\n\n\tparams := url.Values{}\n\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\tif req.GetCurrentDocument().GetExists() {\n\t\tparams.Add(\"currentDocument.exists\", fmt.Sprintf(\"%v\", req.GetCurrentDocument().GetExists()))\n\t}\n\tif req.GetCurrentDocument().GetUpdateTime() != nil {\n\t\tupdateTime, err := protojson.Marshal(req.GetCurrentDocument().GetUpdateTime())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tparams.Add(\"currentDocument.updateTime\", string(updateTime[1:len(updateTime)-1]))\n\t}\n\n\tbaseUrl.RawQuery = params.Encode()\n\n\t// Build HTTP headers from client and context metadata.\n\thds := []string{\"x-goog-request-params\", fmt.Sprintf(\"%s=%v\", \"name\", url.QueryEscape(req.GetName()))}\n\n\thds = append(c.xGoogHeaders, hds...)\n\thds = append(hds, \"Content-Type\", \"application/json\")\n\theaders := gax.BuildHeaders(ctx, hds...)\n\treturn gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\tif settings.Path != \"\" {\n\t\t\tbaseUrl.Path = settings.Path\n\t\t}\n\t\thttpReq, err := http.NewRequest(\"DELETE\", baseUrl.String(), nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\thttpReq = httpReq.WithContext(ctx)\n\t\thttpReq.Header = headers\n\n\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer httpRsp.Body.Close()\n\n\t\t// Returns nil if there is no error, otherwise wraps\n\t\t// the response code and body into a non-nil error\n\t\treturn googleapi.CheckResponse(httpRsp)\n\t}, opts...)\n}", "func (client *ReplicationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, replicationName string, options *ReplicationsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/replications/{replicationName}\"\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif replicationName == \"\" {\n\t\treturn nil, errors.New(\"parameter replicationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{replicationName}\", url.PathEscape(replicationName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-01-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (a *DefaultApiService) DeleteTopicExecute(r ApiDeleteTopicRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"DefaultApiService.DeleteTopic\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/topics/{topicName}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"topicName\"+\"}\", _neturl.PathEscape(parameterToString(r.topicName, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (client *WebAppsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, name string, options *WebAppsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\tif options != nil && options.DeleteMetrics != nil {\n\t\treqQP.Set(\"deleteMetrics\", strconv.FormatBool(*options.DeleteMetrics))\n\t}\n\tif options != nil && options.DeleteEmptyServerFarm != nil {\n\t\treqQP.Set(\"deleteEmptyServerFarm\", strconv.FormatBool(*options.DeleteEmptyServerFarm))\n\t}\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (r *DeviceConfigurationAssignmentRequest) Delete(ctx context.Context) error {\n\treturn r.JSONRequest(ctx, \"DELETE\", \"\", nil, nil)\n}", "func (client IngestionSettingsClient) Delete(ctx context.Context, ingestionSettingName string) (result autorest.Response, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/IngestionSettingsClient.Delete\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.Response != nil {\n\t\t\t\tsc = result.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tif err := validation.Validate([]validation.Validation{\n\t\t{TargetValue: client.SubscriptionID,\n\t\t\tConstraints: []validation.Constraint{{Target: \"client.SubscriptionID\", Name: validation.Pattern, Rule: `^[0-9A-Fa-f]{8}-([0-9A-Fa-f]{4}-){3}[0-9A-Fa-f]{12}$`, Chain: nil}}}}); err != nil {\n\t\treturn result, validation.NewError(\"security.IngestionSettingsClient\", \"Delete\", err.Error())\n\t}\n\n\treq, err := client.DeletePreparer(ctx, ingestionSettingName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"security.IngestionSettingsClient\", \"Delete\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.DeleteSender(req)\n\tif err != nil {\n\t\tresult.Response = resp\n\t\terr = autorest.NewErrorWithError(err, \"security.IngestionSettingsClient\", \"Delete\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.DeleteResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"security.IngestionSettingsClient\", \"Delete\", resp, \"Failure responding to request\")\n\t\treturn\n\t}\n\n\treturn\n}", "func (client *PrivateDNSZoneGroupsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, privateEndpointName string, privateDNSZoneGroupName string, options *PrivateDNSZoneGroupsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/privateEndpoints/{privateEndpointName}/privateDnsZoneGroups/{privateDnsZoneGroupName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif privateEndpointName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateEndpointName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateEndpointName}\", url.PathEscape(privateEndpointName))\n\tif privateDNSZoneGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter privateDNSZoneGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{privateDnsZoneGroupName}\", url.PathEscape(privateDNSZoneGroupName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-04-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *ApplicationTypeVersionsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, clusterName string, applicationTypeName string, version string, options *ApplicationTypeVersionsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceFabric/clusters/{clusterName}/applicationTypes/{applicationTypeName}/versions/{version}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif clusterName == \"\" {\n\t\treturn nil, errors.New(\"parameter clusterName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{clusterName}\", url.PathEscape(clusterName))\n\tif applicationTypeName == \"\" {\n\t\treturn nil, errors.New(\"parameter applicationTypeName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{applicationTypeName}\", url.PathEscape(applicationTypeName))\n\tif version == \"\" {\n\t\treturn nil, errors.New(\"parameter version cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{version}\", url.PathEscape(version))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *WebhooksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif webhookName == \"\" {\n\t\treturn nil, errors.New(\"parameter webhookName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{webhookName}\", url.PathEscape(webhookName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (o *DeleteGatewayBundleUsingDELETEOKBody) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := o.validateMessage(formats); err != nil {\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (a *HyperflexApiService) DeleteHyperflexHealthCheckDefinition(ctx context.Context, moid string) ApiDeleteHyperflexHealthCheckDefinitionRequest {\n\treturn ApiDeleteHyperflexHealthCheckDefinitionRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmoid: moid,\n\t}\n}", "func (a *NamespacesApiService) UnsubscribeNamespace(ctx _context.Context, tenant string, cluster string, namespace string, subscription string, localVarOptionals *UnsubscribeNamespaceOpts) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/namespaces/{tenant}/{namespace}/unsubscribe/{subscription}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"tenant\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", tenant)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"cluster\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", cluster)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"namespace\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", namespace)), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"subscription\"+\"}\", _neturl.QueryEscape(fmt.Sprintf(\"%v\", subscription)), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Authoritative.IsSet() {\n\t\tlocalVarQueryParams.Add(\"authoritative\", parameterToString(localVarOptionals.Authoritative.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (a *FrinxOpenconfigRoutingPolicyApiService) DeleteFrinxOpenconfigRoutingPolicyRoutingPolicyPolicyDefinitionsPolicyDefinitionConfig(ctx context.Context, name string, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/config/network-topology:network-topology/network-topology:topology/unified/network-topology:node/{node-id}/yang-ext:mount/frinx-openconfig-routing-policy:routing-policy/frinx-openconfig-routing-policy:policy-definitions/frinx-openconfig-routing-policy:policy-definition/{name}/frinx-openconfig-routing-policy:config/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"name\"+\"}\", fmt.Sprintf(\"%v\", name), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"node-id\"+\"}\", fmt.Sprintf(\"%v\", nodeId), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\", \"application/xml\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\", \"application/xml\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func (client *KeyVaultClient) getDeletedSasDefinitionCreateRequest(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, options *KeyVaultClientGetDeletedSasDefinitionOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/deletedstorage/{storage-account-name}/sas/{sas-definition-name}\"\n\tif storageAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter storageAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{storage-account-name}\", url.PathEscape(storageAccountName))\n\tif sasDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sasDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sas-definition-name}\", url.PathEscape(sasDefinitionName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (client *SQLResourcesClient) deleteSQLTriggerCreateRequest(ctx context.Context, resourceGroupName string, accountName string, databaseName string, containerName string, triggerName string, options *SQLResourcesClientBeginDeleteSQLTriggerOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/sqlDatabases/{databaseName}/containers/{containerName}/triggers/{triggerName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif accountName == \"\" {\n\t\treturn nil, errors.New(\"parameter accountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{accountName}\", url.PathEscape(accountName))\n\tif databaseName == \"\" {\n\t\treturn nil, errors.New(\"parameter databaseName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{databaseName}\", url.PathEscape(databaseName))\n\tif containerName == \"\" {\n\t\treturn nil, errors.New(\"parameter containerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{containerName}\", url.PathEscape(containerName))\n\tif triggerName == \"\" {\n\t\treturn nil, errors.New(\"parameter triggerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{triggerName}\", url.PathEscape(triggerName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2023-03-15-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func NewDeleteaspecificSubscriberRegistrationRequest(server string, id string) (*http.Request, error) {\n\tvar err error\n\n\tvar pathParam0 string\n\n\tpathParam0, err = runtime.StyleParam(\"simple\", false, \"id\", id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/subscriberregistrations/%s\", pathParam0)\n\tif basePath[0] == '/' {\n\t\tbasePath = basePath[1:]\n\t}\n\n\tqueryUrl, err = queryUrl.Parse(basePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"DELETE\", queryUrl.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn req, nil\n}", "func (m *ScheduleRequestBuilder) Delete(ctx context.Context, requestConfiguration *ScheduleRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.CreateDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": ia572726a95efa92ddd544552cd950653dc691023836923576b2f4bf716cf204a.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.requestAdapter.SendNoContentAsync(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (client *AFDOriginsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, profileName string, originGroupName string, originName string, options *AFDOriginsClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Cdn/profiles/{profileName}/originGroups/{originGroupName}/origins/{originName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif profileName == \"\" {\n\t\treturn nil, errors.New(\"parameter profileName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{profileName}\", url.PathEscape(profileName))\n\tif originGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter originGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{originGroupName}\", url.PathEscape(originGroupName))\n\tif originName == \"\" {\n\t\treturn nil, errors.New(\"parameter originName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{originName}\", url.PathEscape(originName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func TestEventServiceDeleteEventSubscription(t *testing.T) {\n\tvar result EventService\n\terr := json.NewDecoder(strings.NewReader(eventServiceBody)).Decode(&result)\n\tif err != nil {\n\t\tt.Errorf(\"Error decoding JSON: %s\", err)\n\t}\n\n\t// create the custom test client\n\ttestClient := &common.TestClient{\n\t\tCustomReturnForActions: map[string][]interface{}{\n\t\t\thttp.MethodDelete: {\n\t\t\t\t// defining the custom return for the\n\t\t\t\t// first DELETE operation\n\t\t\t\terr,\n\t\t\t},\n\t\t},\n\t}\n\tresult.SetClient(testClient)\n\n\t// create event subscription\n\terr = result.DeleteEventSubscription(\n\t\tcontext.Background(),\n\t\t\"/redfish/v1/EventService/Subscriptions/SubscriptionId/\")\n\n\t// validate the return values\n\tif err != nil {\n\t\tt.Errorf(\"Error making DeleteEventSubscription call: %s\", err)\n\t}\n}", "func (client *IntegrationRuntimeNodesClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, factoryName string, integrationRuntimeName string, nodeName string, options *IntegrationRuntimeNodesClientDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/nodes/{nodeName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif factoryName == \"\" {\n\t\treturn nil, errors.New(\"parameter factoryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{factoryName}\", url.PathEscape(factoryName))\n\tif integrationRuntimeName == \"\" {\n\t\treturn nil, errors.New(\"parameter integrationRuntimeName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{integrationRuntimeName}\", url.PathEscape(integrationRuntimeName))\n\tif nodeName == \"\" {\n\t\treturn nil, errors.New(\"parameter nodeName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{nodeName}\", url.PathEscape(nodeName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2018-06-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (client *ManagementAssociationsClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, managementAssociationName string, options *ManagementAssociationsDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{providerName}/{resourceType}/{resourceName}/providers/Microsoft.OperationsManagement/ManagementAssociations/{managementAssociationName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif client.providerName == \"\" {\n\t\treturn nil, errors.New(\"parameter client.providerName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{providerName}\", url.PathEscape(client.providerName))\n\tif client.resourceType == \"\" {\n\t\treturn nil, errors.New(\"parameter client.resourceType cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceType}\", url.PathEscape(client.resourceType))\n\tif client.resourceName == \"\" {\n\t\treturn nil, errors.New(\"parameter client.resourceName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceName}\", url.PathEscape(client.resourceName))\n\tif managementAssociationName == \"\" {\n\t\treturn nil, errors.New(\"parameter managementAssociationName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{managementAssociationName}\", url.PathEscape(managementAssociationName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2015-11-01-preview\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (r *SubscriptionsService) Delete(subscription string) *SubscriptionsDeleteCall {\n\tc := &SubscriptionsDeleteCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.subscription = subscription\n\treturn c\n}", "func (a *SubscriptionsApiService) CreateSubscriptionExecute(r ApiCreateSubscriptionRequest) (*SubscriptionResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *SubscriptionResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"SubscriptionsApiService.CreateSubscription\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/customers/{id}/subscription\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", url.PathEscape(parameterValueToString(r.id, \"id\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.subscriptionRequest == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"subscriptionRequest is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/vnd.conekta-v2.1.0+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.acceptLanguage != nil {\n\t\tparameterAddToHeaderOrQuery(localVarHeaderParams, \"Accept-Language\", r.acceptLanguage, \"\")\n\t}\n\tif r.xChildCompanyId != nil {\n\t\tparameterAddToHeaderOrQuery(localVarHeaderParams, \"X-Child-Company-Id\", r.xChildCompanyId, \"\")\n\t}\n\t// body params\n\tlocalVarPostBody = r.subscriptionRequest\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := io.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 422 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client *WebAppsClient) deleteHostNameBindingSlotCreateRequest(ctx context.Context, resourceGroupName string, name string, slot string, hostName string, options *WebAppsDeleteHostNameBindingSlotOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/slots/{slot}/hostNameBindings/{hostName}\"\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif name == \"\" {\n\t\treturn nil, errors.New(\"parameter name cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{name}\", url.PathEscape(name))\n\tif slot == \"\" {\n\t\treturn nil, errors.New(\"parameter slot cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{slot}\", url.PathEscape(slot))\n\tif hostName == \"\" {\n\t\treturn nil, errors.New(\"parameter hostName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{hostName}\", url.PathEscape(hostName))\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.ep, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2021-02-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (s *server) Delete(ctx context.Context, body *pb.NameHolder) (*pb.DeletionResponse, error) {\n\tappName := body.GetName()\n\tfilter := types.M{\n\t\tmongo.NameKey: appName,\n\t\tmongo.InstanceTypeKey: mongo.AppInstance,\n\t}\n\n\tnode, _ := redis.FetchAppNode(appName)\n\tgo redis.DecrementServiceLoad(ServiceName, node)\n\tgo redis.RemoveApp(appName)\n\tgo diskCleanup(appName)\n\n\tif configs.CloudflareConfig.PlugIn {\n\t\tgo cloudflare.DeleteRecord(appName, mongo.AppInstance)\n\t}\n\n\t_, err := mongo.DeleteInstance(filter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &pb.DeletionResponse{Success: true}, nil\n}" ]
[ "0.592985", "0.5866576", "0.58419967", "0.57738614", "0.56166816", "0.5599317", "0.548799", "0.54524446", "0.53816104", "0.5365328", "0.5344507", "0.53164077", "0.5290776", "0.52716213", "0.52396584", "0.522985", "0.52265644", "0.5176691", "0.516902", "0.5165735", "0.5159293", "0.51157105", "0.50979966", "0.50296104", "0.501114", "0.50061053", "0.4982357", "0.49743396", "0.49721643", "0.4959361", "0.49484882", "0.49280027", "0.49138007", "0.4884166", "0.4859557", "0.48581192", "0.48498666", "0.48474073", "0.48364997", "0.4829512", "0.48286155", "0.48215675", "0.48207694", "0.48126152", "0.47945544", "0.4790461", "0.47840017", "0.47617042", "0.47582376", "0.47545034", "0.47295707", "0.47264913", "0.4725014", "0.47225022", "0.47046015", "0.47002465", "0.46957308", "0.46954986", "0.46950528", "0.46897358", "0.46847287", "0.46757996", "0.4668818", "0.46685433", "0.46661052", "0.46655315", "0.46647742", "0.4663693", "0.4654804", "0.46546596", "0.46519437", "0.46490285", "0.46486092", "0.46475714", "0.46447846", "0.46413535", "0.4636931", "0.46328935", "0.46315423", "0.46235687", "0.46204963", "0.46130824", "0.46056807", "0.45998615", "0.45899767", "0.45857173", "0.45772165", "0.45746005", "0.45745808", "0.45687503", "0.45678532", "0.45654058", "0.45583072", "0.4552589", "0.45523155", "0.4545646", "0.4541835", "0.45395464", "0.45337301", "0.45284376" ]
0.76387185
0
SDKResponseMetdata returns the response metadata for the DeleteSubscriptionDefinition request.
func (r *DeleteSubscriptionDefinitionResponse) SDKResponseMetdata() *aws.Response { return r.response }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (client *KeyVaultClient) deleteSasDefinitionHandleResponse(resp *http.Response) (KeyVaultClientDeleteSasDefinitionResponse, error) {\n\tresult := KeyVaultClientDeleteSasDefinitionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.DeletedSasDefinitionBundle); err != nil {\n\t\treturn KeyVaultClientDeleteSasDefinitionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s DeleteAppReplicationConfigurationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteResolverRuleOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteResourceDefinitionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteDeploymentOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDomainAssociationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDomainNameOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteSkillGroupOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (client BaseClient) DeleteSubscriptionResponder(resp *http.Response) (result Error, err error) {\n err = autorest.Respond(\n resp,\n client.ByInspecting(),\n azure.WithErrorUnlessStatusCode(http.StatusOK,http.StatusAccepted,http.StatusBadRequest,http.StatusForbidden,http.StatusNotFound,http.StatusInternalServerError),\n autorest.ByUnmarshallingJSON(&result),\n autorest.ByClosing())\n result.Response = autorest.Response{Response: resp}\n return\n }", "func (s DeleteChannelOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r DeleteSubscriptionDefinitionRequest) Send(ctx context.Context) (*DeleteSubscriptionDefinitionResponse, error) {\n\tr.Request.SetContext(ctx)\n\terr := r.Request.Send()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := &DeleteSubscriptionDefinitionResponse{\n\t\tDeleteSubscriptionDefinitionOutput: r.Request.Data.(*DeleteSubscriptionDefinitionOutput),\n\t\tresponse: &aws.Response{Request: r.Request},\n\t}\n\n\treturn resp, nil\n}", "func (s DeleteReplicationJobOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteAppLaunchConfigurationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (client *KeyVaultClient) getDeletedSasDefinitionHandleResponse(resp *http.Response) (KeyVaultClientGetDeletedSasDefinitionResponse, error) {\n\tresult := KeyVaultClientGetDeletedSasDefinitionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.DeletedSasDefinitionBundle); err != nil {\n\t\treturn KeyVaultClientGetDeletedSasDefinitionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s DeleteResolverEndpointOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteModelOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteAssociationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteContactOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDocumentOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteIntegrationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteResourceDataSyncOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteApiOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (*DeleteSubscriptionResponse) Descriptor() ([]byte, []int) {\n\treturn file_toit_api_data_proto_rawDescGZIP(), []int{5}\n}", "func (s DeleteContainerPolicyOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteRuleGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteSubscriptionDefinitionOutput) MarshalFields(e protocol.FieldEncoder) error {\n\treturn nil\n}", "func (s DeleteMaintenanceWindowOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteIntegrationResponseOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDatasetContentOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteAuthorizerOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDatasetOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (client *KeyVaultClient) recoverDeletedSasDefinitionHandleResponse(resp *http.Response) (KeyVaultClientRecoverDeletedSasDefinitionResponse, error) {\n\tresult := KeyVaultClientRecoverDeletedSasDefinitionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SasDefinitionBundle); err != nil {\n\t\treturn KeyVaultClientRecoverDeletedSasDefinitionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s DeleteRoomSkillParameterOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func DeleteStatisticDefinition(settings *playfab.Settings, postData *DeleteStatisticDefinitionRequestModel, entityToken string) (*EmptyResponseModel, error) {\n if entityToken == \"\" {\n return nil, playfab.NewCustomError(\"entityToken should not be an empty string\", playfab.ErrorGeneric)\n }\n b, errMarshal := json.Marshal(postData)\n if errMarshal != nil {\n return nil, playfab.NewCustomError(errMarshal.Error(), playfab.ErrorMarshal)\n }\n\n sourceMap, err := playfab.Request(settings, b, \"/Statistic/DeleteStatisticDefinition\", \"X-EntityToken\", entityToken)\n if err != nil {\n return nil, err\n }\n \n result := &EmptyResponseModel{}\n\n config := mapstructure.DecoderConfig{\n DecodeHook: playfab.StringToDateTimeHook,\n Result: result,\n }\n \n decoder, errDecoding := mapstructure.NewDecoder(&config)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n \n errDecoding = decoder.Decode(sourceMap)\n if errDecoding != nil {\n return nil, playfab.NewCustomError(errDecoding.Error(), playfab.ErrorDecoding)\n }\n\n return result, nil\n}", "func (s DeleteApiMappingOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteParametersOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteServerCatalogOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteLoggerDefinitionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteDocumentationVersionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteProfileOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteDatastoreOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteParameterOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteRoomOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeletePipelineOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteUserDefinedFunctionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteInventoryOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteSubscriptionDefinitionInput) MarshalFields(e protocol.FieldEncoder) error {\n\te.SetValue(protocol.HeaderTarget, \"Content-Type\", protocol.StringValue(\"application/json\"), protocol.Metadata{})\n\n\tif s.SubscriptionDefinitionId != nil {\n\t\tv := *s.SubscriptionDefinitionId\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.PathTarget, \"SubscriptionDefinitionId\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (s DeleteJobOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteObjectOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteBranchOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteContainerOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteRouteOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteActivationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteConfigurationSetEventDestinationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteAppOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteAppOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeleteRouteResponseOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func ExampleAssessmentsMetadataClient_DeleteInSubscription() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armsecurity.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\t_, err = clientFactory.NewAssessmentsMetadataClient().DeleteInSubscription(ctx, \"ca039e75-a276-4175-aebc-bcd41e4b14b7\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n}", "func (client *KeyVaultClient) deleteSasDefinitionCreateRequest(ctx context.Context, vaultBaseURL string, storageAccountName string, sasDefinitionName string, options *KeyVaultClientDeleteSasDefinitionOptions) (*policy.Request, error) {\n\thost := \"{vaultBaseUrl}\"\n\thost = strings.ReplaceAll(host, \"{vaultBaseUrl}\", vaultBaseURL)\n\turlPath := \"/storage/{storage-account-name}/sas/{sas-definition-name}\"\n\tif storageAccountName == \"\" {\n\t\treturn nil, errors.New(\"parameter storageAccountName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{storage-account-name}\", url.PathEscape(storageAccountName))\n\tif sasDefinitionName == \"\" {\n\t\treturn nil, errors.New(\"parameter sasDefinitionName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{sas-definition-name}\", url.PathEscape(sasDefinitionName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(host, urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"7.2\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header.Set(\"Accept\", \"application/json\")\n\treturn req, nil\n}", "func (s DeleteProjectOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteChannelResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (client BaseClient) DeleteSubscription(ctx context.Context, subscriptionID uuid.UUID, APIVersion string, xMsRequestid *uuid.UUID, xMsCorrelationid *uuid.UUID) (result Error, err error) {\n if tracing.IsEnabled() {\n ctx = tracing.StartSpan(ctx, fqdn + \"/BaseClient.DeleteSubscription\")\n defer func() {\n sc := -1\n if result.Response.Response != nil {\n sc = result.Response.Response.StatusCode\n }\n tracing.EndSpan(ctx, sc, err)\n }()\n }\n req, err := client.DeleteSubscriptionPreparer(ctx, subscriptionID, APIVersion, xMsRequestid, xMsCorrelationid)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", nil , \"Failure preparing request\")\n return\n }\n\n resp, err := client.DeleteSubscriptionSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", resp, \"Failure sending request\")\n return\n }\n\n result, err = client.DeleteSubscriptionResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"azuremarketplacesaas.BaseClient\", \"DeleteSubscription\", resp, \"Failure responding to request\")\n }\n\n return\n }", "func (s DeleteAddressBookOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteIntegrationResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeletePatchBaselineOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DeregisterPatchBaselineForPatchGroupOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DisassociateResolverRuleOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DisassociateServiceQuotaTemplateResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteResourcePolicyResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteSolutionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DisassociateSkillGroupFromRoomOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *RemoveLayerVersionPermissionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteLogPatternResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func UnmarshalChannelResponseDefinition(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(ChannelResponseDefinition)\n\terr = core.UnmarshalPrimitive(m, \"channel_id\", &obj.ChannelID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"name\", &obj.Name)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"description\", &obj.Description)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"type\", &obj.Type)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"severity\", &obj.Severity, UnmarshalChannelResponseDefinitionSeverity)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"endpoint\", &obj.Endpoint)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enabled\", &obj.Enabled)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"alert_source\", &obj.AlertSource, UnmarshalChannelResponseDefinitionAlertSourceItem)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"frequency\", &obj.Frequency)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (r *DeleteMailboxPermissionsResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteRolePolicyResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeletePolicyVersionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteScalingPlanResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteGatewayGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func UnmarshalPageRulesDeleteResponse(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(PageRulesDeleteResponse)\n\terr = core.UnmarshalPrimitive(m, \"success\", &obj.Success)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"errors\", &obj.Errors)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"messages\", &obj.Messages)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalModel(m, \"result\", &obj.Result, UnmarshalPageRulesDeleteResponseResult)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}", "func (client *KeyVaultClient) getDeletedSasDefinitionsHandleResponse(resp *http.Response) (KeyVaultClientGetDeletedSasDefinitionsResponse, error) {\n\tresult := KeyVaultClientGetDeletedSasDefinitionsResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.DeletedSasDefinitionListResult); err != nil {\n\t\treturn KeyVaultClientGetDeletedSasDefinitionsResponse{}, err\n\t}\n\treturn result, nil\n}", "func (s DeleteStageOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func MockDeleteMetadatumResponse(t *testing.T, key string) {\n\tth.Mux.HandleFunc(shareEndpoint+\"/\"+shareID+\"/metadata/\"+key, func(w http.ResponseWriter, r *http.Request) {\n\t\tth.TestMethod(t, r, \"DELETE\")\n\t\tth.TestHeader(t, r, \"X-Auth-Token\", fake.TokenID)\n\t\tw.WriteHeader(http.StatusOK)\n\t})\n}", "func (client *subscriptionClient) deleteHandleResponse(resp *http.Response) (SubscriptionDeleteResponse, error) {\n\tresult := SubscriptionDeleteResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsXML(resp, &result.Object); err != nil {\n\t\treturn SubscriptionDeleteResponse{}, err\n\t}\n\treturn result, nil\n}", "func (r *DeleteReusableDelegationSetResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *ConfirmSubscriptionResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteDomainEntryResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DescribeInventoryDeletionsOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (s DisassociateDeviceFromRoomOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteSkillGroupResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s StopAppReplicationOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (client *KeyVaultClient) getSasDefinitionHandleResponse(resp *http.Response) (KeyVaultClientGetSasDefinitionResponse, error) {\n\tresult := KeyVaultClientGetSasDefinitionResponse{RawResponse: resp}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.SasDefinitionBundle); err != nil {\n\t\treturn KeyVaultClientGetSasDefinitionResponse{}, err\n\t}\n\treturn result, nil\n}", "func (r *DeleteClientCertificateResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (m *GroupPolicyDefinitionsItemNextVersionDefinitionPreviousVersionDefinitionRequestBuilder) Delete(ctx context.Context, requestConfiguration *GroupPolicyDefinitionsItemNextVersionDefinitionPreviousVersionDefinitionRequestBuilderDeleteRequestConfiguration)(error) {\n requestInfo, err := m.ToDeleteRequestInformation(ctx, requestConfiguration);\n if err != nil {\n return err\n }\n errorMapping := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.ErrorMappings {\n \"4XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n \"5XX\": i20a3050780ee0b0cde0a884a4f35429a20d60067e3bcda382ec5400079147459.CreateODataErrorFromDiscriminatorValue,\n }\n err = m.BaseRequestBuilder.RequestAdapter.SendNoContent(ctx, requestInfo, errorMapping)\n if err != nil {\n return err\n }\n return nil\n}", "func (r *DeleteInstanceBackupRuleResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (s DeleteUserOutput) SDKResponseMetadata() aws.Response {\n\treturn s.responseMetadata\n}", "func (r *DeleteInstanceResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func (r *DeleteInstanceResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}", "func UnmarshalAnalyticsEngineCreateCustomizationResponse(m map[string]interface{}) (result *AnalyticsEngineCreateCustomizationResponse, err error) {\n\tobj := new(AnalyticsEngineCreateCustomizationResponse)\n\tobj.RequestID, err = core.UnmarshalFloat64(m, \"request_id\")\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj\n\treturn\n}", "func (r *DeletePipelineResponse) SDKResponseMetdata() *aws.Response {\n\treturn r.response\n}" ]
[ "0.58202094", "0.5759106", "0.5703992", "0.5664324", "0.55798805", "0.55427086", "0.5469124", "0.54644465", "0.5454366", "0.5450999", "0.5446981", "0.5435991", "0.54300785", "0.5424213", "0.540189", "0.5369609", "0.5356356", "0.5353937", "0.5351326", "0.5335966", "0.5329625", "0.53277797", "0.5313987", "0.5278754", "0.52759916", "0.52749294", "0.526926", "0.526418", "0.5261043", "0.52434075", "0.5241963", "0.5227595", "0.52052414", "0.52029884", "0.51895815", "0.5186396", "0.51711553", "0.516472", "0.5159134", "0.515643", "0.5144704", "0.5131712", "0.5127304", "0.5125167", "0.511042", "0.5104236", "0.50982696", "0.509551", "0.507998", "0.5065155", "0.5056461", "0.50551414", "0.50540704", "0.50302696", "0.5026668", "0.5026668", "0.50202185", "0.50185394", "0.50121206", "0.50077677", "0.4997072", "0.49761832", "0.49646127", "0.49456197", "0.49359792", "0.49237177", "0.4922244", "0.49215606", "0.4915033", "0.4908235", "0.4903217", "0.48989883", "0.4896712", "0.4889405", "0.48868877", "0.48754123", "0.48697364", "0.48654482", "0.48639607", "0.48609176", "0.4856925", "0.48563826", "0.48512322", "0.48475382", "0.48470753", "0.4835918", "0.48284468", "0.4825342", "0.48063824", "0.47807807", "0.47778362", "0.4773331", "0.47665155", "0.47631544", "0.47577822", "0.47561735", "0.47492257", "0.47492257", "0.47363013", "0.47328022" ]
0.66170776
0
SetupClient makes sure that whatever things need to be done before we use the datastore can be done before we need to use the datastore.
func (db *CXDBMemory) SetupClient(coins []*coinparam.Params) (err error) { db.puzzles = make(map[[32]byte][]*match.EncryptedAuctionOrder) db.puzzleMtx = new(sync.Mutex) db.balances = make(map[*pubkeyCoinPair]uint64) db.balancesMtx = new(sync.Mutex) db.orders = make(map[[32]byte][]*match.AuctionOrder) db.ordersMtx = new(sync.Mutex) return }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func setupClient() *Client {\n\treturn &Client{\n\t\tlogger: NewNilLogger(),\n\t\tpredicateKey: predicateKeyDefault,\n\t\ttemplate: templateDefault,\n\t\tmaxWorkerCount: maxWorkers,\n\t}\n}", "func (a *Agent) setupClient() error {\n\n\tconfig, err := a.clientConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client config setup failed: %v\", err)\n\t}\n\n\tclient, err := client.New(config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"client setup failed: %v\", err)\n\t}\n\n\ta.client = client\n\n\treturn nil\n}", "func setup() Client {\n\tvar (\n\t\tclient Client\n\t\tendPoints EndPoints\n\t\tuserCredentials UserCredentials\n\t\temail string\n\t\tid, secret string\n\t)\n\n\temail = os.Getenv(\"DISCORD_EMAIL\")\n\tid = os.Getenv(\"DISCORD_CLIENT_ID\")\n\tsecret = os.Getenv(\"DISCORD_SECRET\")\n\n\tclient = Client{}\n\tclient.ID, _ = strconv.Atoi(id)\n\tclient.Secret = secret\n\n\tendPoints = EndPoints{}\n\tendPoints.BaseURL = os.Getenv(\"DISCORD_API_URL\")\n\tendPoints.UsersEP = \"/users\"\n\n\tuserCredentials = UserCredentials{}\n\tuserCredentials.Email = email\n\n\tclient.EndPoints = endPoints\n\tclient.UserLogin = userCredentials\n\n\tfmt.Println(client)\n\treturn client\n}", "func clientSetup() (kube.Client, error) {\n\tconfig, err := kube.DefaultRestConfig(\"\", \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kube.NewClient(kube.NewClientConfigForRestConfig(config), \"\")\n}", "func SetupDBClient() *DBClient {\n\t\n\tdb := &DBClient{\n\t\tclient: redis.NewClient(&redis.Options{\n\t\t Addr: config.GetConfig().GetRedisURL(),\n\t\t Password: \"\",\n\t\t DB: 0,\n\t\t}),\n\t}\n\n\treturn db\n}", "func setupClient() *Client {\n\treturn &Client{\n\t\terr: make(chan error),\n\t\trequest: make(chan []byte, maxConCurrentMessages),\n\t\tresults: &sync.Map{},\n\t\tresultMessenger: &sync.Map{},\n\t\tlogger: logging.NewNilLogger(),\n\t\tgremlinVersion: \"3\",\n\t}\n}", "func Setup(t *testing.T) *test.Clients {\n\tif test.Flags.Namespace == \"\" {\n\t\ttest.Flags.Namespace = defaultNamespaceName\n\t}\n\n\tclients, err := test.NewClients(\n\t\ttest.Flags.Kubeconfig,\n\t\ttest.Flags.Cluster,\n\t\ttest.Flags.Namespace)\n\tif err != nil {\n\t\tt.Fatalf(\"Couldn't initialize clients: %v\", err)\n\t}\n\treturn clients\n}", "func clientSetup(t *testing.T) (*e2e.ManagementServer, string, uint32, func()) {\n\t// Spin up a xDS management server on a local port.\n\tnodeID := uuid.New().String()\n\tfs, err := e2e.StartManagementServer(e2e.ManagementServerOptions{})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create a bootstrap file in a temporary directory.\n\tbootstrapCleanup, err := bootstrap.CreateFile(bootstrap.Options{\n\t\tNodeID: nodeID,\n\t\tServerURI: fs.Address,\n\t\tServerListenerResourceNameTemplate: \"grpc/server\",\n\t})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Initialize a gRPC server and register the stubServer on it.\n\tserver := grpc.NewServer()\n\ttestgrpc.RegisterTestServiceServer(server, &testService{})\n\n\t// Create a local listener and pass it to Serve().\n\tlis, err := testutils.LocalTCPListener()\n\tif err != nil {\n\t\tt.Fatalf(\"testutils.LocalTCPListener() failed: %v\", err)\n\t}\n\n\tgo func() {\n\t\tif err := server.Serve(lis); err != nil {\n\t\t\tt.Errorf(\"Serve() failed: %v\", err)\n\t\t}\n\t}()\n\n\treturn fs, nodeID, uint32(lis.Addr().(*net.TCPAddr).Port), func() {\n\t\tfs.Stop()\n\t\tbootstrapCleanup()\n\t\tserver.Stop()\n\t}\n}", "func SetupForTesting(t *testing.T) (*client.Client, *sql.DB) {\n\tdb.CleanCache(t)\n\tdbc := db.ConnectForTesting(t)\n\tsrv, addr := NewServer(t, dbc)\n\n\tt.Cleanup(srv.Stop)\n\n\tconn, err := grpc.Dial(addr, grpc.WithInsecure(),\n\t\tgrpc.WithUnaryInterceptor(interceptors.UnaryClientInterceptor),\n\t\tgrpc.WithStreamInterceptor(interceptors.StreamClientInterceptor))\n\tjtest.RequireNil(t, err)\n\n\tgcl := pb.NewGokuClient(conn)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, conn.Close())\n\t})\n\n\tcl := client.New(gcl)\n\n\t// Wait until connected to avoid startup race.\n\tctx, cancel := context.WithTimeout(context.Background(), time.Second*2)\n\tdefer cancel()\n\n\tfor {\n\t\tif conn.GetState() == connectivity.Ready {\n\t\t\tbreak\n\t\t}\n\n\t\tif !conn.WaitForStateChange(ctx, conn.GetState()) {\n\t\t\trequire.Fail(t, \"grpc client connect timeout\")\n\t\t}\n\t}\n\n\treturn cl, dbc\n}", "func (e *Environment) SetupClientsets() error {\n\tvar err error\n\te.Clientset, err = kubernetes.NewForConfig(e.KubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\te.VersionedClientset, err = versioned.NewForConfig(e.KubeConfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.QuarksStatefulSetClient, err = qstsclient.NewForConfig(e.KubeConfig)\n\treturn err\n}", "func Setup(fixture Fixture, tableName string) (index.Client, chunkclient.Client, io.Closer, error) {\n\tvar tbmConfig index.TableManagerConfig\n\tflagext.DefaultValues(&tbmConfig)\n\tindexClient, chunkClient, tableClient, schemaConfig, closer, err := fixture.Clients()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\ttableManager, err := index.NewTableManager(tbmConfig, schemaConfig, 12*time.Hour, tableClient, nil, nil, nil)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\terr = tableManager.SyncTables(context.Background())\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\terr = tableClient.CreateTable(context.Background(), config.TableDesc{\n\t\tName: tableName,\n\t})\n\n\treturn indexClient, chunkClient, closer, err\n}", "func Setup() error {\n\tconfig := cfg.SharedConfig()\n\toptions := mq.NewClientOptions()\n\toptions.AddBroker(fmt.Sprintf(\"%s://%s:%s\",\n\t\tconfig.MQTT.Transport,\n\t\tconfig.MQTT.Address,\n\t\tconfig.MQTT.Port,\n\t))\n\toptions.SetClientID(config.MQTT.ClientID)\n\tclient = mq.NewClient(options)\n\tif token := client.Connect(); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t} else {\n\t\tlogger.Println(\"MQTT client connected\")\n\t}\n\n\tif token := client.Subscribe(config.MQTT.Topics.Demand, 0, handleDemand); token.Wait() && token.Error() != nil {\n\t\treturn token.Error()\n\t}\n\n\treturn nil\n}", "func (s *TestBase) Setup() {\n\tvar err error\n\tshardID := 10\n\tclusterName := s.ClusterMetadata.GetCurrentClusterName()\n\n\ts.DefaultTestCluster.SetupTestDatabase()\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\ts.VisibilityTestCluster.SetupTestDatabase()\n\t}\n\n\tcfg := s.DefaultTestCluster.Config()\n\tfactory := client.NewFactory(&cfg, clusterName, nil, s.logger)\n\n\ts.TaskMgr, err = factory.NewTaskManager()\n\ts.fatalOnError(\"NewTaskManager\", err)\n\n\ts.MetadataManager, err = factory.NewMetadataManager()\n\ts.fatalOnError(\"NewMetadataManager\", err)\n\n\ts.HistoryV2Mgr, err = factory.NewHistoryManager()\n\ts.fatalOnError(\"NewHistoryManager\", err)\n\n\ts.ShardMgr, err = factory.NewShardManager()\n\ts.fatalOnError(\"NewShardManager\", err)\n\n\ts.ExecutionMgrFactory = factory\n\ts.ExecutionManager, err = factory.NewExecutionManager(shardID)\n\ts.fatalOnError(\"NewExecutionManager\", err)\n\n\tvisibilityFactory := factory\n\tif s.VisibilityTestCluster != s.DefaultTestCluster {\n\t\tvCfg := s.VisibilityTestCluster.Config()\n\t\tvisibilityFactory = client.NewFactory(&vCfg, clusterName, nil, s.logger)\n\t}\n\t// SQL currently doesn't have support for visibility manager\n\ts.VisibilityMgr, err = visibilityFactory.NewVisibilityManager()\n\tif err != nil {\n\t\ts.fatalOnError(\"NewVisibilityManager\", err)\n\t}\n\n\ts.ReadLevel = 0\n\ts.ReplicationReadLevel = 0\n\ts.ShardInfo = &p.ShardInfo{\n\t\tShardID: shardID,\n\t\tRangeID: 0,\n\t\tTransferAckLevel: 0,\n\t\tReplicationAckLevel: 0,\n\t\tTimerAckLevel: time.Time{},\n\t\tClusterTimerAckLevel: map[string]time.Time{clusterName: time.Time{}},\n\t\tClusterTransferAckLevel: map[string]int64{clusterName: 0},\n\t}\n\n\ts.TaskIDGenerator = &TestTransferTaskIDGenerator{}\n\terr = s.ShardMgr.CreateShard(&p.CreateShardRequest{ShardInfo: s.ShardInfo})\n\ts.fatalOnError(\"CreateShard\", err)\n\n\tqueue, err := factory.NewDomainReplicationQueue()\n\ts.fatalOnError(\"Create DomainReplicationQueue\", err)\n\ts.DomainReplicationQueue = queue\n}", "func (h *H) Setup() {\n\tvar err error\n\th.restConfig, err = clientcmd.RESTConfigFromKubeConfig(h.Kubeconfig.Contents)\n\tExpect(err).ShouldNot(HaveOccurred(), \"failed to configure client\")\n\n\tif len(h.InstalledWorkloads) < 1 {\n\t\th.InstalledWorkloads = make(map[string]string)\n\t}\n\n\t// setup project to run tests\n\tsuffix := randomStr(5)\n\tproj, err := h.createProject(suffix)\n\tExpect(err).ShouldNot(HaveOccurred(), \"failed to create project\")\n\tExpect(proj).ShouldNot(BeNil())\n\n\th.proj = proj\n}", "func (sdkClient *SDKClient) Initialize() error {\n\t_LOGGER.Println(\"SDKClient.Initialize: start\")\n\n\t// Create SDK setup for the integration tests\n\tsdkOptions := deffab.Options{\n\t\tConfigFile: sdkClient.ConfigFile,\n\t\t//\t\tOrgID: setup.OrgID,\n\t\tStateStoreOpts: opt.StateStoreOpts{\n\t\t\tPath: \"/tmp/enroll_user\",\n\t\t},\n\t}\n\n\tsdk, err := deffab.NewSDK(sdkOptions)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error initializing SDK: %s\", err)\n\t}\n\t_LOGGER.Println(\"SDK Created \")\n\tsdkClient.SDK = sdk\n\tsession, err := sdk.NewPreEnrolledUserSession(sdkClient.OrgID, \"Admin\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting admin user session for org: %s\", err)\n\t}\n\tsc, err := sdk.NewSystemClient(session)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"NewSystemClient returned error: %v\", err)\n\t}\n\n\tsdkClient.Client = sc\n\tsdkClient.AdminUser = session.Identity()\n\t_LOGGER.Println(\"Admin context found \")\n\tordererAdmin, err := sdk.NewPreEnrolledUser(\"ordererorg\", \"Admin\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error getting orderer admin user: %v\", err)\n\t}\n\n\tsdkClient.OrdererAdmin = ordererAdmin\n\t_LOGGER.Println(\"Orderer admin is retrieved \")\n\n\tsdkClient.Initialized = true\n\n\treturn nil\n}", "func setupDatabase(t *testing.T) (client *entity.Client) {\n\tclient = enttest.Open(t, \"sqlite3\", \"file:ent?mode=memory&_fk=1\")\n\tctx := context.Background()\n\tif err := client.Schema.Create(ctx); err != nil {\n\t\tpanic(err)\n\t}\n\n\tif err := setSampleData(ctx, client); err != nil {\n\t\tpanic(err)\n\t}\n\treturn client\n}", "func InitDatastore() *datastore.Client {\n\tstore, err := datastore.NewClient(context.Background(), os.Getenv(envVarNames[evProjectID]))\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get datastore client: %v\\n\", err)\n\t}\n\treturn store\n}", "func setup() {\n\t// test server\n\tmux = http.NewServeMux()\n\tserver = httptest.NewServer(mux)\n\n\t// configure findface client to use test server\n\tclient = NewClient(token, nil, nil)\n\n\turl, _ := url.Parse(server.URL)\n\tclient.BaseURL = url\n}", "func (s *MarketplaceTestSuite) SetupTest() {\n\t// call parent's method.\n\ts.AppTestSuite.SetupTest()\n\n\tconn, err := NewGRPCClient(s.App.Creds())\n\ts.Require().NoError(err, \"cannot get grpc client\")\n\n\ts.conn = conn\n\ts.client = pb.NewMarketClient(conn)\n}", "func TestSetup(t *testing.T) {\n\ttestServer, testData = setup(t) // Initialize all test data for this suite.\n\tdataClient = data.NewClient()\n}", "func setupFakeClient(url string) *Client {\n\treturn &Client{\n\t\tServiceEndpoint: ServiceEndpoint{\n\t\t\tRequestURL: url,\n\t\t\tDocsURL: \"some-docs-url\",\n\t\t},\n\t}\n}", "func (p *Provider) clientSetup() (*Client, error) {\n\tdefer metrics.MeasureSince([]string{\"scada\", \"setup\"}, time.Now())\n\n\t// Reset the previous backoff\n\tp.backoffLock.Lock()\n\tp.noRetry = false\n\tp.backoff = 0\n\tp.backoffLock.Unlock()\n\n\t// Dial a new connection\n\topts := Opts{\n\t\tAddr: p.config.Endpoint,\n\t\tTLS: true,\n\t\tTLSConfig: p.config.TLSConfig,\n\t\tLogOutput: p.config.LogOutput,\n\t}\n\tclient, err := DialOpts(&opts)\n\tif err != nil {\n\t\tp.logger.Printf(\"[ERR] scada-client: failed to dial: %v\", err)\n\t\treturn nil, err\n\t}\n\n\t// Perform a handshake\n\tresp, err := p.handshake(client)\n\tif err != nil {\n\t\tp.logger.Printf(\"[ERR] scada-client: failed to handshake: %v\", err)\n\t\tclient.Close()\n\t\treturn nil, err\n\t}\n\tif resp != nil && resp.SessionID != \"\" {\n\t\tp.logger.Printf(\"[DEBUG] scada-client: assigned session '%s'\", resp.SessionID)\n\t}\n\tif resp != nil && !resp.Authenticated {\n\t\tp.logger.Printf(\"[WARN] scada-client: authentication failed: %v\", resp.Reason)\n\t}\n\n\t// Set the new client\n\tp.clientLock.Lock()\n\tif p.client != nil {\n\t\tp.client.Close()\n\t}\n\tp.client = client\n\tp.clientLock.Unlock()\n\n\tp.sessionLock.Lock()\n\tp.sessionID = resp.SessionID\n\tp.sessionAuth = resp.Authenticated\n\tp.sessionLock.Unlock()\n\n\treturn client, nil\n}", "func (migration *Migration) SetupDbClient(user, password, cert, key, rootCA string, port int) error {\n\ttlsConfig := &dbclient.TlsConfig{}\n\tif (cert != \"\") && (key != \"\") && (rootCA != \"\") {\n\t\ttlsConfig.UseTls = true\n\t\ttlsConfig.RootCA = rootCA\n\t\ttlsConfig.ClientCert = cert\n\t\ttlsConfig.ClientKey = key\n\t}\n\thost := \"tcp(\" + migration.Host + \":\" + strconv.Itoa(port) + \")\"\n\tdb, err := newDbClient(user, password, host, migration.Database, \"\", tlsConfig)\n\tif err != nil {\n\t\tglog.Errorf(\"Failed to connect to the database (error: %s).\", err)\n\t\treturn ErrDbConnect\n\t} else {\n\t\tmigration.DbClient = db\n\t}\n\tglog.Infof(\"Successfully connected to the database (host = %s, user = %s, database = %s, root ca = %s, cert = %s, key = %s).\",\n\t\thost, user, migration.Database, rootCA, cert, key)\n\treturn nil\n}", "func InitializeClient(c StorageClient) {\n\tif c == nil {\n\t\tclient = &storageclient.ThirdPartyClient{}\n\t} else {\n\t\tclient = c\n\t}\n}", "func setupClient(t *testing.T, serverResponseBody string) (*lokalise.Client, *fixture, func()) {\n\treturn setupServerAndClient(t, func(f *fixture) http.HandlerFunc {\n\t\treturn func(rw http.ResponseWriter, req *http.Request) {\n\t\t\tf.calledMethod = req.Method\n\t\t\tf.calledPath = req.URL.Path\n\t\t\trequestBody, err := ioutil.ReadAll(req.Body)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"read request body failed: %v\", err)\n\t\t\t}\n\t\t\tf.requestBody = string(requestBody)\n\t\t\trw.Header().Set(\"Content-Type\", \"application/json\")\n\t\t\trw.WriteHeader(http.StatusOK)\n\t\t\tfmt.Fprint(rw, serverResponseBody)\n\t\t}\n\t})\n}", "func (m *gaeModule) initDSClient(ctx context.Context, host module.Host, cloudProject string, poolSize int) (*datastore.Client, error) {\n\tlogging.Infof(ctx, \"Setting up datastore client for project %q\", cloudProject)\n\n\t// Enable auth only when using the real datastore.\n\tvar clientOpts []option.ClientOption\n\tif addr := os.Getenv(\"DATASTORE_EMULATOR_HOST\"); addr == \"\" {\n\t\tts, err := auth.GetTokenSource(ctx, auth.AsSelf, auth.WithScopes(auth.CloudOAuthScopes...))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"failed to initialize the token source\").Err()\n\t\t}\n\t\tclientOpts = []option.ClientOption{\n\t\t\toption.WithTokenSource(ts),\n\t\t\toption.WithGRPCDialOption(grpcmon.WithClientRPCStatsMonitor()),\n\t\t}\n\t}\n\n\tif poolSize > 0 {\n\t\tclientOpts = append(clientOpts, option.WithGRPCConnectionPool(poolSize))\n\t}\n\tclient, err := datastore.NewClient(ctx, cloudProject, clientOpts...)\n\tif err != nil {\n\t\treturn nil, errors.Annotate(err, \"failed to instantiate the datastore client\").Err()\n\t}\n\n\thost.RegisterCleanup(func(ctx context.Context) {\n\t\tif err := client.Close(); err != nil {\n\t\t\tlogging.Warningf(ctx, \"Failed to close the datastore client - %s\", err)\n\t\t}\n\t})\n\n\t// TODO(vadimsh): \"Ping\" the datastore to verify the credentials are correct?\n\n\treturn client, nil\n}", "func initializeBoltClient() {\n\tservice.DBClient = &dbclient.BoltClient{}\n\tservice.DBClient.OpenBoltDb()\n\tservice.DBClient.Seed()\n}", "func initializeBoltClient() {\n\tmiddleware.DBClient = &dbClients.BoltClient{} // create boltDB instance by passing an implementation of the interface to it\n\tmiddleware.DBClient.OpenBoltDB()\n\tmiddleware.DBClient.Seed()\n}", "func (coord *Coordinator) Setup(\n\tchainA, chainB *TestChain,\n) (string, string) {\n\tclientA, clientB := coord.SetupClientConnections(chainA, chainB, exported.Tendermint)\n\n\treturn clientA, clientB\n}", "func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {\n\t// mux is the HTTP request multiplexer used with the test server.\n\tmux = http.NewServeMux()\n\tserver := httptest.NewServer(mux)\n\n\t// client configured to use test server\n\tclient, _ = NewClient(testAPIKey, nil)\n\turl, _ := url.Parse(server.URL + \"/\")\n\n\tclient.BaseURL = url\n\tclient.JWTAuthToken = testJWTAuthToken\n\n\treturn client, mux, server.URL, server.Close\n}", "func setupServerAndClient(t *testing.T, handler func(*fixture) http.HandlerFunc) (*lokalise.Client, *fixture, func()) {\n\tf := fixture{}\n\tserver := httptest.NewServer(handler(&f))\n\tt.Logf(\"http server: %s\", server.URL)\n\tclient, err := lokalise.NewClient(\"token\",\n\t\tlokalise.WithBaseURL(server.URL),\n\t\tlokalise.WithLogger(&testLogger{T: t}),\n\t)\n\tif err != nil {\n\t\tserver.Close()\n\t\tt.Fatalf(\"unexpected client instantiation error: %v\", err)\n\t}\n\treturn client, &f, server.Close\n}", "func setup() {\r\n\tvar err error\r\n\tclient, err = mongo.NewClient(options.Client().ApplyURI(\"mongodb://127.0.0.1:27017\"))\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\tctx, _ := context.WithTimeout(context.Background(), 10*time.Second) //time out for connection attempts.\r\n\terr = client.Connect(ctx)\r\n\tif err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\r\n\tlen := 5\r\n\tb := make([]byte, len)\r\n\tif _, err := rand.Read(b); err != nil {\r\n\t\tlog.Fatalf(\"init test failed... %s\", err)\r\n\t}\r\n\r\n\tfirstname = fmt.Sprintf(\"%X\", b)\r\n\tlastname = fmt.Sprintf(\"%X\", b)\r\n}", "func (clients *ClientSets) SetFakeClient() {\n\n\t// Load kubernetes client set by preloading with k8s objects.\n\tclients.KubeClient = fake.NewSimpleClientset([]runtime.Object{}...)\n\n\t// Load litmus client set by preloading with litmus objects.\n\tclients.LitmusClient = litmusFakeClientset.NewSimpleClientset([]runtime.Object{}...)\n}", "func setup() {\n\t// test server\n\tmux = http.NewServeMux()\n\tmux.Handle(\"/foo1\", http.HandlerFunc(limitResponseHandler))\n\tserver = httptest.NewServer(mux)\n\n\t// appnexus client configured to use test server\n\tclient, _ = NewClient(server.URL)\n\twaiter = false\n}", "func Setup() error {\n\tnamespace := flag.String(\"namespace\", \"default\", \"Integration test namespace\")\n\toperatorNamespace := flag.String(\"operatorNamespace\", \"\", \"Local test run mimicks prod environments\")\n\tskipTeardown := flag.Bool(\"skipteardown\", false, \"Skips tearing down instances created by the tests\")\n\trunid := flag.String(\"runid\", \"test-\"+generateRandomID(3), \"Optional string that will be used to uniquely identify this test run.\")\n\tkubeconfig := os.Getenv(\"KUBECONFIG\")\n\tif home := homeDir(); home != \"\" {\n\t\tkubeconfig = *(flag.String(\"kubeconf\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolute path to the kubeconfig file\"))\n\t} else {\n\t\tkubeconfig = *(flag.String(\"kubeconf\", \"\", \"absolute path to the kubeconfig file\"))\n\t}\n\tflag.Parse()\n\n\tif *operatorNamespace == \"\" {\n\t\toperatorNamespace = namespace\n\t}\n\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trestClient, err := GetRestClientForDellStorage(kubeconfig)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsnapClient, err := snapClient.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tGlobal = &Framework{\n\t\tKubeClient: kubeClient,\n\t\tKubeClient2: *kubeClient,\n\t\tRestClient: *restClient,\n\t\tSnapshotClientBeta: *snapClient,\n\t\tNamespace: *namespace,\n\t\tOperatorNamespace: *operatorNamespace,\n\t\tSkipTeardown: *skipTeardown,\n\t\tRunID: *runid,\n\t}\n\n\treturn nil\n}", "func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {\n\treturn setupWithPath(\"\")\n}", "func (m *Module) Setup() error {\n\tm.ModuleName = \"Netatmo Homecoach\"\n\tm.ModuleDescription = \"Publish Netatmo Homecoach readings to a SensorThings server\"\n\tm.Endpoints = m.getEndpoints()\n\n\tm.settings = Settings{}\n\terr := m.GetSettings(&m.settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(m.settings.ClientID) == 0 || len(m.settings.ClientSecret) == 0 || len(m.settings.Username) == 0 || len(m.settings.Password) == 0 {\n\t\tm.SendError(fmt.Errorf(\"missing config parameters\"), true)\n\t}\n\n\tm.client, err = NewClient(Config{\n\t\tClientID: m.settings.ClientID,\n\t\tClientSecret: m.settings.ClientSecret,\n\t\tUsername: m.settings.Username,\n\t\tPassword: m.settings.Password,\n\t})\n\tif err != nil {\n\t\tm.SendError(fmt.Errorf(\"unable to create Netatmo Homecoach client\"), true)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (suite *MainTestSuite) SetupSuite() {\n\t// initialize the rouge client (on localhost)\n\t// rougeClient := &rouge.Client{Host: \"localhost:6379\"}\n\t// rougeClient.Init()\n\n\trougeClient, err := rouge.NewRougeClient()\n\tsuite.Nil(err)\n\n\t// initialize the server, with our rougeClient\n\tsuite.server = &server{rouge: rougeClient}\n}", "func (coord *Coordinator) SetupClients(\n\tchainA, chainB *TestChain,\n\tclientType string,\n) (string, string) {\n\n\tclientA, err := coord.CreateClient(chainA, chainB, clientType)\n\trequire.NoError(coord.t, err)\n\n\tclientB, err := coord.CreateClient(chainB, chainA, clientType)\n\trequire.NoError(coord.t, err)\n\n\treturn clientA, clientB\n}", "func Setup(isSecure, nop bool) *http.Client {\n\n\tc := http.DefaultClient\n\n\t//Às vezes, para teste, queremos\n\t// desligar a verificação SSL\n\tif !isSecure {\n\t\tc.Transport = &http.Transport{\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tInsecureSkipVerify: false,\n\t\t\t},\n\t\t}\n\t}\n\n\tif nop {\n\t\tc.Transport = &NopTransport{}\n\t}\n\n\thttp.DefaultClient = c\n\treturn c\n}", "func Setup(ctx context.Context, logger *logging.BaseLogger, promReqd bool) (*PerformanceClient, error) {\n\tclients, err := test.NewClients(pkgTest.Flags.Kubeconfig, pkgTest.Flags.Cluster, test.ServingNamespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar p *prometheus.PromProxy\n\tif promReqd {\n\t\tlogger.Infof(\"Creating prometheus proxy client\")\n\t\tp = &prometheus.PromProxy{Namespace: monitoringNS}\n\t\tp.Setup(ctx, logger)\n\t}\n\treturn &PerformanceClient{E2EClients: clients, PromClient: p}, nil\n}", "func (r *Client) Setup() {\n\tfile, err := ioutil.ReadFile(r.Library)\n\tif err != nil {\n\t\tfmt.Printf(\"[ERRO] Could not load library: %v\\n\", err)\n\t\treturn\n\t}\n\n\terr = xml.Unmarshal([]byte(file), &r.Db)\n\tif err != nil {\n\t\tfmt.Printf(\"error: %v\", err)\n\t\treturn\n\t}\n\n\t// Add Id\n\tfor i := 0; i < len(r.Db.Entries); i++ {\n\t\tr.Db.Entries[i].Id = i\n\t}\n\n\t// Sort out the unique artists, albums and genres\n\tfor _, e := range r.Db.Entries {\n\t\tif len(e.Album) > 0 {\n\t\t\tif !r.AlbumExists(e.Album) {\n\t\t\t\titem := Item{\n\t\t\t\t\tId: e.Id,\n\t\t\t\t\tName: e.Album,\n\t\t\t\t\tType: \"Album\",\n\t\t\t\t\tEntry: e,\n\t\t\t\t\tHasGenre: e.Genre != \"Unknown\",\n\t\t\t\t}\n\t\t\t\t// Try and get a pic\n\t\t\t\titem.Image, item.HasImage = r.GetAlbumImage(e.Id)\n\n\t\t\t\tr.Albums = append(r.Albums, item)\n\t\t\t}\n\t\t}\n\t\tif len(e.Artist) > 0 {\n\t\t\tif !r.ArtistExists(e.Artist) {\n\t\t\t\titem := Item{\n\t\t\t\t\tId: e.Id,\n\t\t\t\t\tName: e.Artist,\n\t\t\t\t\tType: \"Artist\",\n\t\t\t\t\tCount: 1,\n\t\t\t\t\tEntry: e,\n\t\t\t\t\tHasGenre: e.Genre != \"Unknown\",\n\t\t\t\t}\n\t\t\t\tr.Artists = append(r.Artists, item)\n\t\t\t} else {\n\t\t\t\tr.IncrementArtistCount(e.Artist)\n\t\t\t}\n\t\t}\n\n\t\tif len(e.Genre) > 0 && e.Genre != \"Unknown\" {\n\t\t\tif !r.GenreExists(e.Genre) {\n\t\t\t\titem := Item{\n\t\t\t\t\tId: e.Id,\n\t\t\t\t\tName: e.Genre,\n\t\t\t\t\tType: \"Genre\",\n\t\t\t\t\tCount: 1,\n\t\t\t\t\tEntry: e,\n\t\t\t\t\tHasGenre: e.Genre != \"Unknown\",\n\t\t\t\t}\n\t\t\t\tr.Genres = append(r.Genres, item)\n\t\t\t} else {\n\t\t\t\tr.IncrementGenreCount(e.Genre)\n\t\t\t}\n\t\t}\n\t}\n}", "func (h *Handler) setupClient(client, worker string) (*Client, error) {\n\tvar err error\n\th.p.mu.Lock()\n\tlock, exists := h.p.clientSetupMutex[client]\n\tif !exists {\n\t\tlock = &deadlock.Mutex{}\n\t\th.p.clientSetupMutex[client] = lock\n\t}\n\th.p.mu.Unlock()\n\n\t// start := time.Now()\n\t// log.Println(\"lock: \", client, \" \", worker)\n\tlock.Lock()\n\tdefer func() {\n\t\tlock.Unlock()\n\t\t// log.Printf(\"unlock: %s %s %f\", client, worker, time.Now().Sub(start).Seconds())\n\t}()\n\tc, err := h.p.FindClientDB(client)\n\tif err == ErrNoUsernameInDatabase {\n\t\tc, err = newClient(h.p, client)\n\t\tif err != nil {\n\t\t\t//fmt.Println(\"Failed to create a new Client\")\n\t\t\th.p.log.Printf(\"Failed to create a new Client: %s\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t\terr = h.p.AddClientDB(c)\n\t\tif err != nil {\n\t\t\th.p.log.Printf(\"Failed to add client to DB: %s\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tif err != nil {\n\t\t\th.p.log.Printf(\"Failed to get client from DB: %s\\n\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif h.p.Client(client) == nil {\n\t\th.p.log.Printf(\"Adding client in memory: %s\\n\", client)\n\t\th.p.AddClient(c)\n\t}\n\treturn c, nil\n}", "func setup() {\n\ttMux = http.NewServeMux()\n\ttServer = httptest.NewServer(tMux)\n\ttConf = NewAPITestingConfig(true)\n\ttClient, _ = NewClient(nil, tConf)\n\tu, _ := url.Parse(tServer.URL + \"/\")\n\ttClient.BaseURL = u\n}", "func InitDatastore(t *testing.T, kinds ...ds.Kind) CleanupFunc {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\n\tif os.Getenv(\"DATASTORE_EMULATOR_HOST\") == \"\" {\n\t\tt.Skip(`Skipping tests that require a local Cloud Datastore emulator.\n\nRun\n\n\t\"gcloud beta emulators datastore start --no-store-on-disk --host-port=localhost:8888\"\n\nand then run\n\n $(gcloud beta emulators datastore env-init)\n\nto set the environment variables. When done running tests you can unset the env variables:\n\n $(gcloud beta emulators datastore env-unset)\n\n`)\n\t}\n\terr := ds.InitForTesting(\"test-project\", fmt.Sprintf(\"test-namespace-%d\", r.Uint64()))\n\tassert.NoError(t, err)\n\tcleanup(t, kinds...)\n\treturn func() {\n\t\tcleanup(t, kinds...)\n\t}\n}", "func InitManagerClient() {\n\tclientUrl, clientUser, clientPass, err := getClientParams()\n\tif err != nil {\n\t\teh.ExitOnError(err)\n\t}\n\n\t// Get a new manager client\n\tclient, err := util.NewManagerClient(clientUrl, clientUser, clientPass)\n\tif err != nil {\n\t\teh.ExitOnError(err)\n\t}\n\tmc = client\n}", "func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {\n\t// mux is the HTTP request multiplexer used with the test server.\n\tmux = http.NewServeMux()\n\n\tapiHandler := http.NewServeMux()\n\tapiHandler.Handle(baseURLPath+\"/\", http.StripPrefix(baseURLPath, mux))\n\tapiHandler.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tfmt.Fprintln(os.Stderr, \"FAIL: Client.BaseURL path prefix is not preserved in the request URL:\")\n\t\tfmt.Fprintln(os.Stderr)\n\t\tfmt.Fprintln(os.Stderr, \"\\t\"+req.URL.String())\n\t\thttp.Error(w, \"Client.BaseURL path prefix is not preserved in the request URL.\", http.StatusInternalServerError)\n\t})\n\n\t// server is a test HTTP server used to provide mock API responses.\n\tserver := httptest.NewServer(apiHandler)\n\n\t// client is the Harvest client being tested and is\n\t// configured to use test server.\n\tclient = NewClient(\"access_token\", \"account_id\")\n\turl, _ := url.Parse(server.URL + baseURLPath + \"/\")\n\tclient.BaseURL = url\n\n\treturn client, mux, server.URL, server.Close\n}", "func setup() {\n\tvar err error\n\tdb, err = sql.Open(\"postgres\", config.DataBase.Postgres())\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\terr = db.Ping()\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tts = httptest.NewServer(handler())\n\n\tclient = &http.Client{}\n}", "func (s *Suite) Setup() {\n\t// We manipuate the Args to set them up for the testcases\n\t// after this test we restore the initial args\n\toldArgs := os.Args\n\tdefer func() { os.Args = oldArgs }()\n\tcases := []struct {\n\t\tName string\n\t\tArgs []string\n\t}{\n\t\t{\"flags set\", []string{\"--config\", \"../../internal/config/config.yaml\", \"--environment\", \"test\"}},\n\t}\n\tfor _, tc := range cases {\n\t\t// this call is required because otherwise flags panics, if args are set between flag.Parse calls\n\t\tflag.CommandLine = flag.NewFlagSet(tc.Name, flag.ExitOnError)\n\t\t// we need a value to set Args[0] to, cause flag begins parsing at Args[1]\n\t\tos.Args = append([]string{tc.Name}, tc.Args...)\n\t}\n\n\tconfig.Init()\n\n\ts.ent = enttest.Open(s.T(), dialect.SQLite,\n\t\tfmt.Sprintf(\"file:%s-%d?mode=memory&cache=shared&_fk=1\",\n\t\t\ts.T().Name(), time.Now().UnixNano(),\n\t\t),\n\t\tenttest.WithMigrateOptions(migrate.WithGlobalUniqueID(true)),\n\t)\n\n\tsrv := handler.New(resolver.NewSchema(s.ent))\n\tsrv.AddTransport(transport.POST{})\n\tsrv.Use(entgql.Transactioner{TxOpener: s.ent})\n\n\tm := auth.Middleware(s.ent)\n\ts.Client = client.New(m(srv))\n\n\tinitdb.InitData(context.Background(), s.ent, config.AppConfig)\n\tInitUser = s.LoginWithInitUser()\n}", "func (suite *TestSuite) SetupTest() {\n\thostname := \"localhost\"\n\tusername := \"bleh\"\n\tpassword := \"bleh\"\n\tsuite.client = NewClient(hostname, username, password, false, true)\n}", "func Setup() *CoreTest {\n\tct := new(CoreTest)\n\tct.DB = LoadDatabase(ct.Core.Log)\n\tct.Core, ct.Test = Services(ct.DB)\n\tct.Request = NewRequest()\n\treturn ct\n}", "func InitClient(ctx context.Context) (*firestore.Client, error) {\n\tclient, err := firestore.NewClient(ctx, ProjectId)\n\tif err != nil {\n\t\treturn nil, errors.New(\"could not open firestore client\")\n\t}\n\treturn client, nil\n}", "func Setup(conf *config.Config) error {\n\tredisConf := conf.AdminRedis\n\tcli := helper.NewRedisClient(&redisConf, nil)\n\tif cli.Ping(dummyCtx).Err() != nil {\n\t\treturn errors.New(\"can not connect to admin redis\")\n\t}\n\t_tokenManager = NewTokenManager(cli)\n\treturn nil\n}", "func (r *CosmosDBReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&v1alpha1.CosmosDB{}).\n\t\tComplete(r)\n}", "func Test_Init(t *testing.T) {\n\tclient, err := Load(\"\", true)\n\tassert.Nil(t, err)\n\tmockClient = client\n}", "func (c *Client) Setup() error {\n\tqueries := []string{\n\t\tfmt.Sprintf(createAdminQuery, constants.InfluxDBAdminUser, constants.InfluxDBAdminPassword),\n\t\tfmt.Sprintf(createUserQuery, constants.InfluxDBGrafanaUser, constants.InfluxDBGrafanaPassword),\n\t\tfmt.Sprintf(createDatabaseQuery, constants.InfluxDBDatabase, constants.DurationDefault),\n\t\tfmt.Sprintf(grantReadQuery, constants.InfluxDBDatabase, constants.InfluxDBGrafanaUser),\n\t\tfmt.Sprintf(createRetentionPolicyQuery, constants.InfluxDBRetentionPolicy,\n\t\t\tconstants.InfluxDBDatabase, constants.DurationDefault) + \" default\",\n\t\tfmt.Sprintf(createRetentionPolicyQuery, constants.RetentionMedium, constants.InfluxDBDatabase,\n\t\t\tconstants.DurationMedium),\n\t\tfmt.Sprintf(createRetentionPolicyQuery, constants.RetentionLong, constants.InfluxDBDatabase,\n\t\t\tconstants.DurationLong),\n\t}\n\tfor _, query := range queries {\n\t\tlog.Infof(\"%v\", query)\n\n\t\tresponse, err := c.PostForm(c.Endpoint(\"query\"), url.Values{\"q\": []string{query}})\n\t\tif err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\n\t\tlog.Infof(\"%v %v %v\", response.Code(), response.Headers(), string(response.Bytes()))\n\t}\n\treturn nil\n}", "func clientSetup(t *testing.T, tss testpb.TestServiceServer) (uint32, func()) {\n\t// Initialize a gRPC server and register the stubServer on it.\n\tserver := grpc.NewServer()\n\ttestpb.RegisterTestServiceServer(server, tss)\n\n\t// Create a local listener and pass it to Serve().\n\tlis, err := testutils.LocalTCPListener()\n\tif err != nil {\n\t\tt.Fatalf(\"testutils.LocalTCPListener() failed: %v\", err)\n\t}\n\n\tgo func() {\n\t\tif err := server.Serve(lis); err != nil {\n\t\t\tt.Errorf(\"Serve() failed: %v\", err)\n\t\t}\n\t}()\n\n\treturn uint32(lis.Addr().(*net.TCPAddr).Port), func() {\n\t\tserver.Stop()\n\t}\n}", "func Setup(db *gorm.DB) error {\n\tlog.SetOutput(ioutil.Discard)\n\tdefer log.SetOutput(os.Stderr)\n\tadapter := gormadapter.NewAdapterByDB(db)\n\tenf, err := casbin.NewEnforcerSafe(conf, adapter)\n\tif err != nil {\n\t\treturn err\n\t}\n\tenf.EnableLog(false)\n\tenf.LoadPolicy()\n\tenforcer = enf\n\treturn nil\n}", "func (c *Config) setupConsoleClient() {\n\tclient, err := console.NewClient(nil, &console.Config{\n\t\tRegion: c.Region,\n\t\tDebugLog: c.DebugLog,\n\t})\n\tif err != nil {\n\t\tc.consoleClient = nil\n\t\tc.consoleClientErr = err\n\t\treturn\n\t}\n\tif c.UAAUsername == \"\" || c.UAAPassword == \"\" {\n\t\tc.consoleClientErr = ErrMissingUAACredentials\n\t\tc.consoleClient = nil\n\t\treturn\n\t}\n\terr = client.Login(c.UAAUsername, c.UAAPassword)\n\tif err != nil {\n\t\tc.consoleClientErr = err\n\t\treturn\n\t}\n\tc.consoleClient = client\n}", "func SetupTLSClient(client *http.Client, certPath string, keyPath string, caCertPath string) error {\n\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsConfig, err := commonTLSConfig(caCertPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttlsConfig.Certificates = []tls.Certificate{cert}\n\ttlsConfig.BuildNameToCertificate()\n\n\ttransport := &http.Transport{TLSClientConfig: tlsConfig}\n\tclient.Transport = transport\n\n\treturn nil\n}", "func setup() {\n\tmux = http.NewServeMux()\n\tserver = httptest.NewServer(mux)\n\n\tparams := CommonParams{LoginToken: \"dnspod login token\"}\n\n\tclient = NewClient(params)\n\tclient.BaseURL = server.URL + \"/\"\n}", "func (s *syncer) dbSetup() error {\n\ts.logger.Info(\"Connecting to the database\")\n\n\tsqlDB, err := sql.Open(\"sqlite3_with_fk\", s.config.Database)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Setup the DB struct\n\ts.db = sqlDB\n\n\t// We don't want multiple clients during setup\n\ts.db.SetMaxOpenConns(1)\n\n\t// Test the connection\n\terr = s.db.Ping()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Create the DB schema (if needed)\n\t_, err = s.db.Exec(schema)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Set the connection limit for the DB pool\n\ts.db.SetMaxOpenConns(10)\n\n\treturn nil\n}", "func (t *Tstore) Setup() error {\n\tlog.Infof(\"Building backend token prefix cache\")\n\n\ttokens, err := t.Inventory()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Inventory: %v\", err)\n\t}\n\n\tlog.Infof(\"%v records in the tstore\", len(tokens))\n\n\tfor _, v := range tokens {\n\t\tt.tokenAdd(v)\n\t}\n\n\treturn nil\n}", "func Setup() error {\n\tloadConfig()\n\tlog.Printf(\"Using %s for persistence\\n\", *database)\n\n\tctx, fn := context.WithTimeout(context.Background(), 4*time.Minute)\n\tdefer fn()\n\n\tdbFactory, err := getDBFactory(ctx, factoryConfig{\n\t\tcanRunCreateStmts: true,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcs := newCribbageServer(dbFactory)\n\n\terr = seedNPCs(ctx, dbFactory)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn cs.serve()\n}", "func setup() {\n\t// test server: 1\n\tmux1 = http.NewServeMux()\n\tserver1 = httptest.NewServer(mux1)\n\n\t// test server: 2\n\tmux2 = http.NewServeMux()\n\tserver2 = httptest.NewServer(mux2)\n\n\t// test server: 3\n\tmux3 = http.NewServeMux()\n\tserver3 = httptest.NewServer(mux3)\n\n\tm1, _ := url.Parse(server1.URL)\n\tm2, _ := url.Parse(server2.URL)\n\tm3, _ := url.Parse(server3.URL)\n\tmaster = []*url.URL{m1, m2, m3}\n\n\tclient = NewClient(master, nil)\n}", "func init() {\n\tvar err error\n\tclient, err = sdscontroller.GetClient(\"\", \"\")\n\tif client == nil || err != nil {\n\t\tglog.Errorf(\"client init failed, %s\", err.Error())\n\t\treturn\n\t}\n}", "func InitClient(APIGwURL string, eventService events.Service) {\n\tAPIGwURL = strings.ReplaceAll(APIGwURL, \"https://\", \"\")\n\torganizationServiceClient = &Client{\n\t\tcl: client.NewHTTPClientWithConfig(strfmt.Default, &client.TransportConfig{\n\t\t\tHost: APIGwURL,\n\t\t\tBasePath: \"organization-service\",\n\t\t\tSchemes: []string{\"https\"},\n\t\t}),\n\t}\n\tv1EventService = eventService\n}", "func (gs *GKEClient) Setup(numNodes *int64, nodeType *string, region *string, zone *string, project *string) (ClusterOperations, error) {\n\tvar err error\n\tgc := &GKECluster{\n\t\tRequest: &GKERequest{\n\t\t\tNumNodes: DefaultGKENumNodes,\n\t\t\tNodeType: DefaultGKENodeType,\n\t\t\tRegion: DefaultGKERegion,\n\t\t\tZone: DefaultGKEZone,\n\t\t\tBackupRegions: DefaultGKEBackupRegions},\n\t}\n\n\tctx := context.Background()\n\n\tc, err := google.DefaultClient(ctx, container.CloudPlatformScope)\n\tif nil != err {\n\t\treturn nil, fmt.Errorf(\"failed create google client: '%v'\", err)\n\t}\n\n\tcontainerService, err := container.New(c)\n\tif nil != err {\n\t\treturn nil, fmt.Errorf(\"failed create container service: '%v'\", err)\n\t}\n\tgc.operations = &GKESDKClient{containerService}\n\n\tif nil != project { // use provided project and create cluster\n\t\tgc.Project = project\n\t\tgc.NeedCleanup = true\n\t} else if err := gc.checkEnvironment(); nil != err {\n\t\treturn nil, fmt.Errorf(\"failed checking existing cluster: '%v'\", err)\n\t} else if nil != gc.Cluster { // return if Cluster was already set by kubeconfig\n\t\treturn gc, nil\n\t}\n\tif nil == gc.Cluster {\n\t\tif common.IsProw() {\n\t\t\tproject, err := boskos.AcquireGKEProject(nil)\n\t\t\tif nil != err {\n\t\t\t\treturn nil, fmt.Errorf(\"failed acquire boskos project: '%v'\", err)\n\t\t\t}\n\t\t\tgc.Project = &project.Name\n\t\t}\n\t\tif nil != numNodes {\n\t\t\tgc.Request.NumNodes = *numNodes\n\t\t}\n\t\tif nil != nodeType {\n\t\t\tgc.Request.NodeType = *nodeType\n\t\t}\n\t\tif nil != region {\n\t\t\tgc.Request.Region = *region\n\t\t}\n\t\tif \"\" != common.GetOSEnv(regionEnv) {\n\t\t\tgc.Request.Region = common.GetOSEnv(regionEnv)\n\t\t}\n\t\tif \"\" != common.GetOSEnv(backupRegionEnv) {\n\t\t\tgc.Request.BackupRegions = strings.Split(common.GetOSEnv(backupRegionEnv), \" \")\n\t\t}\n\t\tif nil != zone {\n\t\t\tgc.Request.Zone = *zone\n\t\t\tgc.Request.BackupRegions = make([]string, 0)\n\t\t}\n\t}\n\tif nil == gc.Project || \"\" == *gc.Project {\n\t\treturn nil, fmt.Errorf(\"gcp project must be set\")\n\t}\n\tlog.Printf(\"use project '%s' for running test\", *gc.Project)\n\treturn gc, nil\n}", "func dcSimpleSetup(t *testing.T) (kubeapiservertesting.TearDownFunc, clientset.Interface) {\n\t// Disable ServiceAccount admission plugin as we don't have serviceaccount controller running.\n\tserver := kubeapiservertesting.StartTestServerOrDie(t, nil, []string{\"--disable-admission-plugins=ServiceAccount\"}, framework.SharedEtcd())\n\n\tconfig := restclient.CopyConfig(server.ClientConfig)\n\tclientSet, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\tt.Fatalf(\"error in create clientset: %v\", err)\n\t}\n\treturn server.TearDownFn, clientSet\n}", "func init() {\n\tmart.Register(&client{})\n}", "func InitTestClient() error {\n\terr := cassdcapi.AddToScheme(scheme.Scheme)\n\tif err != nil {\n\t\treturn err\n\t}\n\tconfig, err := ctrl.GetConfig()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot contact Kind test cluster: %w\", err)\n\t}\n\ttestClient, err = client.New(config, client.Options{Scheme: scheme.Scheme})\n\n\treturn err\n}", "func setUpAPIClient() *APIClient {\n\t// Read config\n\terr := getConfig(contivKubeCfgFile, &contivK8Config)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed: %v\", err)\n\t\treturn nil\n\t}\n\n\treturn NewAPIClient(contivK8Config.K8sAPIServer, contivK8Config.K8sCa,\n\t\tcontivK8Config.K8sKey, contivK8Config.K8sCert)\n\n}", "func setup() {\n\tmux = http.NewServeMux()\n\tfakeServer = httptest.NewServer(mux)\n\n\tclient = NewClient(\"testToken123\")\n\turl, _ := url.Parse(fakeServer.URL)\n\tclient.BaseURL = url\n}", "func TestDvLIRClient_Setup(t *testing.T) {\n\tip := viper.GetString(\"IPAddress\")\n\tpw := viper.GetString(\"Password\")\n\n\tdvlirClient, err := NewDvLIRClient(ip, pw)\n\tif !assert.NoError(t, err, \"Error while creating Api client\") {\n\t\treturn\n\t}\n\n\terr = dvlirClient.Login()\n\n\tfile, err := dvlirClient.GetDataFile(10)\n\tif !assert.NoError(t, err, \"Error during GetDataFile request\") {\n\t\treturn\n\t}\n\tif !assert.IsType(t, DataLines{}, file, \"Return value isn't of type DataLines\") {\n\t\treturn\n\t}\n\tif !assert.NotEmpty(t, file, \"Data file is empty\") {\n\t\treturn\n\t}\n\n\tvalue, err := dvlirClient.GetMomentaryValues()\n\tif !assert.NoError(t, err, \"Error during GetMomentaryValues request\") {\n\t\treturn\n\t}\n\tif !assert.IsType(t, MomentaryValues{}, value, \"Return value isn't of type MomentaryValues\") {\n\t\treturn\n\t}\n\tif !assert.NotEmpty(t, value, \"Momentary data is empty\") {\n\t\treturn\n\t}\n\n\tfmt.Println(\"Serial number electric meter: \" + file[1].MeterNumber)\n\tfmt.Println(\"Serial number network adapter: \" + file[1].DvLIRSn)\n\tfmt.Println(\"Meter reading: \" + file[1].OneEightZero)\n\tfmt.Println(\"Adapter status: \" + value.Status)\n\n\tdefer func() {\n\t\terr = dvlirClient.Logout()\n\t\tif !assert.NoError(t, err, \"Error during Logout\") {\n\t\t\treturn\n\t\t}\n\t}()\n}", "func setup() (client *Client, mux *http.ServeMux, serverURL string, teardown func()) {\n\t// mux is the HTTP request multiplexer used with the test server.\n\tmux = http.NewServeMux()\n\n\t// We want to ensure that tests catch mistakes where the endpoint URL is\n\t// specified as absolute rather than relative. It only makes a difference\n\t// when there's a non-empty base URL path. So, use that. See issue #752.\n\tapiHandler := http.NewServeMux()\n\tapiHandler.Handle(baseURLPath+\"/\", http.StripPrefix(baseURLPath, mux))\n\tapiHandler.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tfmt.Fprintln(os.Stderr, \"FAIL: Client.BaseURL path prefix is not preserved in the request URL:\")\n\t\tfmt.Fprintln(os.Stderr)\n\t\tfmt.Fprintln(os.Stderr, \"\\t\"+req.URL.String())\n\t\tfmt.Fprintln(os.Stderr)\n\t\tfmt.Fprintln(os.Stderr, \"\\tDid you accidentally use an absolute endpoint URL rather than relative?\")\n\t\thttp.Error(w, \"Client.BaseURL path prefix is not preserved in the request URL.\", http.StatusInternalServerError)\n\t})\n\n\t// server is a test HTTP server used to provide mock API responses.\n\tserver := httptest.NewServer(apiHandler)\n\n\t// client drives HTTP request to server\n\tclient = NewClient(nil)\n\turl, _ := url.Parse(server.URL + baseURLPath + \"/\")\n\tclient.BaseURL = url\n\tclient.UploadURL = url\n\n\treturn client, mux, server.URL, server.Close\n}", "func setup() (sdk.Context, store.DataStore) {\n\tdb := db.NewMemDB()\n\tms := cosmosStore.NewCommitMultiStore(db)\n\n\tctx := sdk.NewContext(ms, abci.Header{}, false, log.NewNopLogger())\n\n\tdataStoreKey := sdk.NewKVStoreKey(\"data\")\n\n\tms.MountStoreWithDB(dataStoreKey, sdk.StoreTypeIAVL, db)\n\tms.LoadLatestVersion()\n\n\tdataStore := store.NewDataStore(dataStoreKey)\n\treturn ctx, dataStore\n}", "func setupTests() (*clusterHandler, *fakeclient.Client) {\n\txdsC := fakeclient.NewClient()\n\tch := newClusterHandler(&cdsBalancer{xdsClient: xdsC})\n\treturn ch, xdsC\n}", "func ClientInit(conf config.AppConfig, parentDriver *driver.DB, rep *handlers.DBRepo) {\n\t// conf is the application config, from goBlender\n\tapp = conf\n\trepo = rep\n\n\t// If we have additional databases (external to this application) we set the connection here.\n\t// The connection is specified in goBlender preferences.\n\t//conn := app.AlternateConnection\n\n\t// loggers\n\tinfoLog = app.InfoLog\n\terrorLog = app.ErrorLog\n\n\t// In case we need it, we get the database connection from goBlender and save it,\n\tparentDB = parentDriver\n\n\t// We can access handlers from goBlender, but need to initialize them first.\n\tif app.Database == \"postgresql\" {\n\t\thandlers.NewPostgresqlHandlers(parentDB, app.ServerName, app.InProduction, &app)\n\t} else {\n\t\thandlers.NewMysqlHandlers(parentDB, app.ServerName, app.InProduction, &app)\n\t}\n\n\t// Set a different template for home page, if needed.\n\t//repo.SetHomePageTemplate(\"client-sample.page.tmpl\")\n\n\t// Set a different template for inside pages, if needed.\n\t//repo.SetDefaultPageTemplate(\"client-sample.page.tmpl\")\n\n\t// Create client middleware\n\tNewClientMiddleware(app)\n}", "func PtClientSetup(methodNames []string) PtClientInfo {\n\tvar info PtClientInfo\n\n\tver := getManagedTransportVer()\n\tif ver == \"\" {\n\t\tPtVersionError(\"no-version\")\n\t} else {\n\t\tPtLine(\"VERSION\", ver)\n\t}\n\n\tinfo.MethodNames = getClientTransports(methodNames)\n\tif len(info.MethodNames) == 0 {\n\t\tPtCmethodsDone()\n\t\tos.Exit(1)\n\t}\n\n\treturn info\n}", "func (suite *OauthTestSuite) SetupSuite() {\n\n\t// Initialise the config\n\tsuite.cnf = config.NewConfig(false, false)\n\n\t// Create the test database\n\tdb, err := database.CreateTestDatabase(testDbPath, testMigrations, testFixtures)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tsuite.db = db\n\n\t// Fetch test client\n\tsuite.clients = make([]*Client, 0)\n\tif err := suite.db.Order(\"id\").Find(&suite.clients).Error; err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Fetch test users\n\tsuite.users = make([]*User, 0)\n\tif err := suite.db.Order(\"id\").Find(&suite.users).Error; err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// Initialise the service\n\tsuite.service = NewService(suite.cnf, suite.db)\n}", "func (c *CloudsqlController) SetupWithManager(mgr ctrl.Manager) error {\n\tr := &Reconciler{\n\t\tclient: mgr.GetClient(),\n\t\tfactory: &operationsFactory{mgr.GetClient()},\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tNamed(controllerName).\n\t\tFor(&v1alpha1.CloudsqlInstance{}).\n\t\tOwns(&core.Secret{}).\n\t\tComplete(r)\n}", "func (db *RethinkDBAdapter) Setup() *CASServerError {\n\n\t// Setup the Database\n\t_, err := r.\n\t\tDBCreate(db.dbName).\n\t\tRun(db.session)\n\tif err != nil {\n\t\tcasError := &FailedToSetupDatabaseError\n\t\tcasError.err = &err\n\t\treturn casError\n\t}\n\n\t// Setup tables\n\tdb.SetupServicesTable()\n\tdb.SetupTicketsTable()\n\tdb.SetupUsersTable()\n\tdb.SetupApiKeysTable()\n\n\treturn nil\n}", "func init() {\n\tif STORMPATH_API_KEY_ID == \"\" {\n\t\tlog.Fatal(\"STORMPATH_API_KEY_ID not set in the environment.\")\n\t} else if STORMPATH_API_KEY_SECRET == \"\" {\n\t\tlog.Fatal(\"STORMPATH_API_KEY_SECRET not set in the environment.\")\n\t}\n\n\t// Generate a globally unique UUID to be used as a prefix throughout our\n\t// testing.\n\tuuid, err := uuid.NewV4()\n\tif err != nil {\n\t\tlog.Fatal(\"UUID generation failed.\")\n\t}\n\n\t// Store our test prefix.\n\tTEST_PREFIX = uuid.String() + \"-\"\n\n\t// Generate a Stormpath client we'll use for all our tests.\n\tclient, err := NewClient(&ApiKeyPair{\n\t\tId: STORMPATH_API_KEY_ID,\n\t\tSecret: STORMPATH_API_KEY_SECRET,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(\"Couldn't create a Stormpath client.\")\n\t}\n\tCLIENT = client\n}", "func (a *Audit) Setup() {\n\ta.c = client.New()\n\n\ta.setupReporters()\n\n\tif err := a.c.GetProjects(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve project resources: %v\", err)\n\t}\n\n\tif err := a.c.GetIamResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve iam resources: %v\", err)\n\t}\n\n\tif err := a.c.GetComputeResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve compute resources: %v\", err)\n\t}\n\n\tif err := a.c.GetLoggingResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve logging resources: %v\", err)\n\t}\n\n\tif err := a.c.GetNetworkResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve network resources: %v\", err)\n\t}\n\n\tif err := a.c.GetContainerResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve container resources: %v\", err)\n\t}\n\n\tif err := a.c.GetStorageResources(); err != nil {\n\t\tglog.Fatalf(\"Failed to retrieve storage resources: %v\", err)\n\t}\n}", "func (c *Config) setupCartelClient() {\n\tif c.CartelHost == \"\" {\n\t\tac, err := config.New(config.WithRegion(c.Region))\n\t\tif err == nil {\n\t\t\tif host := ac.Service(\"cartel\").Host; host != \"\" {\n\t\t\t\tc.CartelHost = host\n\t\t\t}\n\t\t}\n\t}\n\tclient, err := cartel.NewClient(nil, &cartel.Config{\n\t\tRegion: c.Region,\n\t\tHost: c.CartelHost,\n\t\tToken: c.CartelToken,\n\t\tSecret: c.CartelSecret,\n\t\tNoTLS: c.CartelNoTLS,\n\t\tSkipVerify: c.CartelSkipVerify,\n\t\tDebugLog: c.DebugLog,\n\t})\n\tif err != nil {\n\t\tc.cartelClient = nil\n\t\tc.cartelClientErr = err\n\t\treturn\n\t}\n\tc.cartelClient = client\n}", "func Setup(ESServer, ESIndexPrefix, ESHostname string) {\n\tserverBase = ESServer\n\tindexPrefix = ESIndexPrefix\n\thostMarker = ESHostname\n\tcheckServerPresent()\n}", "func setup() (client *GitHubClient, mux *http.ServeMux, serverURL string, tearDown func()) {\n\t// mux is the HTTP request multiplexer used with the test server.\n\tmux = http.NewServeMux()\n\n\tapiHandler := http.NewServeMux()\n\tapiHandler.Handle(\"/\", mux)\n\n\t// server is a test HTTP server used to provide mock API responses.\n\tserver := httptest.NewServer(apiHandler)\n\n\t// client is the GitHub client being tested and is\n\t// configured to use test server.\n\tclient = NewGitHubClient(testGitHubOwner, testGitHubRepo, testGitHubToken)\n\tu, _ := url.Parse(server.URL + \"/\")\n\tclient.Client.BaseURL = u\n\n\treturn client, mux, server.URL, server.Close\n}", "func datastoreClient(ctx context.Context) (*datastore.Client, error) {\n\tid, err := metadata.ProjectID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn datastore.NewClient(ctx, id)\n}", "func (setup *FabricSetup) Initialize() error {\r\n\r\n\t// Add parameters for the initialization\r\n\tif setup.initialized {\r\n\t\treturn errors.New(\"sdk already initialized\")\r\n\t}\r\n\r\n\t// Initialize the SDK with the configuration file\r\n\tsdk, err := fabsdk.New(config.FromFile(setup.ConfigFile))\r\n\tif err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to create SDK\")\r\n\t}\r\n\tsetup.sdk = sdk\r\n\tfmt.Println(\"Step 1: SDK created\")\r\n\r\n\t// The resource management client is responsible for managing channels (create/update channel)\r\n\tresourceManagerClientContext := setup.sdk.Context(fabsdk.WithUser(setup.OrgAdmin), fabsdk.WithOrg(setup.OrgName))\r\n\tif err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to load Admin identity\")\r\n\t}\r\n\tfmt.Println(\"\\n Step 2.a: Value of resourceManagerClientContext is: \", resourceManagerClientContext)\r\n\tresMgmtClient, err := resmgmt.New(resourceManagerClientContext)\r\n\tif err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to create channel management client from Admin identity\")\r\n\t}\r\n\tfmt.Println(\"\\n Step 2.b: Value of resMgmtClient is: \", resMgmtClient)\r\n\tsetup.admin = resMgmtClient\r\n\tfmt.Println(\"\\n Step 2 completed: Resource management client created\")\r\n\r\n\t// The MSP client allow us to retrieve user information from their identity, like its signing identity which we will need to save the channel\r\n\tmspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg(setup.OrgName))\r\n\tif err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to create MSP client\")\r\n\t}\r\n\tfmt.Println(\"\\n Step 3: Value of mspClient is: \", mspClient)\r\n\r\n\tadminIdentity, err := mspClient.GetSigningIdentity(setup.OrgAdmin)\r\n\tif err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to get admin signing identity\")\r\n\t}\r\n\tPrintln(\"\\n Step 4: Value of adminIdentity is: \", adminIdentity)\r\n\r\n\treq := resmgmt.SaveChannelRequest{ChannelID: setup.ChannelID, ChannelConfigPath: setup.ChannelConfig, SigningIdentities: []msp.SigningIdentity{adminIdentity}}\r\n\tfmt.Println(\"\\n Step 5: value of req is: \", req)\r\n\tfmt.Println(\"Step 5.a: Value of setup.Orderer is: \", setup.OrdererID)\r\n\r\n\ttxID, err := setup.admin.SaveChannel(req, resmgmt.WithOrdererEndpoint(setup.OrdererID))\r\n\tif err != nil || txID.TransactionID == \"\" {\r\n\t\treturn errors.WithMessage(err, \"failed to save channel\")\r\n\t}\r\n\tfmt.Println(\"Channel created\")\r\n\r\n\t// Make admin user join the previously created channel\r\n\tif err = setup.admin.JoinChannel(setup.ChannelID, resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(setup.OrdererID)); err != nil {\r\n\t\treturn errors.WithMessage(err, \"failed to make admin join channel\")\r\n\t}\r\n\tfmt.Println(\"Channel joined\")\r\n\r\n\tfmt.Println(\"Initialization Successful\")\r\n\tsetup.initialized = true\r\n\treturn nil\r\n}", "func setupAndRun(t *testing.T, createChannel bool, configOpt core.ConfigProvider, test testSDKFunc, sdkOpts ...fabsdk.Option) {\n\n\tif integration.IsLocal() {\n\t\t//If it is a local test then add entity mapping to config backend to parse URLs\n\t\tconfigOpt = integration.AddLocalEntityMapping(configOpt)\n\t}\n\n\tsdk, err := fabsdk.New(configOpt, sdkOpts...)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create new SDK: %s\", err)\n\t}\n\tdefer sdk.Close()\n\n\t// Delete all private keys from the crypto suite store\n\t// and users from the user store at the end\n\tintegration.CleanupUserData(t, sdk)\n\tdefer integration.CleanupUserData(t, sdk)\n\n\tif createChannel {\n\t\tcreateChannelAndCC(t, sdk)\n\t}\n\n\ttest(t, sdk)\n}", "func (s *backendSuite) setUpTest(c *C) {\n\ts.controller = gomock.NewController(c)\n\ts.mockBackend = mock.NewMockBackend(s.controller)\n\ts.backend = kv.MakeBackend(s.mockBackend)\n}", "func (setup *FabricSetup) Initialize() error {\n\n\tsetup.client = make([]*channel.Client, len(setup.ChannelID))\n\tsetup.ledger = make([]*ledger.Client, len(setup.ChannelID))\n\tsetup.admin = make([]*resmgmt.Client, len(setup.ChannelID))\n\tsetup.event = make([]*event.Client, len(setup.ChannelID))\n\t// Add parameters for the initialization\n\tif setup.initialized {\n\t\treturn errors.New(\"sdk already initialized\")\n\t}\n\n\t// Initialize the SDK with the configuration file\n\tsdk, err := fabsdk.New(config.FromFile(setup.ConfigFile))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to create SDK\")\n\t}\n\tsetup.sdk = sdk\n\tfmt.Println(\"SDK created\")\n\n\t// The resource management client is responsible for managing channels (create/update channel)\n\tresourceManagerClientContext := setup.sdk.Context(fabsdk.WithUser(setup.OrgAdmin), fabsdk.WithOrg(setup.OrgName))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to load Admin identity\")\n\t}\n\tresMgmtClient, err := resmgmt.New(resourceManagerClientContext)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to create channel management client from Admin identity\")\n\t}\n\tfmt.Println(\"Ressource management client created\")\n\n\t// The MSP client allow us to retrieve user information from their identity, like its signing identity which we will need to save the channel\n\tmspClient, err := mspclient.New(sdk.Context(), mspclient.WithOrg(setup.OrgName))\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to create MSP client\")\n\t}\n\tadminIdentity, err := mspClient.GetSigningIdentity(setup.OrgAdmin)\n\tif err != nil {\n\t\treturn errors.WithMessage(err, \"failed to get admin signing identity\")\n\t}\n\n\t//循环创建通道 加入通道\n\tfor i, _ := range setup.ChannelID {\n\t\tsetup.admin[i] = resMgmtClient\n\t\treq := resmgmt.SaveChannelRequest{ChannelID: setup.ChannelID[i], ChannelConfigPath: setup.ChannelConfig[i], SigningIdentities: []msp.SigningIdentity{adminIdentity}}\n\t\ttxID, err := setup.admin[i].SaveChannel(req, resmgmt.WithOrdererEndpoint(setup.OrdererID))\n\t\tif err != nil || txID.TransactionID == \"\" {\n\t\t\treturn errors.WithMessage(err, \"failed to save channel\")\n\t\t}\n\t\t//Make admin user join the previously created channel\n\t\tif err = setup.admin[i].JoinChannel(setup.ChannelID[i], resmgmt.WithRetry(retry.DefaultResMgmtOpts), resmgmt.WithOrdererEndpoint(setup.OrdererID)); err != nil {\n\t\t\treturn errors.WithMessage(err, \"failed to make admin join channel\")\n\t\t}\n\t\tfmt.Println(setup.ChannelID[i])\n\t\tfmt.Println(\"Channel created\")\n\t\tfmt.Println(\"Channel joined\")\n\t}\n\n\tfmt.Println(\"Initialization Successful\")\n\tsetup.initialized = true\n\treturn nil\n}", "func init() {\n\tdefaultClient = New(\"\")\n}", "func setup(client Fetcher) {\n\tw = httptest.NewRecorder()\n\thandler = TweetsHandler(client)\n\treq, _ := http.NewRequest(\"GET\", \"/\", nil)\n\thandler.ServeHTTP(w, req)\n}", "func TestInitAndGetWithCorruptDatastore(t *testing.T) {\n\tuserlib.SetDebugStatus(false)\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore := userlib.DatastoreGetMap()\n\tkeystore := userlib.KeystoreGetMap()\n\t_, _ = datastore, keystore\n\n\t_, err := InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys []userlib.UUID\n\tvar vals [][]byte\n\tfor k, v := range datastore {\n\t\tkeys = append(keys, k)\n\t\tvals = append(vals, v)\n\t}\n\tuserlib.DatastoreSet(keys[0], vals[1])\n\tfor i := 1; i < len(keys); i++ {\n\t\tuserlib.DatastoreSet(keys[i], vals[0])\n\t}\n\n\t_, err = GetUser(\"alice\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for alice but still got user.\")\n\t\treturn\n\t}\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was corrupted for bob but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\tuserlib.DatastoreClear()\n\t_, err = GetUser(\"bob\", \"fubar\")\n\tif err == nil {\n\t\tt.Error(\"Datastore was empty but still got user.\")\n\t\treturn\n\t}\n\n\tuserlib.DatastoreClear()\n\tuserlib.KeystoreClear()\n\tdatastore = userlib.DatastoreGetMap()\n\n\t_, err = InitUser(\"bob\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\t_, err = InitUser(\"alice\", \"fubar\")\n\tif err != nil {\n\t\tt.Error(err)\n\t\treturn\n\t}\n\n\tvar keys1 []userlib.UUID\n\tvar vals1 [][]byte\n\tfor k, v := range datastore {\n\t\tkeys1 = append(keys1, k)\n\t\tvals1 = append(vals1, v)\n\t}\n\tdatastore[keys1[0]] = userlib.RandomBytes(len(keys1[0]))\n\n\t_, err0 := GetUser(\"bob\", \"fubar\")\n\t_, err1 := GetUser(\"alice\", \"fubar\")\n\tif err0 == nil && err1 == nil {\n\t\tt.Error(\"successfully got all users when datastore was corrupted.\")\n\t}\n}", "func BuildClientset() {\n\tonce.Do(func() {\n\t\tif err := setupKubeClientset(); err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t})\n}", "func (suite *KeeperTestSuite) SetupTest() {\n\ttApp := app.NewTestApp()\n\n\tctx := tApp.NewContext(true, tmprototypes.Header{Height: 1, Time: tmtime.Now()})\n\ttApp.InitializeFromGenesisStates()\n\t_, addrs := app.GeneratePrivKeyAddressPairs(5)\n\tvar strAddrs []string\n\tfor _, addr := range addrs {\n\t\tacc := tApp.GetAccountKeeper().NewAccountWithAddress(ctx, addr)\n\t\ttApp.GetAccountKeeper().SetAccount(ctx, acc)\n\t\tstrAddrs = append(strAddrs, addr.String())\n\t}\n\n\tkeeper := tApp.GetIssuanceKeeper()\n\tmodAccount, err := sdk.AccAddressFromBech32(\"kava1cj7njkw2g9fqx4e768zc75dp9sks8u9znxrf0w\")\n\tsuite.Require().NoError(err)\n\n\tsuite.tApp = tApp\n\tsuite.ctx = ctx\n\tsuite.keeper = keeper\n\tsuite.addrs = strAddrs\n\tsuite.modAccount = modAccount\n}", "func (s *Store) Init(ctx context.Context, metadataRaw secretstores.Metadata) error {\n\tmetadata, err := s.parseSecretManagerMetadata(metadataRaw)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tclient, err := s.getClient(ctx, metadata)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to setup secretmanager client: %s\", err)\n\t}\n\n\ts.client = client\n\ts.ProjectID = metadata.ProjectID\n\n\treturn nil\n}", "func Setup(mgr ctrl.Manager, args controller.Args, _ logging.Logger) error {\n\treconciler := Reconciler{\n\t\tClient: mgr.GetClient(),\n\t\tdm: args.DiscoveryMapper,\n\t\tScheme: mgr.GetScheme(),\n\t}\n\treturn reconciler.SetupWithManager(mgr)\n}", "func (suite *ServiceTestSuite) SetupTest() {\n\tsuite.mockCtrl = gomock.NewController(suite.T())\n\tsuite.resmgrClient = resource_mocks.NewMockResourceManagerServiceYARPCClient(suite.mockCtrl)\n\tsuite.hostMgrClient = host_mocks.NewMockInternalHostServiceYARPCClient(suite.mockCtrl)\n\tsuite.metrics = metrics.NewMetrics(tally.NoopScope)\n\tsuite.hostService = NewService(suite.hostMgrClient, suite.resmgrClient, suite.metrics)\n}" ]
[ "0.7327495", "0.6999887", "0.69618183", "0.6907028", "0.67116094", "0.66912305", "0.65061927", "0.6484708", "0.64401776", "0.64209616", "0.63864416", "0.6375688", "0.6373344", "0.6360606", "0.63027203", "0.6278499", "0.6260439", "0.62370163", "0.6213235", "0.619793", "0.619535", "0.61792237", "0.6156875", "0.61565095", "0.6148874", "0.61351997", "0.61230826", "0.611051", "0.61099446", "0.61097586", "0.60909957", "0.60590786", "0.6039296", "0.60195875", "0.5991225", "0.5982303", "0.5971908", "0.59581774", "0.59566724", "0.595489", "0.59526414", "0.5939014", "0.5937391", "0.5935752", "0.5908745", "0.5896668", "0.5893933", "0.5891978", "0.58818746", "0.588164", "0.5851392", "0.5848917", "0.58477753", "0.58430046", "0.58421725", "0.58400005", "0.5837989", "0.58190024", "0.58151984", "0.5807731", "0.5804204", "0.5802681", "0.57756174", "0.5742847", "0.5740404", "0.5726366", "0.5724846", "0.57241696", "0.5717136", "0.57150316", "0.57080144", "0.5707563", "0.5706602", "0.57057256", "0.5700688", "0.56939596", "0.56849945", "0.56788605", "0.56777734", "0.5665925", "0.5663876", "0.56520516", "0.5651839", "0.56500334", "0.5648028", "0.56247264", "0.5624348", "0.5623452", "0.56125396", "0.5610322", "0.56091475", "0.5607805", "0.5604624", "0.55945164", "0.5592273", "0.55858487", "0.5585144", "0.5578532", "0.5578213", "0.55742794" ]
0.7386597
0
MergeValuesCustomIdentifiers merges the metric values and custom identifiers
func MergeValuesCustomIdentifiers(values []*ValuesCustomIdentifier, newValue *ValuesCustomIdentifier) []*ValuesCustomIdentifier { for _, value := range values { if value.CustomIdentifier == newValue.CustomIdentifier || (value.CustomIdentifier != nil && newValue.CustomIdentifier != nil && *value.CustomIdentifier == *newValue.CustomIdentifier) { value.Values = merge(value.Values, newValue.Values) return values } } return append(values, newValue) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *CirconusMetrics) Custom(metricName string, metric Metric) error {\n\tif !metricTypeRx.MatchString(metric.Type) {\n\t\treturn fmt.Errorf(\"unrecognized circonus metric type (%s)\", metric.Type)\n\t}\n\n\tm.custm.Lock()\n\tm.custom[metricName] = metric\n\tm.custm.Unlock()\n\n\treturn nil\n}", "func (o LookupProvisioningConfigResultOutput) CustomId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupProvisioningConfigResult) string { return v.CustomId }).(pulumi.StringOutput)\n}", "func WithCustomDimensions(dimensions string) ConversionOps {\r\n\treturn func(c *conversionOptions) {\r\n\t\tc.customDimensions = dimensions\r\n\t}\r\n}", "func (e *storageExecutor) mergeGroupByTagValueIDs(tagValueIDs []*roaring.Bitmap) {\n\tif tagValueIDs == nil {\n\t\treturn\n\t}\n\te.mutex.Lock()\n\tdefer e.mutex.Unlock()\n\n\tfor idx, tagVIDs := range e.tagValueIDs {\n\t\tif tagVIDs == nil {\n\t\t\te.tagValueIDs[idx] = tagValueIDs[idx]\n\t\t} else {\n\t\t\ttagVIDs.Or(tagValueIDs[idx])\n\t\t}\n\t}\n}", "func Merge(metrics map[string]metricSource.MetricData, other map[string]metricSource.MetricData) map[string]metricSource.MetricData {\n\tresult := make(map[string]metricSource.MetricData, len(metrics)+len(other))\n\tfor k, v := range metrics {\n\t\tresult[k] = v\n\t}\n\tfor k, v := range other {\n\t\tresult[k] = v\n\t}\n\treturn result\n}", "func (o AutoscalingPolicyOutput) CustomMetricUtilizations() AutoscalingPolicyCustomMetricUtilizationArrayOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicy) []AutoscalingPolicyCustomMetricUtilization {\n\t\treturn v.CustomMetricUtilizations\n\t}).(AutoscalingPolicyCustomMetricUtilizationArrayOutput)\n}", "func (o AutoscalingPolicyResponseOutput) CustomMetricUtilizations() AutoscalingPolicyCustomMetricUtilizationResponseArrayOutput {\n\treturn o.ApplyT(func(v AutoscalingPolicyResponse) []AutoscalingPolicyCustomMetricUtilizationResponse {\n\t\treturn v.CustomMetricUtilizations\n\t}).(AutoscalingPolicyCustomMetricUtilizationResponseArrayOutput)\n}", "func (s BatchGetCustomDataIdentifierSummary) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Deleted != nil {\n\t\tv := *s.Deleted\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"deleted\", protocol.BoolValue(v), metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (o RegistryTaskRegistryCredentialOutput) Customs() RegistryTaskRegistryCredentialCustomArrayOutput {\n\treturn o.ApplyT(func(v RegistryTaskRegistryCredential) []RegistryTaskRegistryCredentialCustom { return v.Customs }).(RegistryTaskRegistryCredentialCustomArrayOutput)\n}", "func (o PhpAppLayerOutput) CustomSecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *PhpAppLayer) pulumi.StringArrayOutput { return v.CustomSecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func (o AutoscalingPolicyPtrOutput) CustomMetricUtilizations() AutoscalingPolicyCustomMetricUtilizationArrayOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicy) []AutoscalingPolicyCustomMetricUtilization {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CustomMetricUtilizations\n\t}).(AutoscalingPolicyCustomMetricUtilizationArrayOutput)\n}", "func (s CustomDataIdentifierSummary) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Arn != nil {\n\t\tv := *s.Arn\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"arn\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.CreatedAt != nil {\n\t\tv := *s.CreatedAt\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"createdAt\",\n\t\t\tprotocol.TimeValue{V: v, Format: \"iso8601\", QuotedFormatTime: true}, metadata)\n\t}\n\tif s.Description != nil {\n\t\tv := *s.Description\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"description\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Id != nil {\n\t\tv := *s.Id\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"id\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\tif s.Name != nil {\n\t\tv := *s.Name\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"name\", protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v)}, metadata)\n\t}\n\treturn nil\n}", "func (agent *Agent) AddCustomMetric(metric newrelic_platform_go.IMetrica) {\n\tagent.CustomMetrics = append(agent.CustomMetrics, metric)\n}", "func (s) TestCustomTagsTracingMetrics(t *testing.T) {\n\tdefer func(ne func(config *config) (tracingMetricsExporter, error)) {\n\t\tnewExporter = ne\n\t}(newExporter)\n\tfe := &fakeOpenCensusExporter{SeenViews: make(map[string]string), t: t}\n\tnewExporter = func(config *config) (tracingMetricsExporter, error) {\n\t\tct := config.Labels\n\t\tif len(ct) < 1 {\n\t\t\tt.Fatalf(\"less than 2 custom tags sent in\")\n\t\t}\n\t\tif val, ok := ct[\"customtag1\"]; !ok || val != \"wow\" {\n\t\t\tt.Fatalf(\"incorrect custom tag: got %v, want %v\", val, \"wow\")\n\t\t}\n\t\tif val, ok := ct[\"customtag2\"]; !ok || val != \"nice\" {\n\t\t\tt.Fatalf(\"incorrect custom tag: got %v, want %v\", val, \"nice\")\n\t\t}\n\t\treturn fe, nil\n\t}\n\n\t// This configuration present in file system and it's defined custom tags should make it\n\t// to the created exporter.\n\tconfigJSON := `{\n\t\t\"project_id\": \"fake\",\n\t\t\"cloud_trace\": {},\n\t\t\"cloud_monitoring\": {\"sampling_rate\": 1.0},\n\t\t\"labels\":{\"customtag1\":\"wow\",\"customtag2\":\"nice\"}\n\t}`\n\n\tcleanup, err := createTmpConfigInFileSystem(configJSON)\n\tdefer cleanup()\n\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\terr = Start(ctx)\n\tdefer End()\n\tif err != nil {\n\t\tt.Fatalf(\"Start() failed with err: %v\", err)\n\t}\n}", "func (o *EnvironmentUsageDto) SetCustomMetrics(v []CustomMetricDto) {\n\to.CustomMetrics = &v\n}", "func (o AutoscalingPolicyResponsePtrOutput) CustomMetricUtilizations() AutoscalingPolicyCustomMetricUtilizationResponseArrayOutput {\n\treturn o.ApplyT(func(v *AutoscalingPolicyResponse) []AutoscalingPolicyCustomMetricUtilizationResponse {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CustomMetricUtilizations\n\t}).(AutoscalingPolicyCustomMetricUtilizationResponseArrayOutput)\n}", "func (o LogConfigCounterOptionsOutput) CustomFields() LogConfigCounterOptionsCustomFieldArrayOutput {\n\treturn o.ApplyT(func(v LogConfigCounterOptions) []LogConfigCounterOptionsCustomField { return v.CustomFields }).(LogConfigCounterOptionsCustomFieldArrayOutput)\n}", "func customMetric(name string) string {\n\treturn fmt.Sprintf(\"custom.googleapis.com/%s\", DotSlashes(name))\n}", "func (r *AggregateMetadata) Merge(other AggregateMetadata) {\n\tfor k, v := range other {\n\t\t(*r)[k] += v\n\t}\n}", "func (p CognitoIdpPlugin) FetchMetrics() (map[string]interface{}, error) {\n\tstat := make(map[string]interface{})\n\n\tfor _, met := range [...]metrics{\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignUpSuccesses\", MackerelName: \"SignUpSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignUpThrottles\", MackerelName: \"SignUpThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"SignInSuccesses\", MackerelName: \"SignInSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"SignInThrottles\", MackerelName: \"SignInThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"TokenRefreshSuccesses\", MackerelName: \"TokenRefreshSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"TokenRefreshThrottles\", MackerelName: \"TokenRefreshThrottles\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSuccesses\", Type: metricsTypeSum},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationParcentageOfSuccessful\", Type: metricsTypeAverage},\n\t\t{CloudWatchName: \"FederationSuccesses\", MackerelName: \"FederationSampleCount\", Type: metricsTypeSampleCount},\n\t\t{CloudWatchName: \"FederationThrottles\", MackerelName: \"FederationThrottles\", Type: metricsTypeSum},\n\t} {\n\t\tv, err := p.getLastPoint(met)\n\t\tif err == nil {\n\t\t\tstat[met.MackerelName] = v\n\t\t} else {\n\t\t\tlog.Printf(\"%s: %s\", met, err)\n\t\t}\n\t}\n\treturn stat, nil\n}", "func (kvs KeyValues) Merge(other KeyValues) KeyValues {\n\tif len(other) == 0 {\n\t\treturn kvs.Clone()\n\t}\n\tm := kvs.Map()\n\tfor _, item := range other {\n\t\tm[item.Key] = item.Value\n\t}\n\tmerged := make(KeyValues, len(m))\n\tidx := 0\n\tfor key, value := range m {\n\t\tmerged[idx] = &protoMetricsV1.KeyValue{\n\t\t\tKey: key,\n\t\t\tValue: value,\n\t\t}\n\t\tidx++\n\t}\n\tsort.Sort(merged)\n\treturn merged\n}", "func (lv LabelValues) Merge(additionalLV LabelValues) {\n\tfor label, origin := range additionalLV {\n\t\tif origin == nil {\n\t\t\tcontinue\n\t\t}\n\t\tcopy := make(map[string]uint32)\n\t\tfor value, count := range origin {\n\t\t\tcopy[value] = count\n\t\t}\n\t\tif _, ok := lv[label]; !ok {\n\t\t\tlv[label] = copy\n\t\t\tcontinue\n\t\t}\n\t\tfor v, c := range copy {\n\t\t\tif current, ok := lv[label][v]; !ok {\n\t\t\t\tlv[label][v] = c\n\t\t\t} else {\n\t\t\t\tlv[label][v] = current + c\n\t\t\t}\n\t\t}\n\t}\n}", "func (o LogConfigCounterOptionsResponseOutput) CustomFields() LogConfigCounterOptionsCustomFieldResponseArrayOutput {\n\treturn o.ApplyT(func(v LogConfigCounterOptionsResponse) []LogConfigCounterOptionsCustomFieldResponse {\n\t\treturn v.CustomFields\n\t}).(LogConfigCounterOptionsCustomFieldResponseArrayOutput)\n}", "func (s CustomDataIdentifiers) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Detections != nil {\n\t\tv := s.Detections\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"detections\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddFields(v1)\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.TotalCount != nil {\n\t\tv := *s.TotalCount\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"totalCount\", protocol.Int64Value(v), metadata)\n\t}\n\treturn nil\n}", "func (suite *TestCompountReportSuite) TestMarshalJSONOnDynamicMetrics(c *C) {\n\ttestCases := []*struct {\n\t\tcolumns []string\n\t\texpectedResult string\n\t}{\n\t\t{ // Everything\n\t\t\t[]string{MetricMax, MetricMin, MetricAvg, MetricMed, MetricMdev, MetricLoss, MetricCount, MetricPckSent, MetricPckReceived, MetricNumAgent, MetricNumTarget},\n\t\t\t`\n\t\t\t{\n\t\t\t\t\"max\": 78,\n\t\t\t\t\"min\": 21,\n\t\t\t\t\"avg\": 45.67,\n\t\t\t\t\"med\": 32,\n\t\t\t\t\"mdev\": 5.81,\n\t\t\t\t\"loss\": 0.04,\n\t\t\t\t\"count\": 100,\n\t\t\t\t\"pck_sent\": 2300,\n\t\t\t\t\"pck_received\": 2045,\n\t\t\t\t\"num_agent\": 10,\n\t\t\t\t\"num_target\": 15\n\t\t\t}\n\t\t\t`,\n\t\t},\n\t\t{ // Nothing\n\t\t\t[]string{},\n\t\t\t\"{}\",\n\t\t},\n\t}\n\n\tsampleMetrics := &DynamicMetrics{\n\t\tMetrics: &Metrics{\n\t\t\tMax: 78, Min: 21, Avg: 45.67, Med: 32, Mdev: 5.81, Loss: 0.04,\n\t\t\tCount: 100, NumberOfSentPackets: 2300, NumberOfReceivedPackets: 2045, NumberOfAgents: 10, NumberOfTargets: 15,\n\t\t},\n\t}\n\tfor i, testCase := range testCases {\n\t\tcomment := Commentf(\"Test Case: %d\", i+1)\n\n\t\tsampleMetrics.Output = &testCase.columns\n\n\t\tc.Logf(\"Result JSON: %s\", ojson.MarshalJSON(sampleMetrics))\n\t\tc.Assert(sampleMetrics, ocheck.JsonEquals, ojson.RawJsonForm(testCase.expectedResult), comment)\n\t}\n}", "func (o RegistryTaskRegistryCredentialPtrOutput) Customs() RegistryTaskRegistryCredentialCustomArrayOutput {\n\treturn o.ApplyT(func(v *RegistryTaskRegistryCredential) []RegistryTaskRegistryCredentialCustom {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Customs\n\t}).(RegistryTaskRegistryCredentialCustomArrayOutput)\n}", "func IntersectionCustomsCounter(input string) customsCounter {\n\treturn customsCounter{groups: parseIntersections(input)}\n}", "func BuildProcessorCustomMetricName(configType, metric string) string {\n\tcomponentPrefix := obsmetrics.ProcessorPrefix\n\tif !strings.HasSuffix(componentPrefix, obsmetrics.NameSep) {\n\t\tcomponentPrefix += obsmetrics.NameSep\n\t}\n\tif configType == \"\" {\n\t\treturn componentPrefix\n\t}\n\treturn componentPrefix + configType + obsmetrics.NameSep + metric\n}", "func MergeValues(a, b *Values) {\n\tif a.Imports == nil {\n\t\ta.Imports = b.Imports\n\t\treturn\n\t}\n\tfor key, val := range b.Imports {\n\t\ta.Imports[key] = val\n\t}\n}", "func (o CustomLayerOutput) CustomSecurityGroupIds() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringArrayOutput { return v.CustomSecurityGroupIds }).(pulumi.StringArrayOutput)\n}", "func AnalyticsIntentMetricName_Values() []string {\n\treturn []string{\n\t\tAnalyticsIntentMetricNameCount,\n\t\tAnalyticsIntentMetricNameSuccess,\n\t\tAnalyticsIntentMetricNameFailure,\n\t\tAnalyticsIntentMetricNameSwitched,\n\t\tAnalyticsIntentMetricNameDropped,\n\t}\n}", "func convertScriptedMetrics(data map[string]string, prom chan<- prometheus.Metric) {\n\tfor k := range data {\n\t\t// k = \"script.custom_total\"\n\t\tif strings.HasPrefix(k, \"script.\") {\n\t\t\t// metricName = \"custom_total\"\n\t\t\tmetricName := strings.TrimPrefix(k, \"script.\")\n\t\t\tmetricName = strings.ToLower(metricName)\n\t\t\tvar valueType prometheus.ValueType\n\t\t\t// deduce the metrics value type by following https://prometheus.io/docs/practices/naming/\n\t\t\tif strings.HasSuffix(k, \"_total\") || strings.HasSuffix(k, \"_seconds\") || strings.HasSuffix(k, \"_bytes\") {\n\t\t\t\tvalueType = prometheus.CounterValue\n\t\t\t} else {\n\t\t\t\tvalueType = prometheus.GaugeValue\n\t\t\t}\n\t\t\t// create a metric description on the fly\n\t\t\tdescription := prometheus.NewDesc(\"kamailio_\"+metricName, \"Scripted metric \"+metricName, []string{}, nil)\n\t\t\t// and produce a metric\n\t\t\tconvertStatToMetric(data, k, \"\", description, prom, valueType)\n\t\t}\n\t}\n}", "func marshalValues(v metric.Values, dest []byte) []byte {\n\tsz := formatVersionSize + len(v)*sampleSize\n\tif cap(dest) < sz {\n\t\tdest = make([]byte, sz)\n\t} else {\n\t\tdest = dest[0:sz]\n\t}\n\n\tdest[0] = formatVersion\n\tfor i, val := range v {\n\t\toffset := formatVersionSize + i*sampleSize\n\t\tbinary.LittleEndian.PutUint64(dest[offset:], uint64(val.Timestamp.Unix()))\n\t\tbinary.LittleEndian.PutUint64(dest[offset+8:], math.Float64bits(float64(val.Value)))\n\t}\n\treturn dest\n}", "func (c *controller) getCustomTemplateValues(\n\tctx context.Context, project, domain string, domainTemplateValues templateValuesType) (templateValuesType, error) {\n\tif len(domainTemplateValues) == 0 {\n\t\tdomainTemplateValues = make(templateValuesType)\n\t}\n\tcustomTemplateValues := make(templateValuesType)\n\tfor key, value := range domainTemplateValues {\n\t\tcustomTemplateValues[key] = value\n\t}\n\tcollectedErrs := make([]error, 0)\n\t// All override values saved in the database take precedence over the domain-specific defaults.\n\tresource, err := c.resourceManager.GetResource(ctx, managerinterfaces.ResourceRequest{\n\t\tProject: project,\n\t\tDomain: domain,\n\t\tResourceType: admin.MatchableResource_CLUSTER_RESOURCE,\n\t})\n\tif err != nil {\n\t\tif _, ok := err.(errors.FlyteAdminError); !ok || err.(errors.FlyteAdminError).Code() != codes.NotFound {\n\t\t\tcollectedErrs = append(collectedErrs, err)\n\t\t}\n\t}\n\tif resource != nil && resource.Attributes != nil && resource.Attributes.GetClusterResourceAttributes() != nil {\n\t\tfor templateKey, templateValue := range resource.Attributes.GetClusterResourceAttributes().Attributes {\n\t\t\tcustomTemplateValues[fmt.Sprintf(templateVariableFormat, templateKey)] = templateValue\n\t\t}\n\t}\n\tif len(collectedErrs) > 0 {\n\t\treturn nil, errors.NewCollectedFlyteAdminError(codes.InvalidArgument, collectedErrs)\n\t}\n\treturn customTemplateValues, nil\n}", "func (o IndexingConfigurationThingGroupIndexingConfigurationOutput) CustomFields() IndexingConfigurationThingGroupIndexingConfigurationCustomFieldArrayOutput {\n\treturn o.ApplyT(func(v IndexingConfigurationThingGroupIndexingConfiguration) []IndexingConfigurationThingGroupIndexingConfigurationCustomField {\n\t\treturn v.CustomFields\n\t}).(IndexingConfigurationThingGroupIndexingConfigurationCustomFieldArrayOutput)\n}", "func (ids UserIdentifiers) CombinedIdentifiers() *CombinedIdentifiers {\n\treturn ids.EntityIdentifiers().CombinedIdentifiers()\n}", "func (o LogConfigCounterOptionsPtrOutput) CustomFields() LogConfigCounterOptionsCustomFieldArrayOutput {\n\treturn o.ApplyT(func(v *LogConfigCounterOptions) []LogConfigCounterOptionsCustomField {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CustomFields\n\t}).(LogConfigCounterOptionsCustomFieldArrayOutput)\n}", "func (ao *AggregateOptions) SetCustom(c bson.M) *AggregateOptions {\n\tao.Custom = c\n\treturn ao\n}", "func (c *Aggregator) Merge(oa export.Aggregator, desc *metric.Descriptor) error {\n\to, _ := oa.(*Aggregator)\n\tif o == nil {\n\t\treturn aggregator.NewInconsistentAggregatorError(c, oa)\n\t}\n\tc.value.AddNumber(desc.NumberKind(), o.value)\n\treturn nil\n}", "func (v *Values) MergeAll(ctx context.Context, app v1alpha1.App, catalog v1alpha1.Catalog) (map[string]interface{}, error) {\n\tconfigMapData, err := v.MergeConfigMapData(ctx, app, catalog)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\tsecretData, err := v.MergeSecretData(ctx, app, catalog)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\terr = mergo.Merge(&configMapData, secretData, mergo.WithOverride)\n\tif err != nil {\n\t\treturn nil, microerror.Mask(err)\n\t}\n\n\treturn configMapData, nil\n}", "func mergeValues(u1, u2 url.Values) url.Values {\n\tif u1 == nil {\n\t\treturn u2\n\t}\n\tif u2 == nil {\n\t\treturn u1\n\t}\n\tfor k, v := range u2 {\n\t\tu1[k] = append(u1[k], v...)\n\t}\n\treturn u1\n}", "func (o AppMonitorOutput) CustomEvents() AppMonitorCustomEventsOutput {\n\treturn o.ApplyT(func(v *AppMonitor) AppMonitorCustomEventsOutput { return v.CustomEvents }).(AppMonitorCustomEventsOutput)\n}", "func MetaMerge(a, b map[string]interface{}) map[string]interface{} {\n\tfor k, v := range b {\n\t\t// don't over-write\n\t\tif _, ok := a[k]; !ok {\n\t\t\ta[k] = v\n\t\t}\n\t}\n\treturn a\n}", "func (m *mergeQuerier) LabelValues(name string, matchers ...*labels.Matcher) ([]string, storage.Warnings, error) {\n\tif name == defaultTenantLabel {\n\t\treturn m.tenantIDs, nil, nil\n\t}\n\n\t// ensure the name of a retained tenant id label gets handled under the\n\t// original label name\n\tif name == originalDefaultTenantLabel {\n\t\tname = defaultTenantLabel\n\t}\n\n\treturn m.mergeDistinctStringSlice(func(ctx context.Context, q storage.Querier) ([]string, storage.Warnings, error) {\n\t\treturn q.LabelValues(name, matchers...)\n\t})\n}", "func CreateDynamicPrometheusMetric(name string, workflowStatus *wfv1.WorkflowStatus, registry *prometheus.Registry) {\n\tif workflowStatus.Outputs == nil || workflowStatus.Outputs.Parameters == nil {\n\t\treturn\n\t}\n\n\tfor _, parameter := range workflowStatus.Outputs.Parameters {\n\t\tvar jsonMap map[string][]interface{}\n\t\tjson.Unmarshal([]byte(*parameter.Value), &jsonMap)\n\n\t\tfor _, customMetricRaw := range jsonMap[\"metrics\"] {\n\t\t\tvar metric customMetricMap\n\t\t\tif err := mapstructure.Decode(customMetricRaw.(map[string]interface{}), &metric); err != nil {\n\t\t\t\tlog.Errorf(\"Failed to decode metric for %s: %s\", name, err)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif metric.Name == \"\" {\n\t\t\t\tlog.Errorf(\"Skipping metric collection. Invalid metric %s: %#v\", name, metric)\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// replace \"-\" to \"_\" to make it Prometheus friendly metric names\n\t\t\tmetric.Name = strings.ReplaceAll(name, \"-\", \"_\") + \"_\" + metric.Name\n\n\t\t\tif _, ok := CustomGaugeMetricsMap[metric.Name]; !ok {\n\t\t\t\tCustomGaugeMetricsMap[metric.Name] = prometheus.NewGaugeVec(\n\t\t\t\t\tprometheus.GaugeOpts{\n\t\t\t\t\t\tName: metric.Name,\n\t\t\t\t\t\tHelp: metric.Help,\n\t\t\t\t\t},\n\t\t\t\t\t[]string{hcName},\n\t\t\t\t)\n\t\t\t\tif err := registry.Register(CustomGaugeMetricsMap[metric.Name]); err != nil {\n\t\t\t\t\tlog.Errorf(\"Error registering %s metric %s\\n\", metric.Name, err)\n\t\t\t\t}\n\t\t\t}\n\t\t\tCustomGaugeMetricsMap[metric.Name].With(prometheus.Labels{hcName: name}).Set(metric.Value)\n\t\t\tlog.Printf(\"Successfully collected metric for %s, metric: %#v\", name, metric)\n\t\t}\n\t\tlog.Debugf(\"Here is the registered CustomGaugeMetricsMap %v\\n\", CustomGaugeMetricsMap)\n\t}\n}", "func (o *EnvironmentUsageDto) GetCustomMetrics() []CustomMetricDto {\n\tif o == nil || o.CustomMetrics == nil {\n\t\tvar ret []CustomMetricDto\n\t\treturn ret\n\t}\n\treturn *o.CustomMetrics\n}", "func (mf *MetricFilter) MergeWith(mf2 MetricFilter) MetricFilter {\n\tif mf2.MetricName != \"\" {\n\t\tmf2.MetricNames = append(mf2.MetricNames, mf2.MetricName)\n\t}\n\tmf.MetricNames = append(mf.MetricNames, mf2.MetricNames...)\n\treturn *mf\n}", "func (o StorageClusterSpecOutput) CustomImageRegistry() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterSpec) *string { return v.CustomImageRegistry }).(pulumi.StringPtrOutput)\n}", "func (o ApplicationSpecSourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationSpecSourceKustomize) map[string]string { return v.CommonLabels }).(pulumi.StringMapOutput)\n}", "func (j *Job) SetCustom(name string, value interface{}) *Job {\n\tif j.Custom == nil {\n\t\tj.Custom = map[string]interface{}{}\n\t}\n\n\tj.Custom[name] = value\n\treturn j\n}", "func (o IndexingConfigurationThingGroupIndexingConfigurationPtrOutput) CustomFields() IndexingConfigurationThingGroupIndexingConfigurationCustomFieldArrayOutput {\n\treturn o.ApplyT(func(v *IndexingConfigurationThingGroupIndexingConfiguration) []IndexingConfigurationThingGroupIndexingConfigurationCustomField {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CustomFields\n\t}).(IndexingConfigurationThingGroupIndexingConfigurationCustomFieldArrayOutput)\n}", "func (ids OrganizationOrUserIdentifiers) CombinedIdentifiers() *CombinedIdentifiers {\n\treturn ids.EntityIdentifiers().CombinedIdentifiers()\n}", "func AnalyticsUtteranceMetricName_Values() []string {\n\treturn []string{\n\t\tAnalyticsUtteranceMetricNameCount,\n\t\tAnalyticsUtteranceMetricNameMissed,\n\t\tAnalyticsUtteranceMetricNameDetected,\n\t\tAnalyticsUtteranceMetricNameUtteranceTimestamp,\n\t}\n}", "func makeCustomFormatOpts(tokens []string) string {\n\tvar key string\n\tvar value string\n\tresultOpts := make([]string, 0)\n\n\tfor i := 0; i < len(tokens)-1; i += 2 {\n\t\tkey = tokens[i]\n\t\tvalue = tokens[i+1]\n\t\topt := fmt.Sprintf(`%s = %s`, key, value)\n\t\tresultOpts = append(resultOpts, opt)\n\t}\n\treturn strings.Join(resultOpts, \", \")\n}", "func (o ApplicationStatusOperationStateSyncResultSourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateSyncResultSourceKustomize) map[string]string {\n\t\treturn v.CommonLabels\n\t}).(pulumi.StringMapOutput)\n}", "func (o ApplicationStatusSyncComparedToSourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSourceKustomize) map[string]string { return v.CommonLabels }).(pulumi.StringMapOutput)\n}", "func CustomContext(values map[interface{}]interface{}) web.Middleware {\n\n\t// This is the actual middleware function to be executed.\n\tf := func(after web.Handler) web.Handler {\n\n\t\t// Wrap this handler around the next one provided.\n\t\th := func(ctx context.Context, w http.ResponseWriter, r *http.Request, params map[string]string) error {\n\t\t\tspan, ctx := tracer.StartSpanFromContext(ctx, \"internal.mid.CustomContext\")\n\t\t\tdefer span.Finish()\n\n\t\t\tm := func() error {\n\t\t\t\tfor k, v := range values {\n\t\t\t\t\tif cv := ctx.Value(k); cv == nil {\n\t\t\t\t\t\tctx = context.WithValue(ctx, k, v)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif err := m(); err != nil {\n\t\t\t\tif web.RequestIsJson(r) {\n\t\t\t\t\treturn web.RespondJsonError(ctx, w, err)\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn after(ctx, w, r, params)\n\t\t}\n\n\t\treturn h\n\t}\n\n\treturn f\n}", "func (mnuo *MetricNameUpdateOne) AddMetricIDs(ids ...int) *MetricNameUpdateOne {\n\tmnuo.mutation.AddMetricIDs(ids...)\n\treturn mnuo\n}", "func (o ApplicationOperationSyncSourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationOperationSyncSourceKustomize) map[string]string { return v.CommonLabels }).(pulumi.StringMapOutput)\n}", "func getNameAndValue(m *dto.Metric) map[string]interface{} {\n\tfields := make(map[string]interface{})\n\tif m.Gauge != nil {\n\t\tif !math.IsNaN(m.GetGauge().GetValue()) {\n\t\t\t//nolint:unconvert // Conversion may be needed for float64 https://github.com/mdempsky/unconvert/issues/40\n\t\t\tfields[\"gauge\"] = float64(m.GetGauge().GetValue())\n\t\t}\n\t} else if m.Counter != nil {\n\t\tif !math.IsNaN(m.GetCounter().GetValue()) {\n\t\t\t//nolint:unconvert // Conversion may be needed for float64 https://github.com/mdempsky/unconvert/issues/40\n\t\t\tfields[\"counter\"] = float64(m.GetCounter().GetValue())\n\t\t}\n\t} else if m.Untyped != nil {\n\t\tif !math.IsNaN(m.GetUntyped().GetValue()) {\n\t\t\t//nolint:unconvert // Conversion may be needed for float64 https://github.com/mdempsky/unconvert/issues/40\n\t\t\tfields[\"value\"] = float64(m.GetUntyped().GetValue())\n\t\t}\n\t}\n\treturn fields\n}", "func AnalyticsSessionMetricName_Values() []string {\n\treturn []string{\n\t\tAnalyticsSessionMetricNameCount,\n\t\tAnalyticsSessionMetricNameSuccess,\n\t\tAnalyticsSessionMetricNameFailure,\n\t\tAnalyticsSessionMetricNameDropped,\n\t\tAnalyticsSessionMetricNameDuration,\n\t\tAnalyticsSessionMetricNameTurnsPerConversation,\n\t\tAnalyticsSessionMetricNameConcurrency,\n\t}\n}", "func (c Counters) Merge(other Counters) Counters {\n\tresult := c.Copy()\n\tfor k, v := range other {\n\t\tresult[k] = result[k] + v\n\t}\n\treturn result\n}", "func (w *PropertyWrite) addCustom(q *msg.Request, mr *msg.Result) {\n\tvar (\n\t\tres sql.Result\n\t\terr error\n\t)\n\n\tq.Property.Custom.ID = uuid.Must(uuid.NewV4()).String()\n\tif res, err = w.stmtAddCustom.Exec(\n\t\tq.Property.Custom.ID,\n\t\tq.Property.Custom.RepositoryID,\n\t\tq.Property.Custom.Name,\n\t); err != nil {\n\t\tmr.ServerError(err, q.Section)\n\t\treturn\n\t}\n\tif mr.RowCnt(res.RowsAffected()) {\n\t\tmr.Property = append(mr.Property, q.Property)\n\t}\n}", "func standardEncoder(name string, fNames ...string) encoderFunc {\n\treturn func(ctx context.Context, record interface{}) Components {\n\t\t// Retrieve the value of the specified field\n\t\tfVal := reflect.ValueOf(record)\n\t\tfor _, fName := range fNames {\n\t\t\tfVal = reflect.Indirect(fVal)\n\t\t\tfVal = fVal.FieldByName(fName)\n\t\t}\n\n\t\t// Add string value of field to global id components\n\t\tcomponents := Encode(ctx, record)\n\t\tcomponents.resource = name\n\t\tcomponents.uniqueComponent = fVal.String()\n\n\t\t// Add namespace to global id components\n\t\tif multiRecord, ok := record.(types.MultitenantResource); ok {\n\t\t\taddMultitenantFields(components, multiRecord)\n\t\t}\n\n\t\treturn components\n\t}\n}", "func (myprovider *ElasticWorkerMetricsProvider) GetMetricBySelector(namespace string, selector labels.Selector, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValueList, error) {\n klog.Infof(\"Attempt to retrieve metric: %v for resources in namespace: %v and resource selector: %v\", info, namespace, selector)\n\n resourceNames, err := helpers.ListObjectNames(myprovider.mapper, myprovider.client, namespace, selector, info)\n \tif err != nil {\n \t\tklog.Errorf(\"unable to list matching resource names: %v\", err)\n \t\treturn nil, apierr.NewInternalError(fmt.Errorf(\"unable to list matching resources\"))\n \t}\n\n metrics := []custom_metrics.MetricValue{}\n for idx := range resourceNames {\n value, err := myprovider.valueFor(info, namespace, resourceNames[idx])\n if err != nil {\n klog.Errorf(\"unable to retrieve metrics: %v\", err)\n return nil, err\n }\n metricValue, err := myprovider.metricFor(value, types.NamespacedName{Namespace: namespace, Name: resourceNames[idx]} , info)\n if err != nil {\n \t\tklog.Errorf(\"unable to convert raw metric: %v to metricValue: %v\", value, err)\n \t\treturn nil, apierr.NewInternalError(fmt.Errorf(\"unable to convert raw metric: %v to metricValue: %v\", value, err))\n \t}\n metrics = append(metrics, *metricValue)\n }\n\n return &custom_metrics.MetricValueList{\n Items: metrics,\n }, nil\n}", "func (ipam *IPAMServer) IngestCustomData(devicesWithAddr []custom.DeviceData, devicesWithoutAddr []custom.UnknownDeviceData, preferredHeaderOrder ...string) {\n\tipam.custom.RecreateDatastore(devicesWithAddr, devicesWithoutAddr, preferredHeaderOrder)\n}", "func (o *Options) tagMetrics(rowTags []tag.Tag, addlTags []string) []string {\n\tfinalTags := make([]string, len(o.Tags), len(o.Tags)+len(rowTags)+len(addlTags))\n\tcopy(finalTags, o.Tags)\n\tfor key := range rowTags {\n\t\tfinalTags = append(finalTags,\n\t\t\trowTags[key].Key.Name()+\":\"+rowTags[key].Value)\n\t}\n\tfinalTags = append(finalTags, addlTags...)\n\treturn finalTags\n}", "func (suite *TestCompountReportSuite) TestCompareSpecialValues(c *C) {\n\ttestCases := []*struct {\n\t\tleftValue *Metrics\n\t\trightValue *Metrics\n\t\tcompareFuncName string\n\t\texpectedResult int\n\t}{\n\t\t{&Metrics{Max: 10}, &Metrics{Max: 20}, MetricMax, -1},\n\t\t{&Metrics{Max: -1}, &Metrics{Max: 10}, MetricMax, 1},\n\t\t{&Metrics{Max: 10}, &Metrics{Max: -1}, MetricMax, -1},\n\t\t{&Metrics{Min: 10}, &Metrics{Min: 20}, MetricMin, -1},\n\t\t{&Metrics{Min: -1}, &Metrics{Min: 10}, MetricMin, 1},\n\t\t{&Metrics{Min: 10}, &Metrics{Min: -1}, MetricMin, -1},\n\t\t{&Metrics{Med: 10}, &Metrics{Med: 20}, MetricMed, -1},\n\t\t{&Metrics{Med: -1}, &Metrics{Med: 10}, MetricMed, 1},\n\t\t{&Metrics{Med: 10}, &Metrics{Med: -1}, MetricMed, -1},\n\t\t{&Metrics{Avg: 10.34}, &Metrics{Avg: 20.33}, MetricAvg, -1},\n\t\t{&Metrics{Avg: -1}, &Metrics{Avg: 20.33}, MetricAvg, 1},\n\t\t{&Metrics{Avg: 10.34}, &Metrics{Avg: -1}, MetricAvg, -1},\n\t\t{&Metrics{Mdev: 10.34}, &Metrics{Mdev: 20.33}, MetricMdev, -1},\n\t\t{&Metrics{Mdev: -1}, &Metrics{Mdev: 20.33}, MetricMdev, 1},\n\t\t{&Metrics{Mdev: 10.34}, &Metrics{Mdev: -1}, MetricMdev, -1},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tcomment := ocheck.TestCaseComment(i)\n\t\tocheck.LogTestCase(c, testCase)\n\n\t\ttestedFunc := CompareFunctions[testCase.compareFuncName]\n\t\ttestedResult := testedFunc(\n\t\t\t&DynamicRecord{Metrics: &DynamicMetrics{Metrics: testCase.leftValue}},\n\t\t\t&DynamicRecord{Metrics: &DynamicMetrics{Metrics: testCase.rightValue}},\n\t\t\tutils.Descending,\n\t\t)\n\n\t\tc.Assert(testedResult, Equals, testCase.expectedResult, comment)\n\t}\n}", "func (o ApplicationStatusHistorySourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationStatusHistorySourceKustomize) map[string]string { return v.CommonLabels }).(pulumi.StringMapOutput)\n}", "func ConcatenateValues(values []string, indices []int) (string, error) {\n\treturn ConcatenateValuesNull(values, indices, \"<NULL>\")\n}", "func transformValueMetric(cfEvent *events.Envelope, nrEvent map[string]interface{}) {\n\t// event: origin:\"DopplerServer\" eventType:ValueMetric timestamp:1497038365914920486 deployment:\"cf\" job:\"doppler\" index:\"ca858dc5-2a09-465a-831d-c31fa5fb8802\" ip:\"192.168.16.26\" valueMetric:<name:\"messageRouter.numberOfFirehoseSinks\" value:1 unit:\"sinks\" >\n\tvm := cfEvent.ValueMetric\n\tprefix := \"valueMetric\"\n\tif vm.Name != nil {\n\t\tnrEvent[prefix+\"Name\"] = vm.GetName()\n\t}\n\tif vm.Value != nil {\n\t\tnrEvent[prefix+\"Value\"] = vm.GetValue()\n\t}\n\tif vm.Unit != nil {\n\t\tnrEvent[prefix+\"Unit\"] = vm.GetUnit()\n\t}\n}", "func (o IndexingConfigurationThingIndexingConfigurationOutput) CustomFields() IndexingConfigurationThingIndexingConfigurationCustomFieldArrayOutput {\n\treturn o.ApplyT(func(v IndexingConfigurationThingIndexingConfiguration) []IndexingConfigurationThingIndexingConfigurationCustomField {\n\t\treturn v.CustomFields\n\t}).(IndexingConfigurationThingIndexingConfigurationCustomFieldArrayOutput)\n}", "func CustomVocabularyStatus_Values() []string {\n\treturn []string{\n\t\tCustomVocabularyStatusReady,\n\t\tCustomVocabularyStatusDeleting,\n\t\tCustomVocabularyStatusExporting,\n\t\tCustomVocabularyStatusImporting,\n\t\tCustomVocabularyStatusCreating,\n\t}\n}", "func newCustomMetrics() ICustomMetrics {\n\n\tcounters := make(map[string]prometheus.Counter)\n\tgauges := make(map[string]prometheus.Gauge)\n\tsummaries := make(map[string]prometheus.Summary)\n\thistograms := make(map[string]prometheus.Histogram)\n\n\treturn &customMetrics{\n\t\tcounters: counters,\n\t\tgauges: gauges,\n\t\tsummaries: summaries,\n\t\thistograms: histograms,\n\t}\n}", "func (it *iterator) updateMarshallerWithCustomValues(arg updateLastIterArg) error {\n\tvar (\n\t\tfieldNum = int32(it.customFields[arg.i].fieldNum)\n\t\tfieldType = it.customFields[arg.i].fieldType\n\t\tprotoFieldType = it.customFields[arg.i].protoFieldType\n\t)\n\n\tif protoFieldType == protoFieldTypeNotFound {\n\t\t// This can happen when the field being decoded does not exist (or is reserved)\n\t\t// in the current schema, but the message was encoded with a schema in which the\n\t\t// field number did exist.\n\t\treturn nil\n\t}\n\n\tswitch {\n\tcase isCustomFloatEncodedField(fieldType):\n\t\tvar (\n\t\t\tval = math.Float64frombits(it.customFields[arg.i].floatEncAndIter.PrevFloatBits)\n\t\t\terr error\n\t\t)\n\t\tif fieldType == float64Field {\n\t\t\tit.marshaller.encFloat64(fieldNum, val)\n\t\t} else {\n\t\t\tit.marshaller.encFloat32(fieldNum, float32(val))\n\t\t}\n\t\treturn err\n\n\tcase isCustomIntEncodedField(fieldType):\n\t\tswitch fieldType {\n\t\tcase signedInt64Field:\n\t\t\tval := int64(it.customFields[arg.i].intEncAndIter.prevIntBits)\n\t\t\tif protoFieldType == dpb.FieldDescriptorProto_TYPE_SINT64 {\n\t\t\t\t// The encoding / compression schema in this package treats Protobuf int32 and sint32 the same,\n\t\t\t\t// however, Protobuf unmarshallers assume that fields of type sint are zigzag encoded. As a result,\n\t\t\t\t// the iterator needs to check the fields protobuf type so that it can perform the correct encoding.\n\t\t\t\tit.marshaller.encSInt64(fieldNum, val)\n\t\t\t} else if protoFieldType == dpb.FieldDescriptorProto_TYPE_SFIXED64 {\n\t\t\t\tit.marshaller.encSFixedInt64(fieldNum, val)\n\t\t\t} else {\n\t\t\t\tit.marshaller.encInt64(fieldNum, val)\n\t\t\t}\n\t\t\treturn nil\n\n\t\tcase unsignedInt64Field:\n\t\t\tval := it.customFields[arg.i].intEncAndIter.prevIntBits\n\t\t\tit.marshaller.encUInt64(fieldNum, val)\n\t\t\treturn nil\n\n\t\tcase signedInt32Field:\n\t\t\tvar (\n\t\t\t\tval = int32(it.customFields[arg.i].intEncAndIter.prevIntBits)\n\t\t\t\tfield = it.schema.FindFieldByNumber(fieldNum)\n\t\t\t)\n\t\t\tif field == nil {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"updating last iterated with value, could not find field number %d in schema\", fieldNum)\n\t\t\t}\n\n\t\t\tfieldType := field.GetType()\n\t\t\tif fieldType == dpb.FieldDescriptorProto_TYPE_SINT32 {\n\t\t\t\t// The encoding / compression schema in this package treats Protobuf int32 and sint32 the same,\n\t\t\t\t// however, Protobuf unmarshallers assume that fields of type sint are zigzag encoded. As a result,\n\t\t\t\t// the iterator needs to check the fields protobuf type so that it can perform the correct encoding.\n\t\t\t\tit.marshaller.encSInt32(fieldNum, val)\n\t\t\t} else if fieldType == dpb.FieldDescriptorProto_TYPE_SFIXED32 {\n\t\t\t\tit.marshaller.encSFixedInt32(fieldNum, val)\n\t\t\t} else {\n\t\t\t\tit.marshaller.encInt32(fieldNum, val)\n\t\t\t}\n\t\t\treturn nil\n\n\t\tcase unsignedInt32Field:\n\t\t\tval := uint32(it.customFields[arg.i].intEncAndIter.prevIntBits)\n\t\t\tit.marshaller.encUInt32(fieldNum, val)\n\t\t\treturn nil\n\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"%s expected custom int encoded field but field type was: %v\",\n\t\t\t\titErrPrefix, fieldType)\n\t\t}\n\n\tcase fieldType == bytesField:\n\t\tit.marshaller.encBytes(fieldNum, arg.bytesFieldBuf)\n\t\treturn nil\n\n\tcase fieldType == boolField:\n\t\tit.marshaller.encBool(fieldNum, arg.boolVal)\n\t\treturn nil\n\n\tdefault:\n\t\treturn fmt.Errorf(\n\t\t\t\"%s unhandled fieldType: %v\", itErrPrefix, fieldType)\n\t}\n}", "func tagsFromMetric(m model.Metric) string {\n\ttags := make(map[string]interface{}, len(m)-1)\n\tfor l, v := range m {\n\t\tif l != model.MetricNameLabel {\n\t\t\ttags[string(l)] = string(v)\n\t\t}\n\t}\n\ttagsmarshaled, _ := json.Marshal(tags)\n\treturn string(tagsmarshaled)\n}", "func (e *xmlExporter) writeCustom(name xml.Name, val reflect.Value) error {\n\tt := val.Type()\n\tif t.Implements(typeOfTextMarshaler) {\n\t\tv, err := val.Interface().(encoding.TextMarshaler).MarshalText()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn e.writeValue(name, reflect.ValueOf(string(v)))\n\t}\n\treturn fmt.Errorf(\"Unsupported type: %v\", val.Type())\n}", "func (m *Measurement) uniqueTagValues(expr influxql.Expr) map[string][]string {\n\t// Track unique value per tag.\n\ttags := make(map[string]map[string]struct{})\n\n\t// Find all tag values referenced in the expression.\n\tinfluxql.WalkFunc(expr, func(n influxql.Node) {\n\t\tswitch n := n.(type) {\n\t\tcase *influxql.BinaryExpr:\n\t\t\t// Ignore operators that are not equality.\n\t\t\tif n.Op != influxql.EQ {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Extract ref and string literal.\n\t\t\tvar key, value string\n\t\t\tswitch lhs := n.LHS.(type) {\n\t\t\tcase *influxql.VarRef:\n\t\t\t\tif rhs, ok := n.RHS.(*influxql.StringLiteral); ok {\n\t\t\t\t\tkey, value = lhs.Val, rhs.Val\n\t\t\t\t}\n\t\t\tcase *influxql.StringLiteral:\n\t\t\t\tif rhs, ok := n.RHS.(*influxql.VarRef); ok {\n\t\t\t\t\tkey, value = rhs.Val, lhs.Val\n\t\t\t\t}\n\t\t\t}\n\t\t\tif key == \"\" {\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Add value to set.\n\t\t\tif tags[key] == nil {\n\t\t\t\ttags[key] = make(map[string]struct{})\n\t\t\t}\n\t\t\ttags[key][value] = struct{}{}\n\t\t}\n\t})\n\n\t// Convert to map of slices.\n\tout := make(map[string][]string)\n\tfor k, values := range tags {\n\t\tout[k] = make([]string, 0, len(values))\n\t\tfor v := range values {\n\t\t\tout[k] = append(out[k], v)\n\t\t}\n\t\tsort.Strings(out[k])\n\t}\n\treturn out\n}", "func WithCustomGRPCMetadata(ctx context.Context, md map[string]string) context.Context {\n\tfor k, v := range md {\n\t\t// Uppercase keys will be converted to lowercase.\n\t\tctx = metadata.AppendToOutgoingContext(ctx, k, v)\n\t}\n\n\treturn ctx\n}", "func (r *tagReader) CollectTagValues(\n\ttagKeyID tag.KeyID,\n\ttagValueIDs *roaring.Bitmap,\n\ttagValues map[uint32]string,\n) error {\n\tfor _, reader := range r.readers {\n\t\tif tagValueIDs.IsEmpty() {\n\t\t\treturn nil\n\t\t}\n\t\ttagKeyMetaBlock, err := reader.Get(uint32(tagKeyID))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\ttagKeyMeta, err := newTagKeyMetaFn(tagKeyMetaBlock)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif err := tagKeyMeta.CollectTagValues(tagValueIDs, tagValues); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o ApplicationStatusOperationStateOperationSyncSourceKustomizeOutput) CommonLabels() pulumi.StringMapOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSyncSourceKustomize) map[string]string {\n\t\treturn v.CommonLabels\n\t}).(pulumi.StringMapOutput)\n}", "func (v Values) Merge(src Values) Values {\n\tfor key, srcVal := range src {\n\t\tdestVal, found := v[key]\n\n\t\tsrcType := fmt.Sprintf(\"%T\", srcVal)\n\t\tdestType := fmt.Sprintf(\"%T\", destVal)\n\t\tmatch := srcType == destType\n\t\tvalidSrc := istable(srcVal)\n\t\tvalidDest := istable(destVal)\n\n\t\tif found && match && validSrc && validDest {\n\t\t\tdestMap := destVal.(Values)\n\t\t\tsrcMap := srcVal.(Values)\n\t\t\tdestMap.Merge(srcMap)\n\t\t} else {\n\t\t\tv[key] = srcVal\n\t\t}\n\t}\n\treturn v\n}", "func (o FioSpecOutput) CustomJobFiles() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v FioSpec) []string { return v.CustomJobFiles }).(pulumi.StringArrayOutput)\n}", "func (mnu *MetricNameUpdate) AddMetricIDs(ids ...int) *MetricNameUpdate {\n\tmnu.mutation.AddMetricIDs(ids...)\n\treturn mnu\n}", "func (o ReservationAffinityOutput) Values() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v ReservationAffinity) []string { return v.Values }).(pulumi.StringArrayOutput)\n}", "func (byEntityTypedId MonitoringProps) ByMetricMeta() map[MetricMeta][]model.EntityTypedId {\n\tbyMetricMeta := map[MetricMeta][]model.EntityTypedId{}\n\tfor entityTypedId, monTemplate := range byEntityTypedId {\n\t\tfor _, metricMeta := range monTemplate {\n\t\t\ttypedIds, exists := byMetricMeta[metricMeta]\n\t\t\tif !exists {\n\t\t\t\ttypedIds = []model.EntityTypedId{}\n\t\t\t}\n\t\t\ttypedIds = append(typedIds, entityTypedId)\n\t\t\tbyMetricMeta[metricMeta] = typedIds\n\t\t}\n\t}\n\treturn byMetricMeta\n}", "func (s *SystemMetrics) Combine(cpu, memory, disk, net string) string {\n\treturn cpu + \"|\" + memory + \"|\" + disk + \"|\" + net\n}", "func (o StorageClusterSpecPtrOutput) CustomImageRegistry() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *StorageClusterSpec) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.CustomImageRegistry\n\t}).(pulumi.StringPtrOutput)\n}", "func (o LinuxWebAppOutput) CustomDomainVerificationId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *LinuxWebApp) pulumi.StringOutput { return v.CustomDomainVerificationId }).(pulumi.StringOutput)\n}", "func (sm *ServerMetrics) merge(o *ServerMetrics) {\n\tmergeMap(sm.Utilization, o.Utilization)\n\tmergeMap(sm.RequestCost, o.RequestCost)\n\tmergeMap(sm.NamedMetrics, o.NamedMetrics)\n\tif o.CPUUtilization != -1 {\n\t\tsm.CPUUtilization = o.CPUUtilization\n\t}\n\tif o.MemUtilization != -1 {\n\t\tsm.MemUtilization = o.MemUtilization\n\t}\n\tif o.AppUtilization != -1 {\n\t\tsm.AppUtilization = o.AppUtilization\n\t}\n\tif o.QPS != -1 {\n\t\tsm.QPS = o.QPS\n\t}\n\tif o.EPS != -1 {\n\t\tsm.EPS = o.EPS\n\t}\n}", "func (ids ApplicationIdentifiers) CombinedIdentifiers() *CombinedIdentifiers {\n\treturn ids.EntityIdentifiers().CombinedIdentifiers()\n}", "func (a *Application) loadCustomizedResMap() (resmap.ResMap, error) {\n\terrs := &interror.KustomizationErrors{}\n\tresult, err := a.loadResMapFromBasesAndResources()\n\tif err != nil {\n\t\terrs.Append(errors.Wrap(err, \"loadResMapFromBasesAndResources\"))\n\t}\n\terr = crds.RegisterCRDs(a.ldr, a.kustomization.Crds)\n\tif err != nil {\n\t\terrs.Append(errors.Wrap(err, \"RegisterCRDs\"))\n\t}\n\tcms, err := resmap.NewResMapFromConfigMapArgs(\n\t\tconfigmapandsecret.NewConfigMapFactory(a.fSys, a.ldr),\n\t\ta.kustomization.ConfigMapGenerator)\n\tif err != nil {\n\t\terrs.Append(errors.Wrap(err, \"NewResMapFromConfigMapArgs\"))\n\t}\n\tsecrets, err := resmap.NewResMapFromSecretArgs(\n\t\tconfigmapandsecret.NewSecretFactory(a.fSys, a.ldr.Root()),\n\t\ta.kustomization.SecretGenerator)\n\tif err != nil {\n\t\terrs.Append(errors.Wrap(err, \"NewResMapFromSecretArgs\"))\n\t}\n\tres, err := resmap.MergeWithoutOverride(cms, secrets)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"Merge\")\n\t}\n\n\tresult, err = resmap.MergeWithOverride(result, res)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ta.kustomization.PatchesStrategicMerge = patch.Append(a.kustomization.PatchesStrategicMerge, a.kustomization.Patches...)\n\tpatches, err := resmap.NewResourceSliceFromPatches(a.ldr, a.kustomization.PatchesStrategicMerge)\n\tif err != nil {\n\t\terrs.Append(errors.Wrap(err, \"NewResourceSliceFromPatches\"))\n\t}\n\n\tif len(errs.Get()) > 0 {\n\t\treturn nil, errs\n\t}\n\n\tvar r []transformers.Transformer\n\tt, err := a.newTransformer(patches)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr = append(r, t)\n\tt, err = patchtransformer.NewPatchJson6902Factory(a.ldr).MakePatchJson6902Transformer(a.kustomization.PatchesJson6902)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr = append(r, t)\n\tt, err = transformers.NewImageTagTransformer(a.kustomization.ImageTags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr = append(r, t)\n\n\terr = transformers.NewMultiTransformer(r).Transform(result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result, nil\n}", "func (c *CustomRuleConditionsValue) UnmarshalJSON(data []byte) error {\n\tvar nums interface{}\n\terr := json.Unmarshal(data, &nums)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\titems := reflect.ValueOf(nums)\n\tswitch items.Kind() {\n\tcase reflect.String:\n\t\t*c = append(*c, items.String())\n\n\tcase reflect.Slice:\n\t\t*c = make(CustomRuleConditionsValue, 0, items.Len())\n\t\tfor i := 0; i < items.Len(); i++ {\n\t\t\titem := items.Index(i)\n\t\t\tswitch item.Kind() {\n\t\t\tcase reflect.String:\n\t\t\t\t*c = append(*c, item.String())\n\t\t\tcase reflect.Interface:\n\t\t\t\t*c = append(*c, item.Interface().(string))\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (cc *cpuCollector) exportValues(values []string, cv *promm.GaugeVec) {\n\tfor stateIndex, valueStr := range values {\n\t\tif stateIndex > len(cpuStates) {\n\t\t\tbreak\n\t\t}\n\t\tif cc.recordedStates&(1<<uint(stateIndex)) != 0 {\n\t\t\tjiffies, err := strconv.ParseUint(valueStr, 10, 64)\n\t\t\tif err != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tcc.metricLabels[\"state\"] = cpuStates[stateIndex]\n\t\t\tcv.With(cc.metricLabels).Set(float64(jiffies) * cc.jiffiesScaler)\n\t\t}\n\t}\n}", "func (t Tags) Merge(key string, value ...string) {\n\tfor _, v := range value {\n\t\tcurrent := t.GetAll(key)\n\t\tfound := false\n\t\tfor _, cv := range current {\n\t\t\tif v == cv {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tt.Add(key, v)\n\t\t}\n\t}\n}", "func (c *Components1Jq1T4ISchemasManagedserviceidentityPropertiesUserassignedidentitiesAdditionalproperties) UnmarshalJSON(data []byte) error {\n\tvar rawMsg map[string]json.RawMessage\n\tif err := json.Unmarshal(data, &rawMsg); err != nil {\n\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", c, err)\n\t}\n\tfor key, val := range rawMsg {\n\t\tvar err error\n\t\tswitch key {\n\t\tcase \"clientId\":\n\t\t\terr = unpopulate(val, \"ClientID\", &c.ClientID)\n\t\t\tdelete(rawMsg, key)\n\t\tcase \"principalId\":\n\t\t\terr = unpopulate(val, \"PrincipalID\", &c.PrincipalID)\n\t\t\tdelete(rawMsg, key)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling type %T: %v\", c, err)\n\t\t}\n\t}\n\treturn nil\n}", "func (cs *CounterIndex) Merge(s Counters) {\n\tfor i := range s {\n\t\tc := &s[i]\n\t\tcs.Add(c.Count, c.Values...)\n\t}\n}", "func (myprovider *ElasticWorkerMetricsProvider) metricFor(value string, name types.NamespacedName, info provider.CustomMetricInfo) (*custom_metrics.MetricValue, error) {\n // construct a reference referring to the described object\n objRef, err := helpers.ReferenceFor(myprovider.mapper, name, info)\n if err != nil {\n klog.Errorf(\"error in building reference object: %v\", err)\n return nil, err\n }\n\n currentValue, err := strconv.Atoi(value)\n if err != nil {\n klog.Errorf(\"error in converting string:%v to int for metric value error: %v\", value, err)\n return nil, err\n }\n\n return &custom_metrics.MetricValue{\n DescribedObject: objRef,\n // skipping selector info fill\n Metric: \t custom_metrics.MetricIdentifier{Name:info.Metric},\n // TODO: fetch timestamp from redis, currently using a dummy value\n Timestamp: metav1.Time{time.Now()},\n // TODO: support different types of metric value, currently only load percentage(0-100) is supported\n Value: *resource.NewQuantity(int64(currentValue), \"PercentageLoad\"),\n }, nil\n}", "func (s MetricValue) MarshalFields(e protocol.FieldEncoder) error {\n\tif s.Cidrs != nil {\n\t\tv := s.Cidrs\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"cidrs\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.QuotedValue{ValueMarshaler: protocol.StringValue(v1)})\n\t\t}\n\t\tls0.End()\n\n\t}\n\tif s.Count != nil {\n\t\tv := *s.Count\n\n\t\tmetadata := protocol.Metadata{}\n\t\te.SetValue(protocol.BodyTarget, \"count\", protocol.Int64Value(v), metadata)\n\t}\n\tif s.Ports != nil {\n\t\tv := s.Ports\n\n\t\tmetadata := protocol.Metadata{}\n\t\tls0 := e.List(protocol.BodyTarget, \"ports\", metadata)\n\t\tls0.Start()\n\t\tfor _, v1 := range v {\n\t\t\tls0.ListAddValue(protocol.Int64Value(v1))\n\t\t}\n\t\tls0.End()\n\n\t}\n\treturn nil\n}", "func (p *MetricsProvider) metricsFor(namespace string, selector labels.Selector, info provider.CustomMetricInfo, metricSelector labels.Selector) (*custom_metrics.MetricValueList, error) {\n\tnames, err := helpers.ListObjectNames(p.mapper, p.client, namespace, selector, info)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tres := make([]custom_metrics.MetricValue, 0, len(names))\n\tfor _, name := range names {\n\t\tnamespacedName := types.NamespacedName{Name: name, Namespace: namespace}\n\t\tvalue, err := p.valueFor(info, namespacedName)\n\t\tif err != nil {\n\t\t\tif apierr.IsNotFound(err) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\tmetric, err := p.metricFor(value, namespacedName, info, metricSelector)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, *metric)\n\t}\n\n\treturn &custom_metrics.MetricValueList{\n\t\tItems: res,\n\t}, nil\n}" ]
[ "0.5353237", "0.48009384", "0.47915414", "0.47384396", "0.4737442", "0.46071893", "0.45836797", "0.45555514", "0.45379713", "0.4510305", "0.44950247", "0.44751006", "0.44739965", "0.44663346", "0.44537818", "0.44394836", "0.44092548", "0.44048595", "0.4396583", "0.43906888", "0.43887955", "0.43402815", "0.43316823", "0.43265045", "0.42969602", "0.4288556", "0.42847395", "0.42738926", "0.42657974", "0.42636195", "0.42562637", "0.42338413", "0.4231106", "0.42283672", "0.42107835", "0.4192735", "0.4187332", "0.41745728", "0.41522914", "0.4143361", "0.41370088", "0.41283426", "0.41259593", "0.4121567", "0.41149986", "0.41132823", "0.41090456", "0.41088906", "0.4106516", "0.40983662", "0.40962863", "0.40868777", "0.40819716", "0.40817073", "0.40788856", "0.40687865", "0.4060249", "0.40581036", "0.40390152", "0.40388474", "0.4038434", "0.40364295", "0.40289515", "0.40265855", "0.40249258", "0.40220228", "0.40191317", "0.4015123", "0.4009673", "0.40085703", "0.40018883", "0.39993453", "0.39965713", "0.39939708", "0.3986825", "0.39843786", "0.3982495", "0.39737895", "0.39710224", "0.39677534", "0.39621943", "0.39509857", "0.39433235", "0.3940943", "0.3938725", "0.39347607", "0.39294222", "0.3926075", "0.39234635", "0.3921579", "0.39199373", "0.39179078", "0.39170063", "0.39162824", "0.39125326", "0.3911648", "0.39111552", "0.3906945", "0.38977206", "0.38945076" ]
0.7023413
0
NewECBEncrypter returns a BlockMode which encrypts in electronic code book mode, using the given Block.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode { return (*ecbEncrypter)(newECB(b)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n return (*ecbEncrypter)(newECB(b))\n}", "func newECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(c cipher.Block) cipher.BlockMode {\n\treturn ecbEncrypter{c}\n}", "func NewECBEncrypter(block cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(block))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n return (*ecbDecrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBDecrypter(block cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(block))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\r\n\treturn (*ecbDecrypter)(newECB(b))\r\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func EncryptECB(plaintext []byte, key []byte) ([]byte, error) {\r\n\r\n\t// 1. Check if plaintext is a multiple of 16\r\n\tif len(plaintext)%16 != 0 {\r\n\t\treturn nil, fmt.Errorf(\"plaintext is %d bytes which is not \"+\r\n\t\t\t\"a multiple of 16.\", len(plaintext))\r\n\t}\r\n\r\n\t// 2. Check if key and 16 are of same length\r\n\tif len(key) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"key has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(key))\r\n\t}\r\n\r\n\t// 3. Get an AES block\r\n\tblock, err := aes.NewCipher(key)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tciphertext := make([]byte, len(plaintext))\r\n\r\n\t// 4. Encrypt each block individually and store\r\n\tfor i := 0; i < len(plaintext); i += 16 {\r\n\t\tblock.Encrypt(ciphertext[i:i+16], plaintext[i:i+16])\r\n\t}\r\n\r\n\treturn ciphertext, nil\r\n}", "func NewECBEncryptionOracle(prepend, unknownString []byte) ECBEncryptionOracle {\n\ta := NewAESECB(nil)\n\tif prepend == nil {\n\t\tprepend = RandomBytes(rand.Intn(50) + 1)\n\t}\n\treturn ECBEncryptionOracle{a, prepend, unknownString}\n}", "func (cipher CipherFunction) New(key []byte) (block cipher.Block) {\n\tvar err error\n\tswitch cipher {\n\tcase TripleDES:\n\t\tblock, err = des.NewTripleDESCipher(key)\n\tcase CAST5:\n\t\tblock, err = cast5.NewCipher(key)\n\tcase AES128, AES192, AES256:\n\t\tblock, err = aes.NewCipher(key)\n\t}\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn\n}", "func newBlockCipher(key string) (cipher.Block, error) {\n\n\thash := md5.New()\n\tfmt.Fprint(hash, key)\n\tcipherKey := hash.Sum(nil)\n\treturn aes.NewCipher(cipherKey)\n}", "func ecbModeOracle(c cipher.Block) (func([]byte) []byte, cipher.BlockMode) {\n\tvar mode cipher.BlockMode\n\tif weak.Intn(2) == 0 {\n\t\tmode = NewECBEncrypter(c)\n\t} else {\n\t\tmode = cipher.NewCBCEncrypter(c, RandomBytes(c.BlockSize()))\n\t}\n\tprefix := RandomBytes(RandomInRange(5, 10))\n\tsuffix := RandomBytes(RandomInRange(5, 10))\n\treturn func(buf []byte) []byte {\n\t\tbuf = append(prefix, append(buf, suffix...)...)\n\t\tbuf = PKCS7Pad(buf, mode.BlockSize())\n\t\tmode.CryptBlocks(buf, buf)\n\t\treturn buf\n\t}, mode\n}", "func NewCipher(key []byte) (cipher.Block, error) {}", "func encryptECB(data, key []byte) (encryptedData []byte, err error) {\n\taesCrypt, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tencryptedData = make([]byte, len(data))\n\taesCrypt.Encrypt(encryptedData, data)\n\n\treturn\n}", "func DecryptECB(ciphertext []byte, key []byte) ([]byte, error) {\r\n\r\n\t// 1. Check if ciphertext is a multiple of 16\r\n\tif len(ciphertext)%16 != 0 {\r\n\t\treturn nil, fmt.Errorf(\"ciphertext is %d bytes which is not \"+\r\n\t\t\t\"a multiple of 16.\", len(ciphertext))\r\n\t}\r\n\r\n\t// 2. Check if key and 16 are of same length\r\n\tif len(key) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"key has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(key))\r\n\t}\r\n\r\n\t// 3. Get an AES block\r\n\tblock, err := aes.NewCipher(key)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tplaintext := make([]byte, len(ciphertext))\r\n\r\n\tfor i := 0; i < len(ciphertext); i += 16 {\r\n\t\tblock.Decrypt(plaintext[i:i+16], ciphertext[i:i+16])\r\n\t}\r\n\r\n\treturn plaintext, nil\r\n}", "func NewCipher(key []byte) cipher.Block {\n\texpkey := keyExpansion(key)\n\treturn cipherAES{expkey}\n}", "func AESEncryptWithECB(str, key []byte) ([]byte, error) {\n\tcb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tblockSize := cb.BlockSize()\n\t// The str arguments can be any length, and padding is automatically added to\n\t// str so it is a multiple of a block as required by block-based algorithms such as AES.\n\t// This padding is automatically removed by the AES_DECRYPT() function.\n\tdata := pkcs7Padding(str, blockSize)\n\tcrypted := make([]byte, len(data))\n\tecb := newECBEncrypter(cb)\n\tecb.CryptBlocks(crypted, data)\n\treturn crypted, nil\n}", "func initBlock() (cipher.Block, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Uninitialized Cipher Block\")\n\t}\n\n\treturn block, nil\n}", "func decryptECB(data, key []byte) (decryptedData []byte, err error) {\n\taesCrypt, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdecryptedData = make([]byte, len(data))\n\taesCrypt.Decrypt(decryptedData, data)\n\n\treturn\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func NewBlockReader(salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockReader {\n\tkey := salt.Apply(pass, cipher.KeySize())\n\treturn BlockReaderFn(func(b secret.Block) ([]byte, error) {\n\t\treturn b.Decrypt(key)\n\t})\n}", "func NewContext(block *core.Block, engine db.DB, wb db.WriteBatch) Context {\n\treturn &DefaultContext{\n\t\tqueryEngine: engine,\n\t\twb: wb,\n\t\tblock: block,\n\t\tchannelID: block.Header.ChannelID,\n\t\tevmCtx: &evm.Context{\n\t\t\tBlockHeight: block.GetNumber(),\n\t\t\tBlockTime: block.Header.Time,\n\t\t\tDifficulty: 0,\n\t\t\tGasLimit: 10000000000,\n\t\t\tGasPrice: 0,\n\t\t\tCoinBase: nil,\n\t\t},\n\t\taccounts: make(map[string]*accountInfo),\n\t}\n}", "func BlockSizeECB(f EncryptFunc) int {\n\tconst (\n\t\tbufLen = 1024\n\t\tminBlockSize = 4\n\t\tmaxBlockSize = bufLen / 4\n\t)\n\n\tenc := f(A(bufLen))\n\n\tfor bs := minBlockSize; bs <= maxBlockSize; bs++ {\n\t\tnumNeeded := bufLen/bs - 2 // first or last may be misaligned\n\t\tvar prevBlock []byte // last block that was seen\n\t\tblockCount := 0 // consecutive occurrences of prevBlock\n\t\tfor start := 0; start+bs < len(enc); start += bs {\n\t\t\tbl := enc[start : start+bs]\n\t\t\tif prevBlock == nil || !bytes.Equal(bl, prevBlock) {\n\t\t\t\tprevBlock = bl\n\t\t\t\tblockCount = 0\n\t\t\t} else {\n\t\t\t\tblockCount++\n\t\t\t\tif blockCount >= numNeeded {\n\t\t\t\t\treturn bs\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"couldn't find block size\")\n}", "func (be *ContentEnc) DecryptBlock(ciphertext []byte, blockNo uint64, fileID []byte) ([]byte, error) {\n\n\t// Empty block?\n\tif len(ciphertext) == 0 {\n\t\treturn ciphertext, nil\n\t}\n\n\t// All-zero block?\n\tif bytes.Equal(ciphertext, be.allZeroBlock) {\n\t\ttlog.Debug.Printf(\"DecryptBlock: file hole encountered\")\n\t\treturn make([]byte, be.plainBS), nil\n\t}\n\n\tif len(ciphertext) < be.cryptoCore.IVLen {\n\t\ttlog.Warn.Printf(\"DecryptBlock: Block is too short: %d bytes\", len(ciphertext))\n\t\treturn nil, errors.New(\"Block is too short\")\n\t}\n\n\t// Extract nonce\n\tnonce := ciphertext[:be.cryptoCore.IVLen]\n\tif bytes.Equal(nonce, be.allZeroNonce) {\n\t\t// Bug in tmpfs?\n\t\t// https://github.com/rfjakob/gocryptfs/issues/56\n\t\t// http://www.spinics.net/lists/kernel/msg2370127.html\n\t\treturn nil, errors.New(\"all-zero nonce\")\n\t}\n\tciphertextOrig := ciphertext\n\tciphertext = ciphertext[be.cryptoCore.IVLen:]\n\n\t// Decrypt\n\tvar plaintext []byte\n\taData := make([]byte, 8)\n\taData = append(aData, fileID...)\n\tbinary.BigEndian.PutUint64(aData, blockNo)\n\tplaintext, err := be.cryptoCore.AEADCipher.Open(plaintext, nonce, ciphertext, aData)\n\n\tif err != nil {\n\t\ttlog.Warn.Printf(\"DecryptBlock: %s, len=%d\", err.Error(), len(ciphertextOrig))\n\t\ttlog.Debug.Println(hex.Dump(ciphertextOrig))\n\t\tif be.forceDecode && err == stupidgcm.ErrAuth {\n\t\t\treturn plaintext, err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn plaintext, nil\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\treturn &Block{\n\t\tHead: NewBlockHeader(prev.Head, uxHash, currentTime, fee, body),\n\t\tBody: body,\n\t}, nil\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\thead := NewBlockHeader(prev.Head, uxHash, currentTime, fee, body)\n\treturn &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}, nil\n}", "func IsECB(ciphertext []byte) (bool, error) {\r\n\r\n\tif len(ciphertext)%16 != 0 {\r\n\t\treturn false, fmt.Errorf(\"ciphertext is not a multiple of %d\", 16)\r\n\t}\r\n\r\n\t// Split into 16 byte\r\n\tsplits := SplitBytes(ciphertext, 16)\r\n\r\n\tcount := 0\r\n\r\n\t// Calculate the number of occurrences-1\r\n\tfor _, block := range splits {\r\n\t\tcount += (bytes.Count(ciphertext, block) - 1)\r\n\t}\r\n\r\n\tif count > 1 {\r\n\t\treturn true, nil\r\n\t}\r\n\r\n\treturn false, nil\r\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func NewCipher(key []byte) (cipher.Block, error) {\n\tl := len(key)\n\tif l%4 != 0 {\n\t\treturn nil, KeySizeError\n\t}\n\tc := rtea{}\n\tc.key = make([]uint32, l/4)\n\tfor i := range c.key {\n\t\tc.key[i] = enc.Uint32(key)\n\t\tkey = key[4:]\n\t}\n\n\treturn c, nil\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func AESDecryptWithECB(cryptStr, key []byte) ([]byte, error) {\n\tcb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tmode := newECBDecrypter(cb)\n\tdata := make([]byte, len(cryptStr))\n\tmode.CryptBlocks(data, cryptStr)\n\td := pkcs5UnPadding(data)\n\treturn d, nil\n}", "func New(workers *workerpool.Group, evictionState *eviction.State, slotTimeProviderFunc func() *slot.TimeProvider, latestCommitmentFunc func(slot.Index) (*commitment.Commitment, error), opts ...options.Option[BlockDAG]) (newBlockDAG *BlockDAG) {\n\treturn options.Apply(&BlockDAG{\n\t\tevents: blockdag.NewEvents(),\n\t\tevictionState: evictionState,\n\t\tslotTimeProviderFunc: slotTimeProviderFunc,\n\t\tmemStorage: memstorage.NewSlotStorage[models.BlockID, *blockdag.Block](),\n\t\tcommitmentFunc: latestCommitmentFunc,\n\t\tfutureBlocks: memstorage.NewSlotStorage[commitment.ID, *advancedset.AdvancedSet[*blockdag.Block]](),\n\t\tWorkers: workers,\n\t\t// do not use workerpool to make sure things run synchronously\n\t\t//workerPool: workers.CreatePool(\"Solidifier\", 2),\n\n\t}, opts,\n\t\tfunc(b *BlockDAG) {\n\t\t\tb.solidifier = causalordersync.New(\n\t\t\t\tb.workerPool,\n\t\t\t\tb.Block,\n\t\t\t\t(*blockdag.Block).IsSolid,\n\t\t\t\tb.markSolid,\n\t\t\t\tb.markInvalid,\n\t\t\t\t(*blockdag.Block).Parents,\n\t\t\t\tcausalordersync.WithReferenceValidator[models.BlockID](checkReference),\n\t\t\t)\n\n\t\t\tevictionState.Events.SlotEvicted.Hook(b.evictSlot /*, event.WithWorkerPool(b.workerPool)*/)\n\t\t},\n\t\t(*BlockDAG).TriggerConstructed,\n\t\t(*BlockDAG).TriggerInitialized,\n\t)\n}", "func ECBEncrypt(data []byte, key []byte) ([]byte, error) {\n\n\taesCipher, err := aes.NewCipher(key) // aes aesCipher\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockSize := aesCipher.BlockSize() // block size\n\tdata = Pad(blockSize, data) // pad the data\n\tcrypt := make([]byte, len(data)) // encrypted byte array storage\n\n\t// ECB mode, encrypt each block in data\n\tfor i := 0; i < len(data); i += blockSize {\n\t\taesCipher.Encrypt(crypt[i:i+blockSize], data[i:i+blockSize])\n\t}\n\n\t// fully encrypted data\n\treturn crypt, nil\n}", "func New(protocol *protocol.Protocol, localIdentity *identity.LocalIdentity, opts ...options.Option[BlockIssuer]) *BlockIssuer {\n\treturn options.Apply(&BlockIssuer{\n\t\tEvents: NewEvents(),\n\t\tidentity: localIdentity,\n\t\tprotocol: protocol,\n\t\tworkerPool: protocol.Workers.CreatePool(\"BlockIssuer\", 2),\n\t}, opts, func(i *BlockIssuer) {\n\t\ti.referenceProvider = blockfactory.NewReferenceProvider(protocol, i.optsTimeSinceConfirmationThreshold, func() slot.Index {\n\t\t\treturn protocol.Engine().Storage.Settings.LatestCommitment().Index()\n\t\t})\n\n\t\ti.Factory = blockfactory.NewBlockFactory(\n\t\t\tlocalIdentity,\n\t\t\tprotocol.SlotTimeProvider,\n\t\t\tfunc(blockID models.BlockID) (block *blockdag.Block, exists bool) {\n\t\t\t\treturn i.protocol.Engine().Tangle.BlockDAG().Block(blockID)\n\t\t\t},\n\t\t\tfunc(countParents int) (parents models.BlockIDs) {\n\t\t\t\treturn i.protocol.TipManager.Tips(countParents)\n\t\t\t},\n\t\t\ti.referenceProvider.References,\n\t\t\tfunc() (ecRecord *commitment.Commitment, lastConfirmedSlotIndex slot.Index, err error) {\n\t\t\t\tlatestCommitment := i.protocol.Engine().Storage.Settings.LatestCommitment()\n\t\t\t\tconfirmedSlotIndex := i.protocol.Engine().Storage.Settings.LatestConfirmedSlot()\n\n\t\t\t\treturn latestCommitment, confirmedSlotIndex, nil\n\t\t\t},\n\t\t\ti.optsBlockFactoryOptions...)\n\t}, (*BlockIssuer).setupEvents)\n}", "func New(c cipher.Block) (hash.Hash,error) {\n\treturn hafuN(c)\n}", "func (I *Blockchain) NewBlock(proof uint64, previousHash string) {\n\t// In order to be able to create the first block\n\tif previousHash == \"\" {\n\t\tpreviousHash = \"1\"\n\t}\n\t// Create the block\n\tb := block{\n\t\tindex: I.currentIndex,\n\t\ttimestamp: time.Now().UnixNano(),\n\t\tproof: proof,\n\t\tpreviousHash: previousHash,\n\t\ttransactions: I.currentTransactions,\n\t}\n\t// Append the new block\n\tI.blocks = append(I.blocks, b)\n\t// Reset the transactions\n\tI.currentTransactions = make([]transaction, 0)\n\t// Update the index\n\tI.currentIndex += 1\n\t// Modify the last block variable\n\tI.lastBlock = b\n}", "func New(key []byte, alg func([]byte) (cipher.Block, error)) (cipher.AEAD, error) {\n\tmac, err := alg(key[:(len(key) / 2)])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenc, err := alg(key[(len(key) / 2):])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &siv{\n\t\tenc: enc,\n\t\tmac: mac,\n\t}, nil\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func decryptECB(dst, src, key []byte) {\n\tc, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor i := 0; i < len(src); i += c.BlockSize() {\n\t\tc.Decrypt(dst[i:i+c.BlockSize()], src[i:i+c.BlockSize()])\n\t}\n}", "func NewCipher(nonce, key []byte) (cipher.Stream, error) {\n\treturn chacha.NewCipher(nonce, key, 20)\n}", "func (b *BlockStruct) EncryptBlock() string {\n\tbyteblock, _ := globalPkg.ConvetToByte(*b, \"Block create block package\")\n\tstringblock := string(byteblock)\n\tencryptedblock := cryptogrpghy.AESEncrypt(constants.ENCRYPT_KEY, stringblock)\n\treturn encryptedblock\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func (x *ecbEncrypter) BlockSize() int { return x.blockSize }", "func Encrypt_ECB_PKCS7(key []byte, plainText []byte) []byte {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tnewPlainText := []byte(pkcs7.Pad(string(plainText), block.BlockSize()))\t\n\tcipherText := make([]byte, len(newPlainText))\n\n\tblockSize := block.BlockSize()\n\tfor i := 0; i < len(cipherText); i += blockSize {\n\t\tblock.Encrypt(cipherText[ i : i + blockSize],\n\t\t\t newPlainText[i : i + blockSize])\n\t}\n\n\treturn cipherText\n}", "func NewCipher(key []byte) (cipher.Block, error) {\r\n\tk := len(key)\r\n\tswitch k {\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"sm4: invalid key size %d\", k)\r\n\tcase 16:\r\n\t\tbreak\r\n\t}\r\n\treturn newCipher(key)\r\n}", "func newBlock(prevHash [32]byte, prevHashWithoutTx [32]byte, commitmentProof [crypto.COMM_PROOF_LENGTH]byte, height uint32) *protocol.Block {\n\tblock := new(protocol.Block)\n\tblock.PrevHash = prevHash\n\tblock.PrevHashWithoutTx = prevHashWithoutTx\n\tblock.CommitmentProof = commitmentProof\n\tblock.Height = height\n\tblock.StateCopy = make(map[[32]byte]*protocol.Account)\n\tblock.Aggregated = false\n\n\treturn block\n}", "func NewBlock(index uint64, ordered Events) *Block {\n\tevents := make(hash.EventsSlice, len(ordered))\n\tfor i, e := range ordered {\n\t\tevents[i] = e.Hash()\n\t}\n\n\treturn &Block{\n\t\tIndex: index,\n\t\tEvents: events,\n\t}\n}", "func NewBackendBlock(meta *backend.BlockMeta, r backend.Reader) (*BackendBlock, error) {\n\tencoding, err := FromVersion(meta.Version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &BackendBlock{\n\t\tencoding: encoding,\n\t\tmeta: meta,\n\t\treader: r,\n\t}, nil\n}", "func NewBlock(filename string, blockNum int) *Block {\n\treturn &Block{FileName: filename, BlockNum: blockNum}\n}", "func NewBlock(filename string, blknum uint64) *Block {\n\treturn &Block{\n\t\tfilename: filename,\n\t\tblknum: blknum,\n\t}\n}", "func DetectECB(blockSize int, ct []byte) bool {\n\n\ttopRank := 0 // rank is the highest count of repeating blocks for a tested offset\n\n\t// determine rank for each offset up to blockSize\n\tfor i := 0; i < blockSize; i++ {\n\t\t// unique block counts are saved as strings, int pairs in a map\n\t\tblockCount := make(map[string]int)\n\n\t\t// enumerate through blocks and save in map\n\t\tfor j := i; j <= len(ct)-blockSize; j += blockSize {\n\t\t\tblockCount[string(ct[j:j+blockSize])] += 1\n\t\t}\n\n\t\t// determine rank for test\n\t\trank := 0\n\t\tfor block := range blockCount {\n\t\t\tif blockCount[block] > 1 {\n\t\t\t\trank += blockCount[block] - 1\n\t\t\t}\n\t\t}\n\n\t\t// update top rank\n\t\tif rank > topRank {\n\t\t\ttopRank = rank\n\t\t}\n\t}\n\n\t// increase threshold for longer data sizes\n\tthreshold := 0\n\tif float64(len(ct)) > math.Sqrt(math.Pow(2, float64(blockSize))) {\n\t\tthreshold = 1 // not a very adaptive method\n\t}\n\n\t// compare rank to threshold\n\treturn topRank > threshold\n}", "func queryBlockEnc(blockStr string, prefix int64, blockId int) QueryBlockCipher {\n\tvar ret QueryBlockCipher\n\texp := getHashedValue(blockStr, prefix, blockId) // get the hash value in power part of ciphertext\n\tsubIndex, _ := strconv.Atoi(new(big.Int).Mod(exp, big.NewInt(subIndexSize)).String()) // calculate the sub-index value (G_k mod subIndexSize)\n\tret.subIndex = uint8(subIndex)\n\n\t// generate the ciphertext\n\tret.cipher = exp.Bytes()\n\treturn ret\n}", "func (x *ecbDecrypter) BlockSize() int { return x.blockSize }", "func TestCBCEncAble(t *testing.T) {\n\tb := cipher.Block(&testBlock{})\n\tif _, ok := b.(cbcEncAble); !ok {\n\t\tt.Fatalf(\"testBlock does not implement the cbcEncAble interface\")\n\t}\n\tbm := cipher.NewCBCEncrypter(b, []byte{})\n\tif _, ok := bm.(testInterface); !ok {\n\t\tt.Fatalf(\"cipher.NewCBCEncrypter did not use cbcEncAble interface\")\n\t}\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func EcbEncrypt(key, src []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlogx.Errorf(\"Encrypt key error: % x\", key)\n\t\treturn nil, err\n\t}\n\n\tpadded := pkcs5Padding(src, block.BlockSize())\n\tcrypted := make([]byte, len(padded))\n\tencrypter := NewECBEncrypter(block)\n\tencrypter.CryptBlocks(crypted, padded)\n\n\treturn crypted, nil\n}", "func newBlock(lastBlock Block, seed int, npeer string, transactions []SignedTransaction) Block {\n\tvar newBlock Block\n\n\tnewBlock.Seed = seed\n\tnewBlock.Index = lastBlock.Index + 1\n\tnewBlock.LastHash = lastBlock.Hash\n\tnewBlock.Peer = npeer\n\tnewBlock.SpecialAccounts = lastBlock.SpecialAccounts\n\tnewBlock.Transactions = transactions\n\tnewBlock.Hash = blockHash(newBlock)\n\treturn newBlock\n}", "func (sw *shadowsocksWriter) encryptBlock(ciphertext []byte, plaintext []byte) ([]byte, error) {\n\tout := sw.aead.Seal(ciphertext, sw.counter, plaintext, nil)\n\tincrement(sw.counter)\n\treturn out, nil\n}", "func (sw *shadowsocksWriter) encryptBlock(ciphertext []byte, plaintext []byte) ([]byte, error) {\n\tout := sw.aead.Seal(ciphertext, sw.counter, plaintext, nil)\n\tincrement(sw.counter)\n\treturn out, nil\n}", "func NewBlock(data Data, previousBlock Block, noonce string) Block {\n\tnewBlock := Block{\n\t\ttimestamp: time.Now(),\n\t\tdata: data,\n\t\tpreviousHash: previousBlock.GetHash(),\n\t\tnoonce: noonce,\n\t}\n\tnewBlock.hash()\n\n\treturn newBlock\n}", "func NewBlock(width float64, height float64) *Block {\n\tb := &Block{}\n\tb.contents = &contentstream.ContentStreamOperations{}\n\tb.resources = model.NewPdfPageResources()\n\tb.width = width\n\tb.height = height\n\treturn b\n}", "func NewEngineBTC() *Engine { return newEngine(NewGeneratorBTC()) }", "func NewCBC(\n\tkey string,\n\tencoding encodingType,\n) (AES, error) {\n\treturn NewAES(ModeCBC, key, \"\", encoding)\n}", "func CBCMode(ciphertext, key, iv string) string {\n\n\treturn \"\"\n}", "func NewCipher(key []byte) (cipher.Block, error) {\n\tif len(key) != 8 {\n\t\treturn nil, KeySizeError(len(key))\n\t}\n\n\tc := new(desCipher)\n\tc.generateSubkeys(key)\n\treturn c, nil\n}", "func NewBlock(block Block, data string) Block {\r\n\tt := time.Now().Unix()\r\n\tBlockID := block.BlockID\r\n\tBlockID++\r\n\thashed := sha256.Sum256([]byte(data))\r\n\tsignature, err := rsa.SignPKCS1v15(rand.Reader, nodeinfo.PrivateKey, crypto.SHA256, hashed[:])\r\n\tif err != nil {\r\n\t\tlog.Fatalln(err)\r\n\t}\r\n\tnonce, hash := computeHashWithProofOfWork(IntToStr(BlockID)+IntToStr(t)+data+string(signature)+nodeinfo.NodeID+block.Hash, nodeinfo.Difficulty)\r\n\treturn Block{BlockID, t, data, signature, nodeinfo.NodeID, block.Hash, hash, nonce}\r\n}", "func New() *block {\n\treturn &block{\n\t\tbroadcastChan: make(chan Message, broadcastChanSize),\n\t\tbroadcastMsgSeen: map[string]struct{}{},\n\t}\n}", "func (self *BlockChain) NewBlock(proof int, previous_hash string) {\n\n\t// check if previous hash matches self.hash(self.chain[-1])\n\tt := time.Now()\n\n\tblock := Block{\n\t\tIndex: len(self.Chain) + 1,\n\t\tTimestamp: t.UnixNano(),\n\t\tTransactions: self.CurrentTransactions,\n\t\tProof: proof,\n\t\tPreviousHash: previous_hash}\n\n\t// Reset the current list of transactions\n\tself.CurrentTransactions = nil\n\tself.Chain = append(self.Chain, block)\n}", "func (be *ContentEnc) EncryptBlock(plaintext []byte, blockNo uint64, fileID []byte) []byte {\n\t// Get a fresh random nonce\n\tnonce := be.cryptoCore.IVGenerator.Get()\n\treturn be.doEncryptBlock(plaintext, blockNo, fileID, nonce)\n}", "func NewBlockWriter(rand io.Reader, orgId, streamId uuid.UUID, salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockWriter {\n\tidx, key := 0, salt.Apply(pass, cipher.KeySize())\n\treturn BlockWriterFn(func(data []byte) (next secret.Block, err error) {\n\t\tdefer func() {\n\t\t\tidx++\n\t\t}()\n\n\t\tct, err := cipher.Apply(rand, key, data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tnext = secret.Block{orgId, streamId, idx, ct}\n\t\treturn\n\t})\n}", "func (wc *WalletClient) NewBlock(b Block) error {\n\t_, err := wc.POST(\"/new-block\", b.Json())\n\treturn err\n}", "func NewBlock(transactions []*Transaction, prevBlockHash []byte, height int) *Block {\n\tblock := &Block{time.Now().Unix(), transactions, prevBlockHash, []byte{}, 0, height}\n\tblock.POW()\n\treturn block\n}", "func New(ctx context.Context, now NowFunc) *Blockchain {\n\tvar b = Blockchain{\n\t\tnow: now,\n\t}\n\n\tgenesisBlock := Block{\n\t\t0,\n\t\tb.now().String(),\n\t\t0,\n\t\t\"\",\n\t\t\"\",\n\t}\n\n\tb.Blocks = append(b.Blocks, genesisBlock)\n\n\treturn &b\n}", "func NewBlock(transactions []*Transaction, preBlockHash []byte) *Block {\n\tb := &Block{time.Now().Unix(), transactions, preBlockHash, []byte{}, 252, 0}\n\n\tpow := NewProofOfWork(b)\n\tnonce, hash := pow.Run()\n\n\tb.Nonce = nonce\n\tb.Hash = hash[:]\n\n\treturn b\n}", "func NewORE(sk []byte) (*ORE, error) {\n\tblock, err := aes.NewCipher(sk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tecb := newECBEncrypter(block)\n\treturn &ORE{sk: sk, aes: ecb}, nil\n}", "func (ctx *DefaultContext) NewBlockchain() evm.Blockchain {\n\treturn NewBlockchain(ctx.queryEngine, ctx.channelID)\n}", "func NewFadedBlock() *FadedBlock {\n\treturn &FadedBlock{\n\t\tBlock: *termui.NewBlock(),\n\t}\n}", "func (key twofishKey) newCipher() cipher.Block {\n\tcipher, err := twofish.NewCipher(key[:])\n\tif err != nil {\n\t\tpanic(\"NewCipher only returns an error if len(key) != 16, 24, or 32.\")\n\t}\n\treturn cipher\n}", "func NewCipher(client kms.Client, kmsKeyID string) *Cipher {\n\treturn &Cipher{\n\t\tClient: client,\n\t\tKMSKeyID: kmsKeyID,\n\t}\n}", "func NewMinterBlockchain(storages *utils.Storage, cfg *config.Config, ctx context.Context, period uint64) *Blockchain {\n\t// Initiate Application DB. Used for persisting data like current block, validators, etc.\n\tapplicationDB := appdb.NewAppDB(storages.GetMinterHome(), cfg)\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tvar eventsDB eventsdb.IEventsDB\n\tif !cfg.ValidatorMode {\n\t\teventsDB = eventsdb.NewEventsStore(storages.EventDB())\n\t} else {\n\t\teventsDB = &eventsdb.MockEvents{}\n\t}\n\tconst updateStakesAndPayRewards = 720\n\tif period == 0 {\n\t\tperiod = updateStakesAndPayRewards\n\t}\n\tapp := &Blockchain{\n\t\trewardsCounter: rewards.NewReward(),\n\t\tappDB: applicationDB,\n\t\tstorages: storages,\n\t\teventsDB: eventsDB,\n\t\tcurrentMempool: &sync.Map{},\n\t\tcfg: cfg,\n\t\tstopChan: ctx,\n\t\thaltHeight: uint64(cfg.HaltHeight),\n\t\tupdateStakesAndPayRewardsPeriod: period,\n\t\tstopOk: make(chan struct{}),\n\t\tknownUpdates: map[string]struct{}{\n\t\t\t\"\": {}, // default version\n\t\t\tv230: {}, // add more for update\n\t\t\tv250: {}, // commissions and mempool\n\t\t},\n\t\texecutor: GetExecutor(\"\"),\n\t}\n\tif applicationDB.GetStartHeight() != 0 {\n\t\tapp.initState()\n\t}\n\treturn app\n}", "func NewGenesisBlock() *Block {\n\tidea := &Idea{Text: \"Create IdeaBlox\", Author: \"aakarim\"}\n\tout, err := proto.Marshal(idea)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn NewBlock(out, []byte{})\n}", "func NewBlock(data string, prevBlockHash []byte) *Block {\n\tblock := &Block{time.Now().Unix(), []byte(data), prevBlockHash, []byte{}, 0}\n\tpow := NewProofOfWork(block)\n\n\tnonce, hash := pow.Run()\n\n\tblock.Hash = hash[:]\n\tblock.Nonce = nonce\n\n\treturn block\n}", "func NewCryptoReader(ctx *Context, r io.Reader) io.Reader {\n\t// At the beginning of the reader must be the unencrypted IV to use.\n\tiv := make([]byte, aes.BlockSize)\n\n\tif _, err := io.ReadFull(r, iv); nil != err {\n\t\tlog.Panicf(\"Failed to read IV from file: %v\", err)\n\t}\n\n\t// Create a new AES block cipher and init the output feedback mode stream, then copy the archived file.\n\tblockCipher, err := aes.NewCipher(ctx.getKey())\n\n\tif nil != err {\n\t\tlog.Panicf(\"Failed to create AES block cipher: %v\", err)\n\t}\n\n\tstream := cipher.NewOFB(blockCipher, iv)\n\n\tdecryptingReader := &cipher.StreamReader{\n\t\tS: stream,\n\t\tR: r,\n\t}\n\n\treturn decryptingReader\n}", "func ECBOrCBCEncryption(inputData []byte) ([]byte, int) {\n\trand.Seed(time.Now().UTC().UnixNano())\n\tkey := RandomBytes(aes.BlockSize)\n\t// Append bytes to the beginning.\n\tinputData = append(RandomBytes(rand.Intn(6)+5), inputData...)\n\t// Append bytes to the end.\n\tinputData = append(inputData, RandomBytes(rand.Intn(6)+5)...)\n\tif rand.Intn(2) == 1 {\n\t\tc := NewAESCBC(key, nil)\n\t\treturn c.Encrypt(inputData), 1\n\t}\n\te := NewAESECB(key)\n\treturn e.Encrypt(inputData), 0\n}", "func NewBlock(data *models.Block, opts ...options.Option[Block]) (newBlock *Block) {\n\treturn options.Apply(&Block{\n\t\tstrongChildren: make([]*Block, 0),\n\t\tweakChildren: make([]*Block, 0),\n\t\tlikedInsteadChildren: make([]*Block, 0),\n\t\tModelsBlock: data,\n\t}, opts)\n}", "func indexBlockEnc(block int64, prefix int64, blockId int, gamma []byte) IndexBlockCipher {\n\tvar (\n\t\tret IndexBlockCipher\n\t\ti int64\n\t\tsubIndexPos []int = make([]int, subIndexSize) // the next available space of each sub-index's list\n\t\tcipherPos int = 0 // the next available space of ciphertext list\n\t)\n\n\tfor i = 0; i < subIndexSize; i++ {\n\t\tsubIndexPos[i] = 0\n\t}\n\n\tfor i = 0; i < subIndexSize; i++ { // initialize the tag list with 100 (one value out of range, i.e. no block's id is 100)\n\t\tfor j := 0; j < int(subIndexSize); j++ {\n\t\t\tret.subIndex[i][j] = 100\n\t\t}\n\t}\n\n\tfor i = 0; i < blockPossValue; i++ {\n\t\tif i == block { // do not encrypt the equal block\n\t\t\tcontinue\n\t\t} else if i < block { // the current variable is smaller than the current block\n\t\t\tiStr := strconv.FormatInt(i, 10) + \">\"\n\t\t\texp := getHashedValue(iStr, prefix, blockId) // get the hash value in power part of ciphertext\n\n\t\t\t// calculate the sub-index value (G_k mod subIndexSize)\n\t\t\tsubIndex, _ := strconv.Atoi(new(big.Int).Mod(exp, big.NewInt(subIndexSize)).String())\n\t\t\tret.subIndex[subIndex][subIndexPos[subIndex]] = uint8(cipherPos)\n\t\t\tsubIndexPos[subIndex]++\n\n\t\t\t// generate the ciphertext\n\t\t\tret.ciphers[cipherPos] = F(exp, gamma)\n\t\t\tcipherPos++\n\t\t} else { // the current variable is larger than the current block (the process procedure is similar)\n\t\t\tiStr := strconv.FormatInt(i, 10) + \"<\"\n\t\t\texp := getHashedValue(iStr, prefix, blockId) // get the hash value in power part of ciphertext\n\n\t\t\t// calculate the sub-index value (G_k mod subIndexSize)\n\t\t\tsubIndex, _ := strconv.Atoi(new(big.Int).Mod(exp, big.NewInt(subIndexSize)).String())\n\t\t\tret.subIndex[subIndex][subIndexPos[subIndex]] = uint8(cipherPos)\n\t\t\tsubIndexPos[subIndex]++\n\n\t\t\t// generate the ciphertext\n\t\t\tret.ciphers[cipherPos] = F(exp, gamma)\n\t\t\tcipherPos++\n\t\t}\n\t}\n\treturn ret\n}", "func NewEncryptionEngine(kekName string, wDekPathName string, gcpClient registry.KMSClient, logger *logrus.Logger) *EncryptionEngine {\n\treturn &EncryptionEngine{\n\t\tkekName: kekName,\n\t\twDekPathName: wDekPathName,\n\t\tgcpClient: gcpClient,\n\t\tlogger: logger,\n\t}\n}", "func NewBlock(index idx.Block, time Timestamp, events hash.Events, prevHash hash.Event) *Block {\n\treturn &Block{\n\t\tIndex: index,\n\t\tTime: time,\n\t\tEvents: events,\n\t\tPrevHash: prevHash,\n\t\tSkippedTxs: make([]uint, 0),\n\t}\n}" ]
[ "0.8417233", "0.80440867", "0.7977088", "0.7953862", "0.7821148", "0.7765819", "0.7765819", "0.7765819", "0.7765819", "0.7765819", "0.7417846", "0.72698236", "0.71840376", "0.71840376", "0.71840376", "0.71840376", "0.71840376", "0.62585706", "0.6083144", "0.6078734", "0.59571826", "0.58966786", "0.57839763", "0.57563806", "0.57454914", "0.57438755", "0.55936205", "0.5561343", "0.54590046", "0.53799504", "0.53663707", "0.5362937", "0.53422785", "0.5283655", "0.5249574", "0.52483726", "0.5233217", "0.5222561", "0.5209145", "0.5170467", "0.51615494", "0.5141917", "0.51257414", "0.510251", "0.50910705", "0.5073882", "0.5059106", "0.5045952", "0.50392145", "0.5022956", "0.50215614", "0.5013328", "0.49993163", "0.49953905", "0.4990709", "0.49896672", "0.49735698", "0.49633467", "0.49603978", "0.49188387", "0.49187124", "0.4908895", "0.49034774", "0.49014685", "0.49009123", "0.48970383", "0.48902768", "0.48819777", "0.48807928", "0.48781735", "0.48781735", "0.48512688", "0.48427334", "0.48413813", "0.48399836", "0.48388317", "0.48162374", "0.4792658", "0.47922572", "0.479011", "0.47818828", "0.47788092", "0.47778183", "0.4766495", "0.47664267", "0.47635186", "0.47616538", "0.47576645", "0.474372", "0.47433454", "0.47404265", "0.473067", "0.4723106", "0.4716038", "0.47054586", "0.47016093", "0.47005478", "0.46892437", "0.46891907", "0.467839" ]
0.7868233
4
NewECBDecrypter returns a BlockMode which decrypts in electronic code book mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode { return (*ecbDecrypter)(newECB(b)) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n return (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(block cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(block))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBDecrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbDecrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n return (*ecbEncrypter)(newECB(b))\n}", "func newECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(c cipher.Block) cipher.BlockMode {\n\treturn ecbEncrypter{c}\n}", "func NewECBEncrypter(block cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(block))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\r\n\treturn (*ecbEncrypter)(newECB(b))\r\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func NewECBEncrypter(b cipher.Block) cipher.BlockMode {\n\treturn (*ecbEncrypter)(newECB(b))\n}", "func DecryptECB(ciphertext []byte, key []byte) ([]byte, error) {\r\n\r\n\t// 1. Check if ciphertext is a multiple of 16\r\n\tif len(ciphertext)%16 != 0 {\r\n\t\treturn nil, fmt.Errorf(\"ciphertext is %d bytes which is not \"+\r\n\t\t\t\"a multiple of 16.\", len(ciphertext))\r\n\t}\r\n\r\n\t// 2. Check if key and 16 are of same length\r\n\tif len(key) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"key has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(key))\r\n\t}\r\n\r\n\t// 3. Get an AES block\r\n\tblock, err := aes.NewCipher(key)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tplaintext := make([]byte, len(ciphertext))\r\n\r\n\tfor i := 0; i < len(ciphertext); i += 16 {\r\n\t\tblock.Decrypt(plaintext[i:i+16], ciphertext[i:i+16])\r\n\t}\r\n\r\n\treturn plaintext, nil\r\n}", "func decryptECB(data, key []byte) (decryptedData []byte, err error) {\n\taesCrypt, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdecryptedData = make([]byte, len(data))\n\taesCrypt.Decrypt(decryptedData, data)\n\n\treturn\n}", "func (cipher CipherFunction) New(key []byte) (block cipher.Block) {\n\tvar err error\n\tswitch cipher {\n\tcase TripleDES:\n\t\tblock, err = des.NewTripleDESCipher(key)\n\tcase CAST5:\n\t\tblock, err = cast5.NewCipher(key)\n\tcase AES128, AES192, AES256:\n\t\tblock, err = aes.NewCipher(key)\n\t}\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn\n}", "func (be *ContentEnc) DecryptBlock(ciphertext []byte, blockNo uint64, fileID []byte) ([]byte, error) {\n\n\t// Empty block?\n\tif len(ciphertext) == 0 {\n\t\treturn ciphertext, nil\n\t}\n\n\t// All-zero block?\n\tif bytes.Equal(ciphertext, be.allZeroBlock) {\n\t\ttlog.Debug.Printf(\"DecryptBlock: file hole encountered\")\n\t\treturn make([]byte, be.plainBS), nil\n\t}\n\n\tif len(ciphertext) < be.cryptoCore.IVLen {\n\t\ttlog.Warn.Printf(\"DecryptBlock: Block is too short: %d bytes\", len(ciphertext))\n\t\treturn nil, errors.New(\"Block is too short\")\n\t}\n\n\t// Extract nonce\n\tnonce := ciphertext[:be.cryptoCore.IVLen]\n\tif bytes.Equal(nonce, be.allZeroNonce) {\n\t\t// Bug in tmpfs?\n\t\t// https://github.com/rfjakob/gocryptfs/issues/56\n\t\t// http://www.spinics.net/lists/kernel/msg2370127.html\n\t\treturn nil, errors.New(\"all-zero nonce\")\n\t}\n\tciphertextOrig := ciphertext\n\tciphertext = ciphertext[be.cryptoCore.IVLen:]\n\n\t// Decrypt\n\tvar plaintext []byte\n\taData := make([]byte, 8)\n\taData = append(aData, fileID...)\n\tbinary.BigEndian.PutUint64(aData, blockNo)\n\tplaintext, err := be.cryptoCore.AEADCipher.Open(plaintext, nonce, ciphertext, aData)\n\n\tif err != nil {\n\t\ttlog.Warn.Printf(\"DecryptBlock: %s, len=%d\", err.Error(), len(ciphertextOrig))\n\t\ttlog.Debug.Println(hex.Dump(ciphertextOrig))\n\t\tif be.forceDecode && err == stupidgcm.ErrAuth {\n\t\t\treturn plaintext, err\n\t\t}\n\t\treturn nil, err\n\t}\n\n\treturn plaintext, nil\n}", "func decryptECB(dst, src, key []byte) {\n\tc, err := twofish.NewCipher(key)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfor i := 0; i < len(src); i += c.BlockSize() {\n\t\tc.Decrypt(dst[i:i+c.BlockSize()], src[i:i+c.BlockSize()])\n\t}\n}", "func AESDecryptWithECB(cryptStr, key []byte) ([]byte, error) {\n\tcb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tmode := newECBDecrypter(cb)\n\tdata := make([]byte, len(cryptStr))\n\tmode.CryptBlocks(data, cryptStr)\n\td := pkcs5UnPadding(data)\n\treturn d, nil\n}", "func ECBDecrypt(crypt []byte, key []byte) ([]byte, error) {\n\n\taesCipher, err := aes.NewCipher(key) // aes aesCipher\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockSize := aesCipher.BlockSize() // block size\n\tdata := make([]byte, len(crypt)) // data storage array\n\n\t// ECB mode, decrypt each block in data\n\tfor i := 0; i < len(crypt); i += blockSize {\n\t\taesCipher.Decrypt(data[i:i+blockSize], crypt[i:i+blockSize])\n\t}\n\n\t// remove pad from the decrypted data and return\n\treturn UnPad(data)\n}", "func NewECBEncryptionOracle(prepend, unknownString []byte) ECBEncryptionOracle {\n\ta := NewAESECB(nil)\n\tif prepend == nil {\n\t\tprepend = RandomBytes(rand.Intn(50) + 1)\n\t}\n\treturn ECBEncryptionOracle{a, prepend, unknownString}\n}", "func NewDecrypter(kd KeyDescriptor) (Decrypter, error) {\n\treturn newEngine(kd)\n}", "func NewBlockReader(salt crypto.Salt, pass []byte, cipher crypto.Cipher) BlockReader {\n\tkey := salt.Apply(pass, cipher.KeySize())\n\treturn BlockReaderFn(func(b secret.Block) ([]byte, error) {\n\t\treturn b.Decrypt(key)\n\t})\n}", "func ecbModeOracle(c cipher.Block) (func([]byte) []byte, cipher.BlockMode) {\n\tvar mode cipher.BlockMode\n\tif weak.Intn(2) == 0 {\n\t\tmode = NewECBEncrypter(c)\n\t} else {\n\t\tmode = cipher.NewCBCEncrypter(c, RandomBytes(c.BlockSize()))\n\t}\n\tprefix := RandomBytes(RandomInRange(5, 10))\n\tsuffix := RandomBytes(RandomInRange(5, 10))\n\treturn func(buf []byte) []byte {\n\t\tbuf = append(prefix, append(buf, suffix...)...)\n\t\tbuf = PKCS7Pad(buf, mode.BlockSize())\n\t\tmode.CryptBlocks(buf, buf)\n\t\treturn buf\n\t}, mode\n}", "func newBlockCipher(key string) (cipher.Block, error) {\n\n\thash := md5.New()\n\tfmt.Fprint(hash, key)\n\tcipherKey := hash.Sum(nil)\n\treturn aes.NewCipher(cipherKey)\n}", "func NewCipher(key []byte) (cipher.Block, error) {}", "func NewCipher(key []byte) cipher.Block {\n\texpkey := keyExpansion(key)\n\treturn cipherAES{expkey}\n}", "func aesDecryptBlock(key, ciphertext []byte) [16]byte {\n\tif len(key) != 16 {\n\t\t// assertion\n\t\tpanic(\"key has wrong length\")\n\t}\n\tif len(ciphertext) != 16 {\n\t\t// assertion\n\t\tpanic(\"ciphertext has wrong length\")\n\t}\n\n\tcipher, err := aes.NewCipher(key)\n\tif err != nil {\n\t\t// assertion\n\t\tpanic(fmt.Sprintf(\"Unexpected error during aes.NewCipher: %v\", err))\n\t}\n\n\tvar plaintext [16]byte\n\tcipher.Decrypt(plaintext[:], ciphertext)\n\treturn plaintext\n}", "func NewDecryptor(ctx *FVContext, secretkey *SecretKey) *Decryptor {\n\tdecryptor := new(Decryptor)\n\tdecryptor.ctx = ctx\n\tdecryptor.secretkey = secretkey\n\treturn decryptor\n}", "func ECBDecrypt(k, encrypted []byte) ([]byte, error) {\n\tcipher, err := aes.NewCipher(k)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(encrypted)%aes.BlockSize != 0 {\n\t\treturn nil, err\n\t}\n\tdecrypted := make([]byte, len(encrypted))\n\tsize := 16\n\n\tfor bs, be := 0, size; bs < len(encrypted); bs, be = bs+size, be+size {\n\t\tcipher.Decrypt(decrypted[bs:be], encrypted[bs:be])\n\t}\n\n\treturn decrypted, nil\n}", "func initBlock() (cipher.Block, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif block == nil {\n\t\treturn nil, fmt.Errorf(\"Uninitialized Cipher Block\")\n\t}\n\n\treturn block, nil\n}", "func Decrypt(key, nonce, data []byte, mode MODE) ([]byte, error) {\n\tif len(data) < aes.BlockSize {\n\t\treturn nil, ErrShortData\n\t}\n\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tv := data[:aes.BlockSize]\n\n\tvar raw []byte\n\tif mode == MODEGCM {\n\t\traw = nil // make([]byte, len(data)-16)\n\t} else {\n\t\traw = make([]byte, len(data)-aes.BlockSize)\n\t}\n\n\tswitch mode {\n\tcase MODECBC:\n\t\tif len(data)%aes.BlockSize != 0 {\n\t\t\treturn nil, errors.New(\"cbc: data is not a multiple of the block size\")\n\t\t}\n\n\t\tcbcMode := cipher.NewCBCDecrypter(block, v)\n\t\tcbcMode.CryptBlocks(raw, data[aes.BlockSize:])\n\t\treturn raw, nil\n\n\tcase MODECFB:\n\t\tmodeCFB := cipher.NewCFBDecrypter(block, v)\n\t\tmodeCFB.XORKeyStream(raw, data[aes.BlockSize:])\n\t\tdata = nil\n\t\treturn raw, nil\n\n\tcase MODECTR:\n\t\tmodeCTR := cipher.NewCTR(block, v)\n\t\tmodeCTR.XORKeyStream(raw, data[aes.BlockSize:])\n\t\tdata = nil\n\t\treturn raw, nil\n\n\tcase MODEOFB: // OFB\n\t\tmodeOFB := cipher.NewOFB(block, v)\n\t\tmodeOFB.XORKeyStream(raw, data[aes.BlockSize:])\n\t\tdata = nil\n\t\treturn raw, nil\n\n\tcase MODEGCM:\n\t\taesGCM, err := cipher.NewGCM(block)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tret, err := aesGCM.Open(nil, nonce, data, nil)\n\t\tif err != nil {\n\t\t\tdata = nil\n\t\t\treturn nil, err\n\t\t}\n\t\tdata = nil\n\t\treturn ret, nil\n\n\tdefault:\n\t\treturn nil, ErrInvalidMode\n\t}\n\n}", "func EncryptECB(plaintext []byte, key []byte) ([]byte, error) {\r\n\r\n\t// 1. Check if plaintext is a multiple of 16\r\n\tif len(plaintext)%16 != 0 {\r\n\t\treturn nil, fmt.Errorf(\"plaintext is %d bytes which is not \"+\r\n\t\t\t\"a multiple of 16.\", len(plaintext))\r\n\t}\r\n\r\n\t// 2. Check if key and 16 are of same length\r\n\tif len(key) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"key has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(key))\r\n\t}\r\n\r\n\t// 3. Get an AES block\r\n\tblock, err := aes.NewCipher(key)\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\r\n\tciphertext := make([]byte, len(plaintext))\r\n\r\n\t// 4. Encrypt each block individually and store\r\n\tfor i := 0; i < len(plaintext); i += 16 {\r\n\t\tblock.Encrypt(ciphertext[i:i+16], plaintext[i:i+16])\r\n\t}\r\n\r\n\treturn ciphertext, nil\r\n}", "func NewDecrypter(r io.Reader, password []byte) (io.ReadCloser, error) {\n\tversion, err := readVersion(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecrypterFn, ok := decrypters[version]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unknown decrypter for version(%d)\", version)\n\t}\n\treturn decrypterFn(r, password)\n}", "func EcbDecrypt(key, src []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlogx.Errorf(\"Decrypt key error: % x\", key)\n\t\treturn nil, err\n\t}\n\n\tdecrypter := NewECBDecrypter(block)\n\tdecrypted := make([]byte, len(src))\n\tdecrypter.CryptBlocks(decrypted, src)\n\n\treturn pkcs5Unpadding(decrypted, decrypter.BlockSize())\n}", "func NewCipher(key []byte) (cipher.Block, error) {\n\tif len(key) != 8 {\n\t\treturn nil, KeySizeError(len(key))\n\t}\n\n\tc := new(desCipher)\n\tc.generateSubkeys(key)\n\treturn c, nil\n}", "func NewDecrypter(password []byte) (*Decrypter, error) {\n\tif len(password) == 0 {\n\t\treturn nil, fmt.Errorf(\"NewDecrypter cannot have empty password\")\n\t}\n\n\treturn &Decrypter{password, make(map[[saltLen]byte]*xts.Cipher)}, nil\n}", "func TestCbcDecrypter(t *testing.T) {\n\tvar key = []byte{'Y', 'E', 'L', 'L', 'O', 'W', ' ', 'S', 'U', 'B', 'M', 'A', 'R', 'I', 'N', 'E'}\n\tvar cp, _ = aes.NewCipher(key)\n\tvar iv = make([]byte, cp.BlockSize()) // all zero iv\n\tvar cbc = NewCBCDecrypter(cp, iv)\n\n\tvar src, _ = ioutil.ReadFile(\"10.txt\")\n\tsrc, _ = basics.DecodeBase64(src)\n\tvar dst = make([]byte, len(src))\n\tcbc.CryptBlocks(dst, src)\n\n\tt.Logf(\"got:\\n%s\", hex.Dump(dst))\n}", "func NewDecrypter(keys *EEK) (Decrypter, error) {\n\tgcmCipher, err := newGCMCipher(keys.AESKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &decrypter{\n\t\tgcmCipher: gcmCipher,\n\t\tpageIVMAC: hmac.New(sha256.New, keys.PageIVSeed),\n\t}, nil\n}", "func TestCBCDecAble(t *testing.T) {\n\tb := cipher.Block(&testBlock{})\n\tif _, ok := b.(cbcDecAble); !ok {\n\t\tt.Fatalf(\"testBlock does not implement the cbcDecAble interface\")\n\t}\n\tbm := cipher.NewCBCDecrypter(b, []byte{})\n\tif _, ok := bm.(testInterface); !ok {\n\t\tt.Fatalf(\"cipher.NewCBCDecrypter did not use cbcDecAble interface\")\n\t}\n}", "func IsECB(ciphertext []byte) (bool, error) {\r\n\r\n\tif len(ciphertext)%16 != 0 {\r\n\t\treturn false, fmt.Errorf(\"ciphertext is not a multiple of %d\", 16)\r\n\t}\r\n\r\n\t// Split into 16 byte\r\n\tsplits := SplitBytes(ciphertext, 16)\r\n\r\n\tcount := 0\r\n\r\n\t// Calculate the number of occurrences-1\r\n\tfor _, block := range splits {\r\n\t\tcount += (bytes.Count(ciphertext, block) - 1)\r\n\t}\r\n\r\n\tif count > 1 {\r\n\t\treturn true, nil\r\n\t}\r\n\r\n\treturn false, nil\r\n}", "func NewCryptoReader(ctx *Context, r io.Reader) io.Reader {\n\t// At the beginning of the reader must be the unencrypted IV to use.\n\tiv := make([]byte, aes.BlockSize)\n\n\tif _, err := io.ReadFull(r, iv); nil != err {\n\t\tlog.Panicf(\"Failed to read IV from file: %v\", err)\n\t}\n\n\t// Create a new AES block cipher and init the output feedback mode stream, then copy the archived file.\n\tblockCipher, err := aes.NewCipher(ctx.getKey())\n\n\tif nil != err {\n\t\tlog.Panicf(\"Failed to create AES block cipher: %v\", err)\n\t}\n\n\tstream := cipher.NewOFB(blockCipher, iv)\n\n\tdecryptingReader := &cipher.StreamReader{\n\t\tS: stream,\n\t\tR: r,\n\t}\n\n\treturn decryptingReader\n}", "func New(protocol *protocol.Protocol, localIdentity *identity.LocalIdentity, opts ...options.Option[BlockIssuer]) *BlockIssuer {\n\treturn options.Apply(&BlockIssuer{\n\t\tEvents: NewEvents(),\n\t\tidentity: localIdentity,\n\t\tprotocol: protocol,\n\t\tworkerPool: protocol.Workers.CreatePool(\"BlockIssuer\", 2),\n\t}, opts, func(i *BlockIssuer) {\n\t\ti.referenceProvider = blockfactory.NewReferenceProvider(protocol, i.optsTimeSinceConfirmationThreshold, func() slot.Index {\n\t\t\treturn protocol.Engine().Storage.Settings.LatestCommitment().Index()\n\t\t})\n\n\t\ti.Factory = blockfactory.NewBlockFactory(\n\t\t\tlocalIdentity,\n\t\t\tprotocol.SlotTimeProvider,\n\t\t\tfunc(blockID models.BlockID) (block *blockdag.Block, exists bool) {\n\t\t\t\treturn i.protocol.Engine().Tangle.BlockDAG().Block(blockID)\n\t\t\t},\n\t\t\tfunc(countParents int) (parents models.BlockIDs) {\n\t\t\t\treturn i.protocol.TipManager.Tips(countParents)\n\t\t\t},\n\t\t\ti.referenceProvider.References,\n\t\t\tfunc() (ecRecord *commitment.Commitment, lastConfirmedSlotIndex slot.Index, err error) {\n\t\t\t\tlatestCommitment := i.protocol.Engine().Storage.Settings.LatestCommitment()\n\t\t\t\tconfirmedSlotIndex := i.protocol.Engine().Storage.Settings.LatestConfirmedSlot()\n\n\t\t\t\treturn latestCommitment, confirmedSlotIndex, nil\n\t\t\t},\n\t\t\ti.optsBlockFactoryOptions...)\n\t}, (*BlockIssuer).setupEvents)\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\treturn &Block{\n\t\tHead: NewBlockHeader(prev.Head, uxHash, currentTime, fee, body),\n\t\tBody: body,\n\t}, nil\n}", "func (c CryptoCommon) DecryptBlock(\n\tencryptedBlock kbfscrypto.EncryptedBlock,\n\ttlfCryptKey kbfscrypto.TLFCryptKey,\n\tblockServerHalf kbfscrypto.BlockCryptKeyServerHalf, block data.Block) error {\n\tvar paddedBlock []byte\n\tpaddedBlock, err := kbfscrypto.DecryptBlock(\n\t\tencryptedBlock, tlfCryptKey, blockServerHalf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tencodedBlock, err := kbfscrypto.DepadBlock(paddedBlock)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = c.codec.Decode(encodedBlock, &block)\n\tif err != nil {\n\t\treturn errors.WithStack(BlockDecodeError{err})\n\t}\n\treturn nil\n}", "func NewBlock(oldBlock Block, data string) Block {\n\t// fmt.Println(\"******TODO: IMPLEMENT NewBlock!******\")\n\tblock := Block{Data: data, Timestamp: time.Now().Unix(), PrevHash: oldBlock.Hash, Hash: []byte{}}\n\tblock.Hash = block.calculateHash()\n\t// fmt.Println(\"data: \" + block.Data)\n\t// fmt.Printf(\"timestamp: %d\", block.Timestamp)\n\t// fmt.Println()\n\t// fmt.Printf(\"preHash: %x\", block.PrevHash)\n\t// fmt.Println()\n\t// fmt.Printf(\"currentHash: %x\", block.Hash)\n\t// fmt.Println()\n\t// fmt.Println(\"******TODO: END NewBlock!******\")\n\t// fmt.Println()\n\t// fmt.Println()\n\t// fmt.Println()\n\treturn block\n}", "func NewBlock() (*Block, error) {\n\tn, err := findLast()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th, err := ftoh(n)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfmt.Println(\"Hash: \" + h)\n\n\treturn &Block{Number: n + 1, PreviousHash: h}, nil\n}", "func NewBlock(prev Block, currentTime uint64, uxHash cipher.SHA256, txns Transactions, calc FeeCalculator) (*Block, error) {\n\tif len(txns) == 0 {\n\t\treturn nil, fmt.Errorf(\"Refusing to create block with no transactions\")\n\t}\n\n\tfee, err := txns.Fees(calc)\n\tif err != nil {\n\t\t// This should have been caught earlier\n\t\treturn nil, fmt.Errorf(\"Invalid transaction fees: %v\", err)\n\t}\n\n\tbody := BlockBody{txns}\n\thead := NewBlockHeader(prev.Head, uxHash, currentTime, fee, body)\n\treturn &Block{\n\t\tHead: head,\n\t\tBody: body,\n\t}, nil\n}", "func (x *ecbDecrypter) BlockSize() int { return x.blockSize }", "func (decryptor *PgDecryptor) DecryptBlock(block []byte) ([]byte, error) {\n\tctx := decryptor.dataProcessorContext.UseZoneID(decryptor.GetMatchedZoneID())\n\tctx.WithZone = decryptor.IsWithZone()\n\tdecrypted, err := decryptor.dataProcessor.Process(block, ctx)\n\tif err == nil {\n\t\treturn decrypted, nil\n\t}\n\t// avoid logging errors when block is not AcraStruct\n\tif err == base.ErrIncorrectAcraStructTagBegin {\n\t\treturn nil, errPlainData\n\t} else if err == base.ErrIncorrectAcraStructLength {\n\t\treturn nil, errPlainData\n\t}\n\treturn nil, err\n}", "func BlockSizeECB(f EncryptFunc) int {\n\tconst (\n\t\tbufLen = 1024\n\t\tminBlockSize = 4\n\t\tmaxBlockSize = bufLen / 4\n\t)\n\n\tenc := f(A(bufLen))\n\n\tfor bs := minBlockSize; bs <= maxBlockSize; bs++ {\n\t\tnumNeeded := bufLen/bs - 2 // first or last may be misaligned\n\t\tvar prevBlock []byte // last block that was seen\n\t\tblockCount := 0 // consecutive occurrences of prevBlock\n\t\tfor start := 0; start+bs < len(enc); start += bs {\n\t\t\tbl := enc[start : start+bs]\n\t\t\tif prevBlock == nil || !bytes.Equal(bl, prevBlock) {\n\t\t\t\tprevBlock = bl\n\t\t\t\tblockCount = 0\n\t\t\t} else {\n\t\t\t\tblockCount++\n\t\t\t\tif blockCount >= numNeeded {\n\t\t\t\t\treturn bs\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tpanic(\"couldn't find block size\")\n}", "func NewFadedBlock() *FadedBlock {\n\treturn &FadedBlock{\n\t\tBlock: *termui.NewBlock(),\n\t}\n}", "func NewCipher(key []byte) (cipher.Block, error) {\n\tl := len(key)\n\tif l%4 != 0 {\n\t\treturn nil, KeySizeError\n\t}\n\tc := rtea{}\n\tc.key = make([]uint32, l/4)\n\tfor i := range c.key {\n\t\tc.key[i] = enc.Uint32(key)\n\t\tkey = key[4:]\n\t}\n\n\treturn c, nil\n}", "func NewBlock(b *block.Block, chain blockchainer.Blockchainer) Block {\n\tres := Block{\n\t\tBlock: *b,\n\t\tBlockMetadata: BlockMetadata{\n\t\t\tSize: io.GetVarSize(b),\n\t\t\tConfirmations: chain.BlockHeight() - b.Index + 1,\n\t\t},\n\t}\n\n\thash := chain.GetHeaderHash(int(b.Index) + 1)\n\tif !hash.Equals(util.Uint256{}) {\n\t\tres.NextBlockHash = &hash\n\t}\n\n\treturn res\n}", "func New(workers *workerpool.Group, evictionState *eviction.State, slotTimeProviderFunc func() *slot.TimeProvider, latestCommitmentFunc func(slot.Index) (*commitment.Commitment, error), opts ...options.Option[BlockDAG]) (newBlockDAG *BlockDAG) {\n\treturn options.Apply(&BlockDAG{\n\t\tevents: blockdag.NewEvents(),\n\t\tevictionState: evictionState,\n\t\tslotTimeProviderFunc: slotTimeProviderFunc,\n\t\tmemStorage: memstorage.NewSlotStorage[models.BlockID, *blockdag.Block](),\n\t\tcommitmentFunc: latestCommitmentFunc,\n\t\tfutureBlocks: memstorage.NewSlotStorage[commitment.ID, *advancedset.AdvancedSet[*blockdag.Block]](),\n\t\tWorkers: workers,\n\t\t// do not use workerpool to make sure things run synchronously\n\t\t//workerPool: workers.CreatePool(\"Solidifier\", 2),\n\n\t}, opts,\n\t\tfunc(b *BlockDAG) {\n\t\t\tb.solidifier = causalordersync.New(\n\t\t\t\tb.workerPool,\n\t\t\t\tb.Block,\n\t\t\t\t(*blockdag.Block).IsSolid,\n\t\t\t\tb.markSolid,\n\t\t\t\tb.markInvalid,\n\t\t\t\t(*blockdag.Block).Parents,\n\t\t\t\tcausalordersync.WithReferenceValidator[models.BlockID](checkReference),\n\t\t\t)\n\n\t\t\tevictionState.Events.SlotEvicted.Hook(b.evictSlot /*, event.WithWorkerPool(b.workerPool)*/)\n\t\t},\n\t\t(*BlockDAG).TriggerConstructed,\n\t\t(*BlockDAG).TriggerInitialized,\n\t)\n}", "func NewDESCipher(mode cipherMode) Cipher {\n\tencryptor := &encryptor{\n\t\tkeylen: 8, // DES56\n\t\tblockSize: des.BlockSize,\n\t\tcipherFunc: des.NewCipher,\n\t}\n\n\treturn getCipher(mode, encryptor)\n}", "func DecryptBlock(blockNumber int) []byte {\n\tdecrypted := make([]byte, BlockSize)\n\t// Decrypt bytes one by one.\n\tfor i := 0; i < BlockSize; i++ {\n\t\tcipher := cryptoutil.NewCipher(EncryptedCipherText)[:BlockSize*(blockNumber+2)]\n\n\t\t// Insert previously found bytes.\n\t\tfor j := 0; j < i; j++ {\n\t\t\tcipher[len(cipher)-BlockSize-1-j] = cipher[len(cipher)-BlockSize-1-j] ^ decrypted[BlockSize-1-j] ^ byte(i+1)\n\t\t}\n\n\tguessLoop:\n\t\t// Guess the current byte.\n\t\tfor g := byte(0); g <= 255; g++ {\n\t\t\tencryptedGuess := make([]byte, len(cipher))\n\t\t\tcopy(encryptedGuess, cipher)\n\t\t\tencryptedGuess[len(encryptedGuess)-BlockSize-1-i] = encryptedGuess[len(encryptedGuess)-BlockSize-1-i] ^ g ^ byte(i+1)\n\t\t\tstatusCode := SendRequest(encryptedGuess)\n\t\t\tif statusCode == InvalidMessageErrorCode {\n\t\t\t\tfmt.Printf(\"[%d] %d\\n\", i, g)\n\t\t\t\tdecrypted[BlockSize-1-i] = g\n\t\t\t\tbreak guessLoop\n\t\t\t} else if statusCode == 200 {\n\t\t\t\tfmt.Printf(\"[%d] Got HTTP200 for %d\\n\", i, g)\n\t\t\t\tif g > 1 {\n\t\t\t\t\tdecrypted[BlockSize-1-i] = g\n\t\t\t\t\tbreak guessLoop\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn decrypted\n}", "func New(key []byte, alg func([]byte) (cipher.Block, error)) (cipher.AEAD, error) {\n\tmac, err := alg(key[:(len(key) / 2)])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tenc, err := alg(key[(len(key) / 2):])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &siv{\n\t\tenc: enc,\n\t\tmac: mac,\n\t}, nil\n}", "func NewContext(block *core.Block, engine db.DB, wb db.WriteBatch) Context {\n\treturn &DefaultContext{\n\t\tqueryEngine: engine,\n\t\twb: wb,\n\t\tblock: block,\n\t\tchannelID: block.Header.ChannelID,\n\t\tevmCtx: &evm.Context{\n\t\t\tBlockHeight: block.GetNumber(),\n\t\t\tBlockTime: block.Header.Time,\n\t\t\tDifficulty: 0,\n\t\t\tGasLimit: 10000000000,\n\t\t\tGasPrice: 0,\n\t\t\tCoinBase: nil,\n\t\t},\n\t\taccounts: make(map[string]*accountInfo),\n\t}\n}", "func (be *ContentEnc) DecryptBlocks(ciphertext []byte, firstBlockNo uint64, fileID []byte) ([]byte, error) {\n\tcBuf := bytes.NewBuffer(ciphertext)\n\tvar err error\n\tvar pBuf bytes.Buffer\n\tfor cBuf.Len() > 0 {\n\t\tcBlock := cBuf.Next(int(be.cipherBS))\n\t\tvar pBlock []byte\n\t\tpBlock, err = be.DecryptBlock(cBlock, firstBlockNo, fileID)\n\t\tif err != nil {\n\t\t\tif be.forceDecode && err == stupidgcm.ErrAuth {\n\t\t\t\ttlog.Warn.Printf(\"DecryptBlocks: authentication failure in block #%d, overriden by forcedecode\", firstBlockNo)\n\t\t\t} else {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tpBuf.Write(pBlock)\n\t\tfirstBlockNo++\n\t}\n\treturn pBuf.Bytes(), err\n}", "func NewBlock(filename string, blockNum int) *Block {\n\treturn &Block{FileName: filename, BlockNum: blockNum}\n}", "func New(rawBuffer []byte) *EbpfDecoder {\n\treturn &EbpfDecoder{\n\t\tbuffer: rawBuffer,\n\t\tcursor: 0,\n\t}\n}", "func DetectECB(blockSize int, ct []byte) bool {\n\n\ttopRank := 0 // rank is the highest count of repeating blocks for a tested offset\n\n\t// determine rank for each offset up to blockSize\n\tfor i := 0; i < blockSize; i++ {\n\t\t// unique block counts are saved as strings, int pairs in a map\n\t\tblockCount := make(map[string]int)\n\n\t\t// enumerate through blocks and save in map\n\t\tfor j := i; j <= len(ct)-blockSize; j += blockSize {\n\t\t\tblockCount[string(ct[j:j+blockSize])] += 1\n\t\t}\n\n\t\t// determine rank for test\n\t\trank := 0\n\t\tfor block := range blockCount {\n\t\t\tif blockCount[block] > 1 {\n\t\t\t\trank += blockCount[block] - 1\n\t\t\t}\n\t\t}\n\n\t\t// update top rank\n\t\tif rank > topRank {\n\t\t\ttopRank = rank\n\t\t}\n\t}\n\n\t// increase threshold for longer data sizes\n\tthreshold := 0\n\tif float64(len(ct)) > math.Sqrt(math.Pow(2, float64(blockSize))) {\n\t\tthreshold = 1 // not a very adaptive method\n\t}\n\n\t// compare rank to threshold\n\treturn topRank > threshold\n}", "func encryptECB(data, key []byte) (encryptedData []byte, err error) {\n\taesCrypt, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tencryptedData = make([]byte, len(data))\n\taesCrypt.Encrypt(encryptedData, data)\n\n\treturn\n}", "func (sr *shadowsocksReader) readBlock(decryptedBlockSize int) ([]byte, error) {\n\tif err := sr.init(); err != nil {\n\t\treturn nil, err\n\t}\n\tcipherBlockSize := decryptedBlockSize + sr.aead.Overhead()\n\tif cipherBlockSize > cap(sr.buf) {\n\t\treturn nil, io.ErrShortBuffer\n\t}\n\tbuf := sr.buf[:cipherBlockSize]\n\t_, err := io.ReadFull(sr.reader, buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbuf, err = sr.aead.Open(buf[:0], sr.counter, buf, nil)\n\tincrement(sr.counter)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to decrypt: %v\", err)\n\t}\n\treturn buf, nil\n}", "func DecryptLegacy(b []byte, privateKey ed25519.PrivateKey) ([]byte, error) {\n\tr := NewReader(b)\n\n\tpub, err := r.Read(ed25519.PublicKeySize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata, err := r.ReadAll()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tkey, iv, err := keyPairsToAesKeyIvLegacy(privateKey, pub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn decryptWithAseKeyIv(data, key, iv, nil)\n}", "func AESEncryptWithECB(str, key []byte) ([]byte, error) {\n\tcb, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\tblockSize := cb.BlockSize()\n\t// The str arguments can be any length, and padding is automatically added to\n\t// str so it is a multiple of a block as required by block-based algorithms such as AES.\n\t// This padding is automatically removed by the AES_DECRYPT() function.\n\tdata := pkcs7Padding(str, blockSize)\n\tcrypted := make([]byte, len(data))\n\tecb := newECBEncrypter(cb)\n\tecb.CryptBlocks(crypted, data)\n\treturn crypted, nil\n}", "func (c *CCM) Decrypt(in []byte) ([]byte, error) {\n\tvar h recordlayer.Header\n\terr := h.Unmarshal(in)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, err\n\tcase h.ContentType == protocol.ContentTypeChangeCipherSpec:\n\t\t// Nothing to encrypt with ChangeCipherSpec\n\t\treturn in, nil\n\tcase len(in) <= (8 + recordlayer.HeaderSize):\n\t\treturn nil, errNotEnoughRoomForNonce\n\t}\n\n\tnonce := append(append([]byte{}, c.remoteWriteIV[:4]...), in[recordlayer.HeaderSize:recordlayer.HeaderSize+8]...)\n\tout := in[recordlayer.HeaderSize+8:]\n\n\tadditionalData := generateAEADAdditionalData(&h, len(out)-int(c.tagLen))\n\tout, err = c.remoteCCM.Open(out[:0], nonce, out, additionalData)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: %v\", errDecryptPacket, err) //nolint:errorlint\n\t}\n\treturn append(in[:recordlayer.HeaderSize], out...), nil\n}", "func NewBlock(filename string, blknum uint64) *Block {\n\treturn &Block{\n\t\tfilename: filename,\n\t\tblknum: blknum,\n\t}\n}", "func (c *Coffin) Decrypt(data []byte) ([]byte, error) {\n\tswitch c.Mode {\n\tcase CryptCHACHA20:\n\t\treturn c.decryptCHACHA20(data)\n\tcase CryptAES256:\n\t\treturn c.decryptAES256(data)\n\tcase CryptRSA:\n\t\treturn c.decryptRSA(data)\n\tdefault:\n\t\treturn c.decryptCHACHA20(data)\n\t}\n}", "func (c *Chain) decryptBlock(i uint64) {\n\tb := c.GetBlock(i)\n\tc.last.Xor(c.cipher.Decrypt(b, c.Ck))\n\tc.PutBlock(i, c.last)\n\tc.last = b\n}", "func NewCipher(key []byte) (cipher.Block, error) {\r\n\tk := len(key)\r\n\tswitch k {\r\n\tdefault:\r\n\t\treturn nil, fmt.Errorf(\"sm4: invalid key size %d\", k)\r\n\tcase 16:\r\n\t\tbreak\r\n\t}\r\n\treturn newCipher(key)\r\n}", "func (c *Client) NewDecryptor() (decryptor *Decryptor) {\n\tdecryptor = new(Decryptor)\n\tdecryptor.decryptor = ckks.NewDecryptor(c.params, c.sk)\n\tdecryptor.encoder = ckks.NewEncoder(c.params)\n\tdecryptor.plaintext = ckks.NewPlaintext(c.params, 0, 0)\n\treturn\n}", "func CBCMode(ciphertext, key, iv string) string {\n\n\treturn \"\"\n}", "func DecryptUseCBC(cipherText, key []byte, iv []byte) ([]byte, error) {\n\tblockKey, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblockSize := blockKey.BlockSize()\n\tif len(cipherText)%blockSize != 0 {\n\t\treturn nil, errors.New(\"cipher text is not an integral multiple of the block size\")\n\t}\n\tdecryptTool := cipher.NewCBCDecrypter(blockKey, iv)\n\t// CryptBlocks can work in-place if the two arguments are the same.\n\tdecryptTool.CryptBlocks(cipherText, cipherText)\n\treturn PKCS5UnPadding(cipherText), nil\n}", "func DecryptCBC(ciphertext, key, iv []byte) ([]byte, error) {\r\n\r\n\t// 1. Check if ciphertext is a multiple of 16\r\n\tif len(ciphertext)%16 != 0 {\r\n\t\treturn nil, fmt.Errorf(\"ciphertext is %d bytes which is not \"+\r\n\t\t\t\"a multiple of 16.\",\r\n\t\t\tlen(ciphertext))\r\n\t}\r\n\r\n\t// 2. Check if IV and 16 are of same length\r\n\tif len(iv) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"IV has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(iv))\r\n\t}\r\n\r\n\t// 2.5 Check if key and 16 are of same length\r\n\tif len(key) != 16 {\r\n\t\treturn nil, fmt.Errorf(\"key has wrong length.\\nexpected %d, got %d\",\r\n\t\t\t16, len(key))\r\n\t}\r\n\r\n\t// 3. Split the ciphertext into 16 byte blocks\r\n\tblocks := SplitBytes(ciphertext, 16)\r\n\r\n\t// 4. For each block\r\n\t// https://upload.wikimedia.org/wikipedia/commons/2/2a/CBC_decryption.svg\r\n\r\n\t// 4.1 DecryptECB the block\r\n\t// 4.2 XOR with IV\r\n\t// 4.3 store plaintext\r\n\t// 4.4 IV := block (old ciphertext)\r\n\r\n\tvar plaintext []byte\r\n\r\n\tfor _, block := range blocks {\r\n\t\t// 4.1 DecryptECB the block\r\n\t\tdecryptedBlock, err := DecryptECB(block, key)\r\n\r\n\t\t// Check if it was decrypted correctly\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\r\n\t\t// 4.2 XOR with IV\r\n\t\tdecryptedBlock = XOR(decryptedBlock, iv)\r\n\r\n\t\t// 4.3 store plaintext\r\n\t\tplaintext = append(plaintext, decryptedBlock...)\r\n\r\n\t\t// 4.4 IV := block (old ciphertext)\r\n\t\tiv = block\r\n\t}\r\n\r\n\treturn plaintext, nil\r\n}", "func NewBlock() *Block {\n\treturn &Block{}\n}", "func (st *ApplyInfo) ReadBlock(_is *codec.Reader, tag byte, require bool) error {\n\tvar err error\n\tvar have bool\n\tst.resetDefault()\n\n\terr, have = _is.SkipTo(codec.STRUCT_BEGIN, tag, require)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !have {\n\t\tif require {\n\t\t\treturn fmt.Errorf(\"require ApplyInfo, but not exist. tag %d\", tag)\n\t\t}\n\t\treturn nil\n\n\t}\n\n\tst.ReadFrom(_is)\n\n\terr = _is.SkipToStructEnd()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = have\n\treturn nil\n}", "func Decrypt(ciphertext []byte, key []byte) []byte {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\tlogging.ErrorLogger.Println(err.Error())\n\t}\n\tif len(ciphertext) < aes.BlockSize {\n\t\tpanic(\"ciphertext too short\")\n\t}\n\tiv := ciphertext[:aes.BlockSize]\n\tciphertext = ciphertext[aes.BlockSize:]\n\tif len(ciphertext)%aes.BlockSize != 0 {\n\t\tpanic(\"ciphertext is not a multiple of the block size\")\n\t}\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\tciphertext, err = unPad(ciphertext)\n\tif err != nil {\n\t\tlogging.ErrorLogger.Println(err.Error())\n\t}\n\treturn ciphertext\n}", "func (c AESCBC) Decrypt(cipherText []byte) []byte {\n\t// CBC mode always works in whole blocks.\n\tif len(cipherText)%aes.BlockSize != 0 {\n\t\tpanic(\"ciphertext is not a multiple of the block size\")\n\t}\n\n\tdecryptedText := make([]byte, len(cipherText))\n\n\tmode := cipher.NewCBCDecrypter(c.block, c.iv)\n\n\tfor i := 0; i < len(cipherText)/aes.BlockSize; i++ {\n\t\tmode.CryptBlocks(decryptedText[i*aes.BlockSize:(i+1)*aes.BlockSize], cipherText[i*aes.BlockSize:(i+1)*aes.BlockSize])\n\t}\n\treturn decryptedText\n}", "func NewBlock(transactionPool *mempool, previousBlock *Block) *Block {\n\n\tcurrentBlock := Block{}\n\tcurrentBlock.PreviousBlock = previousBlock\n\n\t// First, select which transactions the block will contain\n\tselectedTransactions := selectTransactions(transactionPool)\n\tcurrentBlock.Transactions = selectedTransactions\n\n\t// Second, calculate the hash of the selected transactions\n\thashedTransaction := string(processTransactions(selectedTransactions))\n\thashedBlockData := hashedTransaction + currentBlock.Hash\n\tcurrentBlock.Hash = hashedBlockData\n\treturn &currentBlock\n}", "func NewORE(sk []byte) (*ORE, error) {\n\tblock, err := aes.NewCipher(sk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tecb := newECBEncrypter(block)\n\treturn &ORE{sk: sk, aes: ecb}, nil\n}", "func NewECE(maxAge time.Duration, logFile string, maxLogSize int, maxLogBackups int, maxLogAge int, logCompress bool) *ECE {\n\tlogObj := log.New(os.Stdout, \"\", 0)\n\n\tlogObj.SetOutput(&lumberjack.Logger{\n\t\tFilename: logFile,\n\t\tMaxSize: maxLogSize,\n\t\tMaxBackups: maxLogBackups,\n\t\tMaxAge: maxLogAge,\n\t\tCompress: logCompress,\n\t})\n\n\ta := &ECE{\n\t\tTtl: maxAge,\n\t\tlogger: logObj,\n\t\tEvents: make(map[string]*Event),\n\t}\n\n\treturn a\n}", "func NewBlock(tx *Transaction) *Block {\n\t\n\treturn nil\n}", "func (st *AdapterConf) ReadBlock(_is *codec.Reader, tag byte, require bool) error {\n\tvar err error\n\tvar have bool\n\tst.resetDefault()\n\n\terr, have = _is.SkipTo(codec.STRUCT_BEGIN, tag, require)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif !have {\n\t\tif require {\n\t\t\treturn fmt.Errorf(\"require AdapterConf, but not exist. tag %d\", tag)\n\t\t}\n\t\treturn nil\n\n\t}\n\n\tst.ReadFrom(_is)\n\n\terr = _is.SkipToStructEnd()\n\tif err != nil {\n\t\treturn err\n\t}\n\t_ = have\n\treturn nil\n}", "func NewBlock(t *testing.T, bc blockchainer.Blockchainer, offset uint32, primary uint32, txs ...*transaction.Transaction) *block.Block {\n\twitness := transaction.Witness{VerificationScript: MultisigVerificationScript()}\n\theight := bc.BlockHeight()\n\th := bc.GetHeaderHash(int(height))\n\thdr, err := bc.GetHeader(h)\n\trequire.NoError(t, err)\n\tb := &block.Block{\n\t\tHeader: block.Header{\n\t\t\tPrevHash: hdr.Hash(),\n\t\t\tTimestamp: (uint64(time.Now().UTC().Unix()) + uint64(hdr.Index)) * 1000,\n\t\t\tIndex: hdr.Index + offset,\n\t\t\tPrimaryIndex: byte(primary),\n\t\t\tNextConsensus: witness.ScriptHash(),\n\t\t\tScript: witness,\n\t\t},\n\t\tTransactions: txs,\n\t}\n\tb.RebuildMerkleRoot()\n\n\tb.Script.InvocationScript = Sign(b)\n\treturn b\n}", "func CBCDecrypt(crypt []byte, key []byte, IV []byte) ([]byte, error) {\n\n\taesCipher, err := aes.NewCipher(key) // aes aesCipher\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockSize := aesCipher.BlockSize() // block size\n\tdata := make([]byte, len(crypt)) // data storage array\n\n\t// CBC mode, decrypt the first block\n\taesCipher.Decrypt(data[0:blockSize], crypt[0:blockSize])\n\ttrailingData := data[blockSize:]\n\tdata = append(Xor(IV, data[0:blockSize]), trailingData...)\n\n\t// decrypt remaining blocks\n\tfor i := blockSize; i < len(crypt); i += blockSize {\n\t\taesCipher.Decrypt(data[i:i+blockSize], crypt[i:i+blockSize]) // D(ct) = pt ^ ct-1\n\t\ttrailingData := data[i+blockSize:] // pt+1...\n\t\txorResults := Xor(crypt[i-blockSize:i], data[i:i+blockSize]) // xor = pt ^ ct-1\n\t\tdata = append(append(data[:i], xorResults...), trailingData...) // slice in new plaintext block\n\t}\n\n\t// remove pad from the decrypted data and return\n\treturn UnPad(data)\n}", "func Decrypt(key, ciphertext []byte) ([]byte, error) {\n\tblock, err := aes.NewCipher(key)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif len(ciphertext)%aes.BlockSize != 0 {\n\t\treturn nil, errors.New(\"not multiple of AES blocksize\")\n\t}\n\n\tiv := ciphertext[:aes.BlockSize]\n\tmode := cipher.NewCBCDecrypter(block, iv)\n\tmode.CryptBlocks(ciphertext, ciphertext)\n\tpad := ciphertext[len(ciphertext)-1]\n\tif pad > aes.BlockSize {\n\t\treturn nil, fmt.Errorf(\"pad value (%d) larger than AES blocksize (%d)\", pad, aes.BlockSize)\n\t}\n\treturn ciphertext[aes.BlockSize : len(ciphertext)-int(pad)], nil\n}", "func DecodeBlock(data []byte) *StBlock {\n\tout := new(StBlock)\n\tout.sign = data[1 : data[0]+1]\n\tbData := data[data[0]+1:]\n\tn := runtime.Decode(bData, &out.Block)\n\tstream := bData[n:]\n\tif len(stream)%HashLen != 0 {\n\t\treturn nil\n\t}\n\tif out.Index < 1 {\n\t\treturn nil\n\t}\n\n\trst := wallet.Recover(out.Producer[:], out.sign, bData)\n\tif !rst {\n\t\tlog.Printf(\"fail to recover block,producer:%x\\n\", out.Producer)\n\t\treturn nil\n\t}\n\th := runtime.GetHash(data)\n\truntime.Decode(h, &out.Key)\n\n\treturn out\n}", "func DecryptByBlockSecretKey(key []byte, cipherText []byte) string {\n\tc, err := aes.NewCipher(key); if err != nil {\n\t\tfmt.Println(err.Error())\n\t\treturn \"\"\n\t}\n\n\tplainText := make([]byte, aes.BlockSize)\n\tc.Decrypt(plainText, cipherText)\n\n\treturn string(plainText)\n}", "func (m *Mode) GetBlock(i uint64) state.State {\n\tbi := i % NBufferBlocks // in the current buffer block\n\treturn m.InBuffer[bi]\n}", "func NewBlock(previousBlock Block, data string) (Block, error) {\n\tvar newBlock Block\n\n\tnewBlock.Index = previousBlock.Index + 1\n\tnewBlock.Timestamp = time.Now().String()\n\tnewBlock.Data = data\n\tnewBlock.PrevHash = previousBlock.Hash\n\tnewBlock.Difficulty = GetDifficulty()\n\n\tif !isCandidateBlockValid(newBlock, previousBlock) {\n\t\treturn newBlock, errors.New(\"Candidate block is not valid\")\n\t}\n\n\tmineBlock(&newBlock)\n\n\treturn newBlock, nil\n}", "func NewReader(seed string) (io.Reader, error) {\n\tsum := sha256.Sum256([]byte(seed))\n\tblock, err := aes.NewCipher(sum[:])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tiv := make([]byte, block.BlockSize())\n\treturn undoAGL{cipher.StreamReader{\n\t\tS: cipher.NewCTR(block, iv),\n\t\tR: devZero{},\n\t}}, nil\n}", "func (c *ecbDecrypter) BlockSize() int {\n\treturn c.blockSize\n}", "func Decrypt(c []byte, q Poracle, l *log.Logger) (string, error) {\n\tn := len(c) / CipherBlockLen\n\tif n < 2 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\tif len(c)%CipherBlockLen != 0 {\n\t\treturn \"\", ErrInvalidCiphertext\n\t}\n\t// The clear text have the same length as the cyphertext - 1\n\t// (the IV).\n\tvar m []byte\n\tfor i := 1; i < n; i++ {\n\t\tc0 := c[(i-1)*CipherBlockLen : CipherBlockLen*(i-1)+CipherBlockLen]\n\t\tc1 := c[CipherBlockLen*i : (CipherBlockLen*i)+CipherBlockLen]\n\t\tl.Printf(\"\\ndecripting block %d of %d\", i, n)\n\t\tmi, err := decryptBlock(c0, c1, q, l)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tm = append(m, mi...)\n\t}\n\treturn string(m), nil\n}", "func (I *Blockchain) NewBlock(proof uint64, previousHash string) {\n\t// In order to be able to create the first block\n\tif previousHash == \"\" {\n\t\tpreviousHash = \"1\"\n\t}\n\t// Create the block\n\tb := block{\n\t\tindex: I.currentIndex,\n\t\ttimestamp: time.Now().UnixNano(),\n\t\tproof: proof,\n\t\tpreviousHash: previousHash,\n\t\ttransactions: I.currentTransactions,\n\t}\n\t// Append the new block\n\tI.blocks = append(I.blocks, b)\n\t// Reset the transactions\n\tI.currentTransactions = make([]transaction, 0)\n\t// Update the index\n\tI.currentIndex += 1\n\t// Modify the last block variable\n\tI.lastBlock = b\n}" ]
[ "0.8701252", "0.8368462", "0.81978804", "0.81978804", "0.81978804", "0.81978804", "0.81978804", "0.7677102", "0.730549", "0.7303622", "0.71535826", "0.7123518", "0.70053756", "0.70053756", "0.70053756", "0.70053756", "0.70053756", "0.6567953", "0.63559914", "0.6006861", "0.59652513", "0.5833099", "0.57328373", "0.56734", "0.56011784", "0.55774236", "0.5561433", "0.553761", "0.552732", "0.5394785", "0.5388905", "0.53500617", "0.528657", "0.5282735", "0.5268249", "0.5268088", "0.5257741", "0.52342016", "0.52323747", "0.5186946", "0.5180674", "0.5174101", "0.5169795", "0.5158607", "0.5158501", "0.5116636", "0.5081536", "0.5058931", "0.50573075", "0.5057287", "0.5053551", "0.50392795", "0.5026913", "0.50231034", "0.5016904", "0.5005431", "0.50051564", "0.49880856", "0.49792057", "0.4908513", "0.48937044", "0.48881245", "0.48862052", "0.48841757", "0.4882327", "0.4867197", "0.4866136", "0.4859627", "0.48479414", "0.483394", "0.48256004", "0.4817861", "0.48173013", "0.48077172", "0.4804279", "0.47936812", "0.47700638", "0.47550884", "0.47550213", "0.47337016", "0.47310334", "0.4712733", "0.46887943", "0.468757", "0.46705252", "0.46702105", "0.46658644", "0.4665208", "0.46512234", "0.46509156", "0.46493003", "0.46467635", "0.46394145", "0.4637115", "0.4635841", "0.4634265", "0.46233243", "0.46112537", "0.46102235", "0.4601979" ]
0.827353
2
Abs returns the absolute value of x.
func Abs(x int) int { if x < 0 { return -x } return x }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Abs(x float64) float64 {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\tif x == 0 {\n\t\treturn 0 // return correctly abs(-0)\n\t}\n\treturn x\n}", "func Abs(x float64) float64 {\n\tif x < 0 {\n\t\tx = -x\n\t}\n\treturn x\n}", "func Abs(x int) int {\n\tif x > 0 {\n\t\treturn x\n\t}\n\treturn -x\n}", "func Abs(x int64) int64 {\n\ta := int64(x)\n\tif a < 0 {\n\t\treturn (-a)\n\t}\n\treturn (a)\n}", "func abs(x int64) int64 {\n\tif x >= 0 {\n\t\treturn x\n\t}\n\treturn -x\n}", "func abs(x int64) int64 {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func abs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func abs(x int) int {\n\tif x < 0{\n\t\treturn -x\n\t}\n\treturn x\n}", "func abs(x int) int {\r\n\tif x < 0 {\r\n\t\treturn -x\r\n\t}\r\n\treturn x\r\n}", "func Abs(x int) int {\n if x < 0 {\n return -x\n }\n return x\n}", "func Abs(x int32) int32 {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func Absolute(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func Abs(arg float64) float64 {\n\treturn math.Abs(arg)\n}", "func IntAbs(x int) int {\n\tif x > 0 {\n\t\treturn x\n\t}\n\n\treturn -x\n}", "func (z *Big) Abs(x *Big) *Big {\n\tif debug {\n\t\tx.validate()\n\t}\n\tif !z.invalidContext(z.Context) && !z.checkNaNs(x, x, absvalue) {\n\t\tz.Context.round(z.copyAbs(x))\n\t}\n\treturn z\n}", "func iAbs(x int) int { if x >= 0 { return x } else { return -x } }", "func (f *Float) Abs(x *Float) *Float {\n\tx.doinit()\n\tf.doinit()\n\tC.mpf_abs(&f.i[0], &x.i[0])\n\treturn f\n}", "func abs(x int32) int32 {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func Abs[T constraints.Number](x T) T {\n\tif x >= 0 {\n\t\treturn x\n\t}\n\treturn -x\n}", "func Abs(z, x *big.Int) *big.Int {\n\treturn z.Abs(x)\n}", "func Abs(x int32) int32 {\n\t// Patented (!) : return (x ^ (x >> 31)) - (x >> 31)\n\treturn (x + (x >> 31)) ^ (x >> 31)\n}", "func Abs(operand int) int {\n\tif operand < 0 {\n\t\treturn operand * -1\n\t}\n\treturn operand\n}", "func goAbs(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func Abs(number int) int {\n\tif number > 0 {\n\t\treturn number\n\t}\n\treturn -number\n}", "func Abs(a int) int {\n\tif a > 0 {\n\t\treturn a\n\t}\n\treturn -a\n}", "func Abs(a int) int {\n\tif a > 0 {\n\t\treturn a\n\t}\n\treturn -a\n}", "func Abs(a int) int {\n\tif a > 0 {\n\t\treturn a\n\t}\n\treturn -a\n}", "func Abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}", "func Abs(v int) int {\n\tif v > 0 {\n\t\treturn v\n\t}\n\treturn -v\n}", "func absolute(x int32) int32 {\n\tmask := x >> 31\n\treturn (x + mask) ^ mask\n}", "func Abs(a int) int {\n\treturn neogointernal.Opcode1(\"ABS\", a).(int)\n}", "func Abs(in Res) Res {\n\tsign := in.Output().Copy()\n\tanyvec.GreaterThan(sign, sign.Creator().MakeNumeric(0))\n\tsign.Scale(sign.Creator().MakeNumeric(2))\n\tsign.AddScalar(sign.Creator().MakeNumeric(-1))\n\treturn Mul(in, NewConst(sign))\n}", "func (z *Int) Abs(x *Int) *Int {}", "func Abs(x float32) float32 {\n\tux := *(*uint32)(unsafe.Pointer(&x)) & 0x7FFFFFFF\n\treturn *(*float32)(unsafe.Pointer(&ux))\n}", "func Abs(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Abs\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func AbsInt(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func AbsInt(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func Abs(b int) int {\n\tif b < 0 {\n\t\treturn -b\n\t}\n\n\treturn b\n}", "func AbsInt(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t} else {\n\t\treturn x\n\t}\n}", "func Abs(num int) int{\n\tif num > 0{\n\t\treturn num\n\t}\n\treturn (-1)*num\n}", "func (z *Float) Abs(x *Float) *Float {}", "func abs(val int) int {\n\tif val < 0 {\n\t\treturn -val\n\t}\n\treturn val\n}", "func Abs(value gcv.Value) gcv.Value {\n\tif value.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Abs(value.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Abs(value.Real()))\n}", "func absInt(x int) int {\n\tif x < 0 {\n\t\treturn -x\n\t}\n\treturn x\n}", "func (c *Clac) Abs() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn unary(\"abs\", vals[0])\n\t})\n}", "func mathAbs(ctx phpv.Context, args []*phpv.ZVal) (*phpv.ZVal, error) {\n\tvar z *phpv.ZVal\n\t_, err := core.Expand(ctx, args, &z)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tz, err = z.AsNumeric(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch z.GetType() {\n\tcase phpv.ZtInt:\n\t\ti := z.AsInt(ctx)\n\t\tif i < 0 {\n\t\t\treturn (-i).ZVal(), nil\n\t\t} else {\n\t\t\treturn i.ZVal(), nil\n\t\t}\n\tcase phpv.ZtFloat:\n\t\treturn phpv.ZFloat(math.Abs(float64(z.AsFloat(ctx)))).ZVal(), nil\n\tdefault:\n\t\treturn phpv.ZNull{}.ZVal(), nil\n\t}\n}", "func abs(v int) int {\n\tif v < 0 {\n\t\treturn -v\n\t}\n\treturn v\n}", "func Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func Abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func Abs(n int) int {\n\tif n >= 0 {\n\t\treturn n\n\t}\n\treturn -n\n}", "func abs(num int64) int64 {\n\tif num < 0 {\n\t\treturn -num\n\t}\n\treturn num\n}", "func (g *Graph) Abs(x Node) Node {\n\treturn g.NewOperator(fn.NewAbs(x), x)\n}", "func getAbs(a int) int {\n if a < 0 {\n return -a\n }\n return a\n}", "func intAbs(n int64) int64 {\n\treturn int64(math.Abs(float64(n)))\n}", "func Abs(a *big.Float) *big.Float {\n\treturn ZeroBigFloat().Abs(a)\n}", "func abs(a int) int {\r\n if a < 0 {\r\n return -a\r\n }\r\n return a\r\n}", "func IntAbs(z *big.Int, x *big.Int,) *big.Int", "func abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}", "func abs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}", "func Absolute(num cty.Value) (cty.Value, error) {\n\treturn AbsoluteFunc.Call([]cty.Value{num})\n}", "func IntAbs(a int) int {\n\tif a < 0 {\n\t\treturn -a\n\t}\n\treturn a\n}", "func (z *Rat) Abs(x *Rat) *Rat {}", "func (d Decimal) Abs() Decimal {\n\tif !d.IsNegative() {\n\t\treturn d\n\t}\n\td.ensureInitialized()\n\td2Value := new(big.Int).Abs(d.value)\n\treturn Decimal{\n\t\tvalue: d2Value,\n\t\texp: d.exp,\n\t}\n}", "func Abs(x complex64) float32 { return math.Hypot(real(x), imag(x)) }", "func ( f MyFloat ) Abs() float64 {\n\tif f < 0 { return float64( -f ) }\n\treturn float64(f) \n}", "func Abs(n int) int {\n if n < 0 {\n return -n\n }\n return n\n}", "func (d Decimal) Abs() Decimal {\n\td.ensureInitialized()\n\td2Value := new(big.Int).Abs(d.value)\n\treturn Decimal{\n\t\tvalue: d2Value,\n\t\texp: d.exp,\n\t}\n}", "func abs(n int) int {\n if n > 0 {\n return n\n }\n\n return -n\n}", "func (f MyFloat) Abs() float64 {\n\tif f < 0 {\n\t\treturn float64(-f)\n\t}\n\treturn float64(f)\n}", "func abs(n int) int {\n if n < 0 {\n return -n\n }\n return n\n}", "func getAbsoluteValue(value int) int {\n\tif value < 0 {\n\t\treturn -value\n\t}\n\treturn value\n}", "func RatAbs(z *big.Rat, x *big.Rat,) *big.Rat", "func TestAbs(t *testing.T) {\n\tvar tests = []struct {\n\t\tOperand int\n\t\tExpected int\n\t}{\n\t\t{Operand: -10, Expected: 10},\n\t\t{Operand: -1, Expected: 1},\n\t\t{Operand: 0, Expected: 0},\n\t\t{Operand: -1, Expected: 1},\n\t\t{Operand: 10, Expected: 10},\n\t}\n\n\tfor _, test := range tests {\n\t\tresult := Abs(test.Operand)\n\t\tif result != test.Expected {\n\t\t\tt.Errorf(\"Abs result incorrect. Operand: %d, Expected: %d, Received: %d\", test.Operand, test.Expected, result)\n\t\t}\n\t}\n}", "func PrintAbs(v Abser) {\n\ta := v.Abs()\n\tfmt.Println(a)\n}", "func (z *Int) Abs() *Int {\n\tif z.Lt(SignedMin) {\n\t\treturn z\n\t}\n\tz.Sub(zero, z)\n\treturn z\n}", "func (self *State)Abs(a any)any{\n self.IncOperations(self.coeff[\"abs\"]+self.off[\"abs\"])\n return wrap1(a,math.Abs)\n}", "func (x *Int) CmpAbs(y *Int) int {}", "func abs(n int) int {\n\tif n < 0 {\n\t\treturn -n\n\t}\n\treturn n\n}", "func (m mathUtil) AbsInt(value int) int {\n\tif value < 0 {\n\t\treturn -value\n\t}\n\treturn value\n}", "func (v Vector) MaxAbs() float64 {\n\tvar res float64\n\tfor _, x := range v {\n\t\tres = math.Max(res, math.Abs(x))\n\t}\n\treturn res\n}", "func (m *MockFinder) Abs(v []byte) []byte {\n\treturn m.fnd.Abs(v)\n}", "func AbsInt(v int) int {\n\tif v < 0 {\n\t\treturn -v\n\t}\n\treturn v\n}", "func (i *Number) Absolute() *Number {\n\treturn NewNumber(math.Abs(i.value))\n}", "func funcAbs(vals []parser.Value, args parser.Expressions, enh *EvalNodeHelper) Vector {\n\treturn simpleFunc(vals, enh, math.Abs)\n}", "func (bi Int) Abs() Int {\n\tif bi.GreaterThanEqual(Zero()) {\n\t\treturn bi.Copy()\n\t}\n\treturn bi.Neg()\n}", "func abs(i int) int {\n\tif i < 0 {\n\t\treturn -i\n\t}\n\treturn i\n}", "func abs(i int) int {\n\tif i < 0 {\n\t\treturn -i\n\t}\n\treturn i\n}", "func (m *Money) Abs() *Money {\n\tif m.M < 0 {\n\t\tm.Neg()\n\t}\n\treturn m\n}" ]
[ "0.8458174", "0.8439933", "0.8292976", "0.8110982", "0.80721015", "0.8036469", "0.80264986", "0.80264986", "0.80264986", "0.8007751", "0.79817164", "0.7907059", "0.78863204", "0.78377527", "0.7805782", "0.7712452", "0.7684405", "0.7656599", "0.7542068", "0.74985456", "0.7495437", "0.7439939", "0.7396938", "0.7393865", "0.73770726", "0.733206", "0.7306088", "0.7306088", "0.7306088", "0.72873855", "0.72869486", "0.7267437", "0.72412443", "0.7211243", "0.7206655", "0.71650314", "0.71584976", "0.7149105", "0.7149105", "0.7132062", "0.7115116", "0.7114169", "0.7095328", "0.70783365", "0.70769113", "0.70734626", "0.7005514", "0.70045954", "0.6998757", "0.69914836", "0.69914836", "0.69914836", "0.69914836", "0.69914836", "0.69676155", "0.6924256", "0.6880235", "0.68685097", "0.68531823", "0.6848639", "0.68135375", "0.6807058", "0.67718184", "0.67718184", "0.67707676", "0.67657", "0.6726247", "0.6718124", "0.6711116", "0.67041105", "0.6692396", "0.6677606", "0.66685045", "0.6665215", "0.6647836", "0.6642377", "0.66394037", "0.66257876", "0.6623106", "0.66109645", "0.6610472", "0.65884674", "0.6561095", "0.6550574", "0.6539527", "0.65386707", "0.6537325", "0.6531982", "0.65192974", "0.6502549", "0.648549", "0.648549", "0.6479659" ]
0.82694644
9
InstallPodMemoryHogEngine installs the given chaosengine for the experiment
func InstallPodMemoryHogEngine(experimentsDetails *types.ExperimentDetails, chaosEngine *v1alpha1.ChaosEngine, clients environment.ClientSets) error { experimentENV := setPodMemoryHogExperimentENV(experimentsDetails) if err := common.InstallChaosEngine(experimentsDetails, chaosEngine, experimentENV, clients); err != nil { return err } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func InstallGoChaosEngine(testsDetails *types.TestDetails, chaosEngine *v1alpha1.ChaosEngine, engineNamespace string, clients environment.ClientSets) error {\n\n\t//Fetch Engine file\n\tres, err := http.Get(testsDetails.EnginePath)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Failed to fetch the rbac file due to %v\", err)\n\t}\n\n\t// ReadAll reads from response until an error or EOF and returns the data it read.\n\tfileInput, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read data from response: %v\", err)\n\t}\n\n\t// Unmarshal decodes the fileInput into chaosEngine\n\terr = yamlChe.Unmarshal([]byte(fileInput), &chaosEngine)\n\tif err != nil {\n\t\tlog.Errorf(\"error when unmarshalling: %v\", err)\n\t}\n\n\t// Initialise engine\n\tsetEngineVar(chaosEngine, testsDetails)\n\n\t// Marshal serializes the values provided into a YAML document.\n\tfileData, err := json.Marshal(chaosEngine)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Failed to marshal ChaosEngine %v\", err)\n\t}\n\n\t//Creating chaos engine\n\tlog.Info(\"[Engine]: Installing ChaosEngine...\")\n\tif err = CreateChaosResource(testsDetails, fileData, testsDetails.ChaosNamespace, clients); err != nil {\n\t\treturn errors.Errorf(\"Failed to apply engine file, err: %v\", err)\n\t}\n\tlog.Info(\"[Engine]: ChaosEngine Installed Successfully !!!\")\n\treturn nil\n}", "func InstallGoChaosExperiment(testsDetails *types.TestDetails, chaosExperiment *v1alpha1.ChaosExperiment, experimentNamespace string, clients environment.ClientSets) error {\n\n\t//Fetch Experiment file\n\tres, err := http.Get(testsDetails.ExperimentPath)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Failed to fetch the experiment file due to %v\", err)\n\t}\n\n\t// ReadAll reads from response until an error or EOF and returns the data it read.\n\tfileInput, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to read data from response: %v\", err)\n\t}\n\n\t// Unmarshal decodes the fileInput into chaosExperiment\n\terr = yamlChe.Unmarshal([]byte(fileInput), &chaosExperiment)\n\tif err != nil {\n\t\tlog.Errorf(\"error when unmarshalling: %v\", err)\n\t}\n\n\t// Initialise experiment\n\tsetExperimentVar(chaosExperiment, testsDetails)\n\n\t// Marshal serializes the value provided into a YAML document.\n\tfileData, err := json.Marshal(chaosExperiment)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Failed to marshal ChaosExperiment %v\", err)\n\t}\n\n\tlog.Info(\"[Experiment]: Installing Experiment...\")\n\n\t//Creating experiment\n\tif err = CreateChaosResource(testsDetails, fileData, testsDetails.ChaosNamespace, clients); err != nil {\n\t\treturn errors.Errorf(\"Failed to apply experiment file, err: %v\", err)\n\t}\n\tlog.Info(\"[ChaosExperiment]: Experiment installed successfully !!!\")\n\tlog.Info(\"[Experiment Image]: Chaos Experiment created successfully with image: \" + testsDetails.ExperimentImage + \" !!!\")\n\n\treturn nil\n}", "func setPodMemoryHogExperimentENV(experimentsDetails *types.ExperimentDetails) *common.ENVDetails {\n\t// contains all the envs\n\tenvDetails := common.ENVDetails{\n\t\tENV: map[string]string{},\n\t}\n\t// Add Experiment ENV's\n\tenvDetails.SetEnv(\"CONTAINER_RUNTIME\", experimentsDetails.ContainerRuntime).\n\t\tSetEnv(\"SOCKET_PATH\", experimentsDetails.SocketPath).\n\t\tSetEnv(\"TARGET_PODS\", experimentsDetails.TargetPods).\n\t\tSetEnv(\"PODS_AFFECTED_PERC\", strconv.Itoa(experimentsDetails.PodsAffectedPerc)).\n\t\tSetEnv(\"MEMORY_CONSUMPTION\", strconv.Itoa(experimentsDetails.MemoryConsumption))\n\n\treturn &envDetails\n}", "func TestBasicHelmInstall(t *testing.T) {\n\tg := NewGomegaWithT(t)\n\n\t// Create a helper.HelmHelper\n\thelmHelper, err := helper.NewOperatorChartHelper()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\t// Create the values to use (in this case empty)\n\tvalues := helper.OperatorValues{}\n\n\t// If we wanted to load a YAML file into the values then we can use\n\t// the values.LoadFromYaml method with a file name relative to this\n\t// test files location\n\t//err = values.LoadFromYaml(\"test.yaml\")\n\t//g.Expect(err).ToNot(HaveOccurred())\n\n\t// Create a HelmReleaseManager with a release name and values\n\thm, err := helmHelper.NewOperatorHelmReleaseManager(\"basic\", &values)\n\tg.Expect(err).ToNot(HaveOccurred())\n\n\t// Defer cleanup (helm delete) to make sure it happens when this method exits\n\tdefer CleanupHelm(t, hm, helmHelper)\n\n\t// Install the chart\n\t_, err = hm.InstallRelease()\n\tg.Expect(err).ToNot(HaveOccurred())\n\n\t// The chart is installed but the Pod(s) may not exist yet so wait for it...\n\t// (we wait a maximum of 5 minutes, retrying every 10 seconds)\n\tpods, err := helper.WaitForOperatorPods(helmHelper.KubeClient, helmHelper.Namespace, time.Second*10, time.Minute*5)\n\tg.Expect(err).ToNot(HaveOccurred())\n\tg.Expect(len(pods)).To(Equal(1))\n\n\t// The Pod(s) exist so get one of them using the k8s client from the helper\n\t// which is in the HelmHelper.KubeClient var configured in the suite .go file.\n\tpod, err := helmHelper.KubeClient.CoreV1().Pods(helmHelper.Namespace).Get(pods[0].Name, metav1.GetOptions{})\n\tg.Expect(err).ToNot(HaveOccurred())\n\n\t// The chart is installed but the Pod we have may not be ready yet so wait for it...\n\t// (we wait a maximum of 5 minutes, retrying every 10 seconds)\n\terr = helper.WaitForPodReady(helmHelper.KubeClient, pod.Namespace, pod.Name, time.Second*10, time.Minute*5)\n\tg.Expect(err).ToNot(HaveOccurred())\n\n\t// Assert some things\n\tcontainer := pod.Spec.Containers[0]\n\tg.Expect(container.Name).To(Equal(\"coherence-operator\"))\n\tg.Expect(container.Env).To(HaveEnvVar(corev1.EnvVar{Name: \"OPERATOR_NAME\", Value: \"coherence-operator\"}))\n\n\t// Obtain a PortForwarder for the Pod - this will forward all of the ports defined in the Pod spec.\n\t// The values returned are a PortForwarder, a map of port name to local port and any error\n\tfwd, ports, err := helper.StartPortForwarderForPod(pod)\n\tg.Expect(err).ToNot(HaveOccurred())\n\n\t// Defer closing the PortForwarder so we clean-up properly\n\tdefer fwd.Close()\n\n\t// The ReST port in the Operator container spec is named \"rest\"\n\trestPort := ports[\"rest\"]\n\n\t// Do a GET on the Zone endpoint for the Pod's NodeName, we should get no error and a 200 response\n\tresp, err := http.Get(fmt.Sprintf(\"http://127.0.0.1:%d/site/%s\", restPort, pod.Spec.NodeName))\n\tg.Expect(err).ToNot(HaveOccurred())\n\tg.Expect(resp.StatusCode).To(Equal(200))\n}", "func main() {\n\tctx := context.Background()\n\n\tu, err := gouser.Current()\n\tcheckErr(err)\n\tuser = u.Username\n\n\t// initialize Dagger client\n\tclient, err := dagger.Connect(ctx, dagger.WithLogOutput(os.Stdout))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer client.Close()\n\n\tR := &hdagger.Runtime{\n\t\tCtx: ctx,\n\t\tClient: client,\n\t}\n\n\t// load hof's code from the host\n\t// todo, find repo root with git\n\tsource := R.Client.Host().Directory(\".\", dagger.HostDirectoryOpts{\n\t\tExclude: []string{\"cue.mod/pkg\", \"docs\", \"next\", \".git\"},\n\t})\n\n\t// gcloud image to run commands in\n\tgcloud := R.GcloudImage()\n\n\t// mount local config & secrets\n\tgcloud = R.WithLocalGcloudConfig(gcloud)\n\t// gcloud = R.WithLocalSSHDir(gcloud)\n\n\t//\n\t// Testing on matrix of {arch}x{runtime}\n\t//\n\thadErr := false\n\tfor _, arch := range arches {\n\t\t// build hof the normal way\n\t\tbase := R.GolangImage(fmt.Sprintf(\"linux/%s64\", arch))\n\t\tdeps := R.FetchDeps(base, source)\n\t\tbuilder := R.BuildHof(deps, source)\n\t\thof := builder.File(\"hof\")\n\n\t\tfor _, runtime := range runtimes {\n\t\t\tvmName := fmt.Sprintf(\"%s-fmt-test-%s-%s\", user, runtime, arch)\n\t\t\tt := gcloud.Pipeline(vmName)\n\t\t\tt = t.WithEnvVariable(\"CACHEBUST\", time.Now().String())\n\t\t\t\n\t\t\t// start VM\n\t\t\tvmFamily := fmt.Sprintf(\"debian-%s-%s\", runtime, arch)\n\t\t\tt = WithBootVM(t, vmName, vmFamily, arch)\n\n\t\t\t// any runtime extra pre-steps before testing\n\t\t\t// we really want to test that it is permission issue and advise the user\n\t\t\t// we should also capture this as a test, so we need a setup where this fails intentionally\n\t\t\tswitch runtime {\n\t\t\tcase \"docker\":\t\n\t\t\t\t// will probably need something like this for nerdctl too\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"sudo usermod -aG docker $USER\")\t\n\n\t\t\tcase \"nerdctl\":\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"sudo nerdctl apparmor load\")\t\n\t\t\t\t// https://github.com/containerd/nerdctl/blob/main/docs/faq.md#does-nerdctl-have-an-equivalent-of-sudo-usermod--ag-docker-user-\n\t\t\t\t// make a user home bin and add to path\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"mkdir -p $HOME/bin && chmod 700 $HOME/bin && echo 'PATH=$HOME/bin:$PATH' >> .profile\")\t\n\t\t\t\t// copy nerdctl and set bits appropriatedly\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"cp /usr/local/bin/nerdctl $HOME/bin && sudo chown $(id -u):$(id -g) $HOME/bin/nerdctl && sudo chmod 0755 $HOME/bin/nerdctl && sudo chown root $HOME/bin/nerdctl && sudo chmod +s $HOME/bin/nerdctl\")\t\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"nerdctl version\")\t\n\n\t\t\tcase \"nerdctl-rootless\":\n\t\t\t\t// ensure the current user can run nerdctl\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"containerd-rootless-setuptool.sh install\")\t\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"nerdctl version\")\t\n\t\t\t}\n\n\t\t\t// remote commands to run\n\t\t\tt = WithGcloudSendFile(t, vmName, \"/usr/local/bin/hof\", hof, true)\n\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof version\")\n\t\t\tt = WithGcloudRemoteBash(t, vmName, \"echo '{}' | hof gen - -T :=foo.json\")\n\n\t\t\t// todo, what do we want to run on the remote VM?\n\t\t\t// we test everthing with docker, we added these tests as a sanity on the tools\n\t\t\t// what we really need is the \"full\" test suite with none (no container runtime)\n\t\t\t// \"full\" because there are some tests we cannot run, because you need a container formatter\n\t\t\t// what is not easy is to separate the directory of testscripts, unless we make 2 dirs, which might be the easy solution\n\t\t\tif runtime != \"none\" {\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof fmt pull [email protected]\")\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof fmt start [email protected]\")\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof fmt status\")\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof fmt test prettier\")\n\t\t\t\tt = WithGcloudRemoteBash(t, vmName, \"hof fmt stop\")\n\t\t\t}\n\n\t\t\t// sync to run them for real\n\t\t\t_, err = t.Sync(R.Ctx)\n\t\t\tif err != nil {\n\t\t\t\thadErr = true\n\t\t\t\tfmt.Println(\"an error!:\", err)\n\t\t\t}\n\n\t\t\t// always try deleting, we mostly ignore the error here (less likely, will also error if not exists)\n\t\t\td := gcloud.Pipeline(\"DELETE \" + vmName)\n\t\t\td = d.WithEnvVariable(\"CACHEBUST\", time.Now().String())\n\t\t\td = WithDeleteVM(d, vmName)\n\t\t\t_, err := d.Sync(R.Ctx)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(\"deleting error!:\", err)\n\t\t\t}\n\n\t\t\t// stop if we had an error\n\t\t\tif hadErr {\n\t\t\t\tbreak\n\t\t\t}\n\t\t} // end runtime loop\n\t\t// stop if we had an error\n\t\tif hadErr {\n\t\t\tfmt.Println(\"stopping b/c error\")\n\t\t\tbreak\n\t\t}\n\t} // end arch loop\n}", "func setEngineVar(chaosEngine *v1alpha1.ChaosEngine, testsDetails *types.TestDetails) {\n\n\t// contains all the envs\n\tenvDetails := ENVDetails{\n\t\tENV: map[string]string{},\n\t}\n\n\t// Add JobCleanUpPolicy of chaos-runner to retain\n\tchaosEngine.Spec.JobCleanUpPolicy = v1alpha1.CleanUpPolicy(testsDetails.JobCleanUpPolicy)\n\n\t// Add ImagePullPolicy of chaos-runner to Always\n\tchaosEngine.Spec.Components.Runner.ImagePullPolicy = corev1.PullPolicy(testsDetails.ImagePullPolicy)\n\n\t// Modify the spec of engine file\n\tchaosEngine.ObjectMeta.Name = testsDetails.EngineName\n\tchaosEngine.ObjectMeta.Namespace = testsDetails.ChaosNamespace\n\n\t// If ChaosEngine contain App Info then update it\n\tif chaosEngine.Spec.Appinfo.Appns != \"\" && chaosEngine.Spec.Appinfo.Applabel != \"\" {\n\t\tchaosEngine.Spec.Appinfo.Appns = testsDetails.AppNS\n\t\tchaosEngine.Spec.Appinfo.Applabel = testsDetails.AppLabel\n\t}\n\tif testsDetails.ChaosServiceAccount != \"\" {\n\t\tchaosEngine.Spec.ChaosServiceAccount = testsDetails.ChaosServiceAccount\n\t} else {\n\t\tchaosEngine.Spec.ChaosServiceAccount = testsDetails.ExperimentName + \"-sa\"\n\t}\n\tchaosEngine.Spec.Experiments[0].Name = testsDetails.NewExperimentName\n\tchaosEngine.Spec.AnnotationCheck = testsDetails.AnnotationCheck\n\n\tswitch testsDetails.ExperimentName {\n\tcase \"ec2-terminate-by-id\":\n\t\tenvDetails.SetEnv(\"EC2_INSTANCE_ID\", testsDetails.InstanceID).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ec2-terminate-by-tag\":\n\t\tenvDetails.SetEnv(\"INSTANCE_TAG\", testsDetails.InstanceTag).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ebs-loss-by-id\":\n\t\tenvDetails.SetEnv(\"EBS_VOLUME_ID\", testsDetails.EBSVolumeID).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ebs-loss-by-tag\":\n\t\tenvDetails.SetEnv(\"EBS_VOLUME_TAG\", testsDetails.EBSVolumeTag).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"disk-fill\":\n\t\tif testsDetails.FillPercentage != 80 {\n\t\t\tenvDetails.SetEnv(\"FILL_PERCENTAGE\", strconv.Itoa(testsDetails.FillPercentage))\n\t\t}\n\t\t// Here not using SetEnv function as SetEnv will not add new variables\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"EPHEMERAL_STORAGE_MEBIBYTES\",\n\t\t\tValue: \"200\",\n\t\t})\n\tcase \"pod-cpu-hog-exec\":\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"CHAOS_KILL_COMMAND\",\n\t\t\tValue: testsDetails.CPUKillCommand,\n\t\t})\n\tcase \"pod-memory-hog-exec\":\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"CHAOS_KILL_COMMAND\",\n\t\t\tValue: testsDetails.MemoryKillCommand,\n\t\t})\n\tcase \"azure-instance-stop\":\n\t\tenvDetails.SetEnv(\"RESOURCE_GROUP\", testsDetails.AzureResourceGroup).\n\t\t\tSetEnv(\"AZURE_INSTANCE_NAME\", testsDetails.AzureInstanceName).\n\t\t\tSetEnv(\"AZURE_SCALE_SET\", testsDetails.AzureScaleSet)\n\tcase \"azure-disk-loss\":\n\t\tenvDetails.SetEnv(\"RESOURCE_GROUP\", testsDetails.AzureResourceGroup).\n\t\t\tSetEnv(\"AZURE_SCALE_SET\", testsDetails.AzureScaleSet).\n\t\t\tSetEnv(\"VIRTUAL_DISK_NAMES\", testsDetails.AzureDiskName)\n\tcase \"gcp-vm-instance-stop\":\n\t\tenvDetails.SetEnv(\"GCP_PROJECT_ID\", testsDetails.GCPProjectID).\n\t\t\tSetEnv(\"VM_INSTANCE_NAMES\", testsDetails.VMInstanceNames).\n\t\t\tSetEnv(\"INSTANCE_ZONES\", testsDetails.InstanceZones)\n\tcase \"gcp-vm-disk-loss\":\n\t\tenvDetails.SetEnv(\"GCP_PROJECT_ID\", testsDetails.GCPProjectID).\n\t\t\tSetEnv(\"DISK_VOLUME_NAMES\", testsDetails.DiskVolumeNames).\n\t\t\tSetEnv(\"DISK_ZONES\", testsDetails.DiskZones).\n\t\t\tSetEnv(\"DEVICE_NAMES\", testsDetails.DeviceNames)\n\tcase \"vm-poweroff\":\n\t\tenvDetails.SetEnv(\"APP_VM_MOIDS\", testsDetails.VMIds)\n\tcase \"process-kill\":\n\t\tenvDetails.SetEnv(\"PROCESS_IDS\", testsDetails.ProcessIds)\n\t}\n\n\t// for experiments like pod network latency\n\tenvDetails.SetEnv(\"NETWORK_LATENCY\", testsDetails.NetworkLatency)\n\n\t// update App Node Details\n\tif testsDetails.ApplicationNodeName != \"\" {\n\t\tenvDetails.SetEnv(\"TARGET_NODE\", testsDetails.ApplicationNodeName)\n\t\tif chaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector == nil {\n\t\t\tchaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector = map[string]string{}\n\t\t}\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector[\"kubernetes.io/hostname\"] = testsDetails.NodeSelectorName\n\t}\n\n\t// update Target Node Details\n\tif testsDetails.TargetNodes != \"\" {\n\t\tlog.Infof(\"[Info] Target Nodes: %v\", testsDetails.TargetNodes)\n\t\tenvDetails.SetEnv(\"TARGET_NODES\", testsDetails.TargetNodes)\n\t}\n\n\t// NODE_LABEL for Node-memory-hog and node-cpu-hog\n\tif testsDetails.NodeLabel != \"\" {\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"NODE_LABEL\",\n\t\t\tValue: testsDetails.NodeLabel,\n\t\t})\n\t}\n\n\t// update all the value corresponding to keys from the ENV's in Engine\n\tfor key, value := range chaosEngine.Spec.Experiments[0].Spec.Components.ENV {\n\t\t_, ok := envDetails.ENV[value.Name]\n\t\tif ok {\n\t\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV[key].Value = envDetails.ENV[value.Name]\n\t\t}\n\t}\n}", "func (a *Agent) InstallChart(\n\tctx context.Context,\n\tconf *InstallChartConfig,\n\tdoAuth *oauth2.Config,\n\tdisablePullSecretsInjection bool,\n) (*release.Release, error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"stacktrace from panic: \\n\" + string(debug.Stack()))\n\t\t}\n\t}()\n\n\tctx, span := telemetry.NewSpan(ctx, \"helm-install-chart\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"project-id\", Value: conf.Cluster.ProjectID},\n\t\ttelemetry.AttributeKV{Key: \"cluster-id\", Value: conf.Cluster.ID},\n\t\ttelemetry.AttributeKV{Key: \"chart-name\", Value: conf.Name},\n\t\ttelemetry.AttributeKV{Key: \"chart-namespace\", Value: conf.Namespace},\n\t)\n\n\tcmd := action.NewInstall(a.ActionConfig)\n\n\tif cmd.Version == \"\" && cmd.Devel {\n\t\tcmd.Version = \">0.0.0-0\"\n\t}\n\n\tcmd.ReleaseName = conf.Name\n\tcmd.Namespace = conf.Namespace\n\tcmd.Timeout = 300 * time.Second\n\n\tif err := checkIfInstallable(conf.Chart); err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error checking if installable\")\n\t}\n\n\tvar err error\n\n\tcmd.PostRenderer, err = NewPorterPostrenderer(\n\t\tconf.Cluster,\n\t\tconf.Repo,\n\t\ta.K8sAgent,\n\t\tconf.Namespace,\n\t\tconf.Registries,\n\t\tdoAuth,\n\t\tdisablePullSecretsInjection,\n\t)\n\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error getting post renderer\")\n\t}\n\n\tif req := conf.Chart.Metadata.Dependencies; req != nil {\n\t\tfor _, dep := range req {\n\t\t\tdepChart, err := loader.LoadChartPublic(ctx, dep.Repository, dep.Name, dep.Version)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, telemetry.Error(ctx, span, err, fmt.Sprintf(\"error retrieving chart dependency %s/%s-%s\", dep.Repository, dep.Name, dep.Version))\n\t\t\t}\n\n\t\t\tconf.Chart.AddDependency(depChart)\n\t\t}\n\t}\n\n\treturn cmd.Run(conf.Chart, conf.Values)\n}", "func InstallLitmus(testsDetails *types.TestDetails) error {\n\n\tlog.Info(\"Installing Litmus ...\")\n\tif err := DownloadFile(\"install-litmus.yaml\", testsDetails.InstallLitmus); err != nil {\n\t\treturn errors.Errorf(\"Failed to fetch litmus operator file due to %v\", err)\n\t}\n\tlog.Info(\"Updating ChaosOperator Image ...\")\n\tif err := EditFile(\"install-litmus.yaml\", \"image: litmuschaos/chaos-operator:latest\", \"image: \"+testsDetails.OperatorImage); err != nil {\n\t\treturn errors.Errorf(\"Unable to update operator image due to %v\", err)\n\n\t}\n\tif err = EditKeyValue(\"install-litmus.yaml\", \" - chaos-operator\", \"imagePullPolicy: Always\", \"imagePullPolicy: \"+testsDetails.ImagePullPolicy); err != nil {\n\t\treturn errors.Errorf(\"Unable to update image pull policy due to %v\", err)\n\t}\n\tlog.Info(\"Updating Chaos Runner Image ...\")\n\tif err := EditKeyValue(\"install-litmus.yaml\", \"CHAOS_RUNNER_IMAGE\", \"value: \\\"litmuschaos/chaos-runner:latest\\\"\", \"value: '\"+testsDetails.RunnerImage+\"'\"); err != nil {\n\t\treturn errors.Errorf(\"Unable to update runner image due to %v\", err)\n\t}\n\t//Creating engine\n\tcommand := []string{\"apply\", \"-f\", \"install-litmus.yaml\"}\n\terr := Kubectl(command...)\n\tif err != nil {\n\t\treturn errors.Errorf(\"Failed to apply litmus installation file, err: %v\", err)\n\t}\n\tlog.Info(\"Litmus installed successfully !!!\")\n\n\treturn nil\n}", "func launchEchoserverPodForHybrid(j *framework.ServiceTestJig, f *framework.Framework, nodeName string, podName string, hostNetwork bool, isLinuxPod bool) *v1.Pod {\n\tfmt.Printf(\"Creating echo server pod %q in namespace %q\", podName, f.Namespace.Name)\n\tpod := newEchoServerPodSpecForHybrid(podName, hostNetwork, isLinuxPod)\n\tpod.Spec.NodeName = nodeName\n\tfor k, v := range j.Labels {\n\t\tpod.ObjectMeta.Labels[k] = v\n\t}\n\tpodClient := f.ClientSet.CoreV1().Pods(f.Namespace.Name)\n\t_, err := podClient.Create(pod)\n\tframework.ExpectNoError(err)\n\tframework.ExpectNoError(f.WaitForPodRunning(podName))\n\tfmt.Printf(\"Echo server pod %q in namespace %q running\", pod.Name, f.Namespace.Name)\n\tpod, err = f.ClientSet.Core().Pods(f.Namespace.Name).Get(podName, metav1.GetOptions{})\n\tframework.ExpectNoError(err)\n\treturn pod\n}", "func PreparePodNetworkChaos(experimentsDetails *experimentTypes.ExperimentDetails, clients clients.ClientSets, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails, resultDetails *types.ResultDetails) error {\n\n\t// extract out the pid of the target container\n\ttargetPID, err := GetPID(experimentsDetails, clients)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// record the event inside chaosengine\n\tif experimentsDetails.EngineName != \"\" {\n\t\tmsg := \"Injecting \" + experimentsDetails.ExperimentName + \" chaos on application pod\"\n\t\ttypes.SetEngineEventAttributes(eventsDetails, types.ChaosInject, msg, \"Normal\", chaosDetails)\n\t\tevents.GenerateEvents(eventsDetails, clients, chaosDetails, \"ChaosEngine\")\n\t}\n\n\tvar endTime <-chan time.Time\n\ttimeDelay := time.Duration(experimentsDetails.ChaosDuration) * time.Second\n\n\t// injecting network chaos inside target container\n\tif err = InjectChaos(experimentsDetails, targetPID); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Infof(\"[Chaos]: Waiting for %vs\", experimentsDetails.ChaosDuration)\n\n\t// signChan channel is used to transmit signal notifications.\n\tsignChan := make(chan os.Signal, 1)\n\t// Catch and relay certain signal(s) to signChan channel.\n\tsignal.Notify(signChan, os.Interrupt, syscall.SIGTERM, syscall.SIGKILL)\n\nloop:\n\tfor {\n\t\tendTime = time.After(timeDelay)\n\t\tselect {\n\t\tcase <-signChan:\n\t\t\tlog.Info(\"[Chaos]: Killing process started because of terminated signal received\")\n\t\t\t// updating the chaosresult after stopped\n\t\t\tfailStep := \"Network Chaos injection stopped!\"\n\t\t\ttypes.SetResultAfterCompletion(resultDetails, \"Stopped\", \"Stopped\", failStep)\n\t\t\tresult.ChaosResult(chaosDetails, clients, resultDetails, \"EOT\")\n\n\t\t\t// generating summary event in chaosengine\n\t\t\tmsg := experimentsDetails.ExperimentName + \" experiment has been aborted\"\n\t\t\ttypes.SetEngineEventAttributes(eventsDetails, types.Summary, msg, \"Warning\", chaosDetails)\n\t\t\tevents.GenerateEvents(eventsDetails, clients, chaosDetails, \"ChaosEngine\")\n\n\t\t\t// generating summary event in chaosresult\n\t\t\ttypes.SetResultEventAttributes(eventsDetails, types.StoppedVerdict, msg, \"Warning\", resultDetails)\n\t\t\tevents.GenerateEvents(eventsDetails, clients, chaosDetails, \"ChaosResult\")\n\n\t\t\tif err = tc.Killnetem(targetPID); err != nil {\n\t\t\t\tlog.Errorf(\"unable to kill netem process, err :%v\", err)\n\n\t\t\t}\n\t\t\tos.Exit(1)\n\t\tcase <-endTime:\n\t\t\tlog.Infof(\"[Chaos]: Time is up for experiment: %v\", experimentsDetails.ExperimentName)\n\t\t\tendTime = nil\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\tlog.Info(\"[Chaos]: Stopping the experiment\")\n\n\t// cleaning the netem process after chaos injection\n\tif err = tc.Killnetem(targetPID); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func installSuHelm(root, profile, unit string) error {\n\tparser := yaml.NewParser()\n\terr := parser.Parse(profile)\n\tif err != nil {\n\t\tlog.Fatalf(\"parser.Parse profile error: err=%s\", err)\n\t}\n\texec := exec.NewExec(root)\n\tfor _, su := range parser.Profile.ServiceUnits {\n\t\tif !strings.EqualFold(su.Name, unit) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, app := range su.Applications {\n\t\t\tshell := exec.Install(su.Name, parser.Profile.Namespace, app.Name)\n\t\t\tlog.Infof(\"InstallAllCharts: root=%s, profile=%s, su=%s, app=%s, shell=%v\",\n\t\t\t\troot, profile, su.Name, app.Name, shell)\n\t\t\terr := exec.Do(shell)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Helm install error: err=%s\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func injectChaosInParallelMode(experimentsDetails *experimentTypes.ExperimentDetails, targetPodList corev1.PodList, clients clients.ClientSets, resultDetails *types.ResultDetails, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails) error {\n\t// creating err channel to recieve the error from the go routine\n\tstressErr := make(chan error)\n\n\t// run the probes during chaos\n\tif len(resultDetails.ProbeDetails) != 0 {\n\t\tif err := probe.RunProbes(chaosDetails, clients, resultDetails, \"DuringChaos\", eventsDetails); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar endTime <-chan time.Time\n\ttimeDelay := time.Duration(experimentsDetails.ChaosDuration) * time.Second\n\n\tfor _, pod := range targetPodList.Items {\n\n\t\tif experimentsDetails.EngineName != \"\" {\n\t\t\tmsg := \"Injecting \" + experimentsDetails.ExperimentName + \" chaos on \" + pod.Name + \" pod\"\n\t\t\ttypes.SetEngineEventAttributes(eventsDetails, types.ChaosInject, msg, \"Normal\", chaosDetails)\n\t\t\tevents.GenerateEvents(eventsDetails, clients, chaosDetails, \"ChaosEngine\")\n\t\t}\n\n\t\tlog.InfoWithValues(\"[Chaos]: The Target application details\", logrus.Fields{\n\t\t\t\"Target Container\": experimentsDetails.TargetContainer,\n\t\t\t\"Target Pod\": pod.Name,\n\t\t\t\"Storage Consumption(MB)\": experimentsDetails.Size,\n\t\t})\n\t\tgo stressStorage(experimentsDetails, pod.Name, clients, stressErr)\n\t}\n\n\tlog.Infof(\"[Chaos]:Waiting for: %vs\", experimentsDetails.ChaosDuration)\n\n\t// signChan channel is used to transmit signal notifications.\n\tsignChan := make(chan os.Signal, 1)\n\t// Catch and relay certain signal(s) to signChan channel.\n\tsignal.Notify(signChan, os.Interrupt, syscall.SIGTERM)\nloop:\n\tfor {\n\t\tendTime = time.After(timeDelay)\n\t\tselect {\n\t\tcase err := <-stressErr:\n\t\t\t// skipping the execution, if recieved any error other than 137, while executing stress command and marked result as fail\n\t\t\t// it will ignore the error code 137(oom kill), it will skip further execution and marked the result as pass\n\t\t\t// oom kill occurs if stor to be stressed exceed than the resource limit for the target container\n\t\t\tif err != nil {\n\t\t\t\tif strings.Contains(err.Error(), \"137\") {\n\t\t\t\t\tlog.Warn(\"Chaos process OOM killed\")\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-signChan:\n\t\t\tlog.Info(\"[Chaos]: Revert Started\")\n\t\t\tif err := killStressParallel(experimentsDetails.TargetContainer, targetPodList, experimentsDetails.AppNS, experimentsDetails.ChaosKillCmd, clients); err != nil {\n\t\t\t\tlog.Errorf(\"Error in Kill stress after abortion, err: %v\", err)\n\t\t\t}\n\t\t\tlog.Info(\"[Chaos]: Revert Completed\")\n\t\t\tos.Exit(1)\n\t\tcase <-endTime:\n\t\t\tlog.Infof(\"[Chaos]: Time is up for experiment: %v\", experimentsDetails.ExperimentName)\n\t\t\tbreak loop\n\t\t}\n\t}\n\tif err := killStressParallel(experimentsDetails.TargetContainer, targetPodList, experimentsDetails.AppNS, experimentsDetails.ChaosKillCmd, clients); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func installAppHelm(root, profile, unit, application string) error {\n\tparser := yaml.NewParser()\n\terr := parser.Parse(profile)\n\tif err != nil {\n\t\tlog.Fatalf(\"parser.Parse profile error: err=%s\", err)\n\t}\n\texec := exec.NewExec(root)\n\tfor _, su := range parser.Profile.ServiceUnits {\n\t\tif !strings.EqualFold(su.Name, unit) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, app := range su.Applications {\n\t\t\tif !strings.EqualFold(app.Name, application) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tshell := exec.Install(su.Name, parser.Profile.Namespace, app.Name)\n\t\t\tlog.Infof(\"InstallAllCharts: root=%s, profile=%s, su=%s, app=%s, shell=%v\",\n\t\t\t\troot, profile, su.Name, app.Name, shell)\n\t\t\terr := exec.Do(shell)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Helm install error: err=%s\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (td *OsmTestData) HelmInstallOSM(release, namespace string) error {\n\tif td.InstType == KindCluster {\n\t\tif err := td.LoadOSMImagesIntoKind(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvalues := fmt.Sprintf(\"osm.image.registry=%s,osm.image.tag=%s,osm.meshName=%s\", td.CtrRegistryServer, td.OsmImageTag, release)\n\targs := []string{\"install\", release, \"../../charts/osm\", \"--set\", values, \"--namespace\", namespace, \"--create-namespace\", \"--wait\"}\n\tstdout, stderr, err := td.RunLocal(\"helm\", args...)\n\tif err != nil {\n\t\ttd.T.Logf(\"stdout:\\n%s\", stdout)\n\t\treturn fmt.Errorf(\"failed to run helm install with osm chart: %s\", stderr)\n\t}\n\n\treturn nil\n}", "func AddToPodDefinitionMemory(pod *corev1.Pod, amountLimit, amountRequest, containerNumber int64) *corev1.Pod {\n\tif nil == pod.Spec.Containers[containerNumber].Resources.Limits {\n\t\tpod.Spec.Containers[containerNumber].Resources.Limits = make(map[corev1.ResourceName]resource.Quantity)\n\t}\n\n\tif nil == pod.Spec.Containers[containerNumber].Resources.Requests {\n\t\tpod.Spec.Containers[containerNumber].Resources.Requests = make(map[corev1.ResourceName]resource.Quantity)\n\t}\n\n\tpod.Spec.Containers[containerNumber].Resources.Limits[\"memory\"] = *resource.NewQuantity(amountLimit*1024*1024*1024, resource.BinarySI)\n\tpod.Spec.Containers[containerNumber].Resources.Requests[\"memory\"] = *resource.NewQuantity(amountRequest*1024*1024*1024, resource.BinarySI)\n\n\treturn pod\n}", "func Install(c *cli.Context) error {\n\t//chartmuseumURL := chartmuseum.GetChartmuseumURL()\n\tlog.Println(\"Parse toml config\")\n\tconfig, err := util.ParseConfig(configFile)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// helm package (compress)\n\tlog.Println(\"Helm package (compress helm chart)\")\n\tchartTgz := fmt.Sprintf(\"charts/%s-%s.tgz\", config.Chart.Name, config.Chart.Version)\n\tchartDir := fmt.Sprintf(\"charts/%s\", config.Chart.Name)\n\terr = util.Compress(chartTgz, chartDir)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// upload chart to chartmuseum\n\tlog.Println(\"Upload to chartmuseum\")\n\tchartdata, err := util.ReadFileBytes(chartTgz)\n\terr = chartmuseum.UploadCharts(chartdata)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// Upload Dockerfile to fileserver\n\tlog.Println(\"Upload Dockerfile\")\n\terr = dockerfile.UploadDockerfile(config.Chart.Name)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t\treturn err\n\t}\n\t// Check pipelines (jenkins和tekton)\n\tif config.Pipeline == \"jenkins\" {\n\t\tlog.Println(\"Create jenkins pipeline\")\n\t\tjauth := jenkins.GetJAuth()\n\t\tjks := jenkins.NewJenkins(jauth)\n\t\tpipeline, err := util.ReadFile(\"Jenkinsfile\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn err\n\t\t}\n\t\tjksconfig := jenkins.CreatePipeline(pipeline)\n\t\terr = jks.CreateJob(jksconfig, config.Chart.Name)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\t\t// Install helm chart(run jenkins job)\n\t\tlog.Println(\"Install helm chart\")\n\t\tvar params map[string]string\n\t\tparams = make(map[string]string)\n\t\tparams[\"action\"] = \"install\"\n\t\tparams[\"tag\"] = fmt.Sprintf(\"auto-%s\", time.Now().Format(\"20060102150405\"))\n\t\terr = jks.BuildWithParams(config.Chart.Name, params)\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t\treturn err\n\t\t}\n\t} else if config.Pipeline == \"tekton\" {\n\t\tlog.Println(\"Start tekton pipelines\")\n\t\tres, err := kubernetes.KubeOper(\"apply\", \"pipelines/\")\n\t\tif err != nil {\n\t\t\tlog.Fatalln(err)\n\t\t}\n\t\tfmt.Println(res)\n\t}\n\n\tlog.Println(\"App install success\")\n\treturn nil\n}", "func setupMemory(ctx context.Context, r types.Resources, s *specs.Spec) {\n\tmemory := &specs.LinuxMemory{}\n\tif r.Memory > 0 {\n\t\tv := r.Memory\n\t\tmemory.Limit = &v\n\t}\n\n\tif r.MemorySwap != 0 {\n\t\tv := r.MemorySwap\n\t\tmemory.Swap = &v\n\t}\n\n\tif r.MemorySwappiness != nil {\n\t\tv := uint64(*r.MemorySwappiness)\n\t\tmemory.Swappiness = &v\n\t}\n\n\tif r.OomKillDisable != nil {\n\t\tv := bool(*r.OomKillDisable)\n\t\tmemory.DisableOOMKiller = &v\n\t}\n\n\ts.Linux.Resources.Memory = memory\n}", "func GetGPUMemoryFromPodEnv(pod *v1.Pod) (gpuMemory uint) {\n\tfor _, container := range pod.Spec.Containers {\n\t\tgpuMemory += getGPUMemoryFromContainerEnv(container)\n\t}\n\tlog.V(100).Info(\"debug: pod %s in ns %s with status %v has GPU Mem %d\",\n\t\tpod.Name,\n\t\tpod.Namespace,\n\t\tpod.Status.Phase,\n\t\tgpuMemory)\n\treturn gpuMemory\n}", "func injectChaosInSerialMode(experimentsDetails *experimentTypes.ExperimentDetails, targetPodList corev1.PodList, clients clients.ClientSets, resultDetails *types.ResultDetails, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails) error {\n\t// creating err channel to recieve the error from the go routine\n\tstressErr := make(chan error)\n\n\t// run the probes during chaos\n\tif len(resultDetails.ProbeDetails) != 0 {\n\t\tif err := probe.RunProbes(chaosDetails, clients, resultDetails, \"DuringChaos\", eventsDetails); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tvar endTime <-chan time.Time\n\ttimeDelay := time.Duration(experimentsDetails.ChaosDuration) * time.Second\n\n\tfor _, pod := range targetPodList.Items {\n\n\t\tif experimentsDetails.EngineName != \"\" {\n\t\t\tmsg := \"Injecting \" + experimentsDetails.ExperimentName + \" chaos on \" + pod.Name + \" pod\"\n\t\t\ttypes.SetEngineEventAttributes(eventsDetails, types.ChaosInject, msg, \"Normal\", chaosDetails)\n\t\t\tevents.GenerateEvents(eventsDetails, clients, chaosDetails, \"ChaosEngine\")\n\t\t}\n\n\t\tlog.InfoWithValues(\"[Chaos]: The Target application details\", logrus.Fields{\n\t\t\t\"Target Container\": experimentsDetails.TargetContainer,\n\t\t\t\"Target Pod\": pod.Name,\n\t\t\t\"Space Consumption(MB)\": experimentsDetails.Size,\n\t\t})\n\t\tgo stressStorage(experimentsDetails, pod.Name, clients, stressErr)\n\n\t\tlog.Infof(\"[Chaos]:Waiting for: %vs\", experimentsDetails.ChaosDuration)\n\n\t\t// signChan channel is used to transmit signal notifications.\n\t\tsignChan := make(chan os.Signal, 1)\n\t\t// Catch and relay certain signal(s) to signChan channel.\n\t\tsignal.Notify(signChan, os.Interrupt, syscall.SIGTERM)\n\n\tloop:\n\t\tfor {\n\t\t\tendTime = time.After(timeDelay)\n\t\t\tselect {\n\t\t\tcase err := <-stressErr:\n\t\t\t\t// skipping the execution, if recieved any error other than 137, while executing stress command and marked result as fail\n\t\t\t\t// it will ignore the error code 137(oom kill), it will skip further execution and marked the result as pass\n\t\t\t\t// oom kill occurs if stor to be stressed exceed than the resource limit for the target container\n\t\t\t\tif err != nil {\n\t\t\t\t\tif strings.Contains(err.Error(), \"137\") {\n\t\t\t\t\t\tlog.Warn(\"Chaos process OOM killed\")\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase <-signChan:\n\t\t\t\tlog.Info(\"[Chaos]: Revert Started\")\n\t\t\t\tif err := killStressSerial(experimentsDetails.TargetContainer, pod.Name, experimentsDetails.AppNS, experimentsDetails.ChaosKillCmd, clients); err != nil {\n\t\t\t\t\tlog.Errorf(\"Error in Kill stress after abortion, err: %v\", err)\n\t\t\t\t}\n\t\t\t\tlog.Info(\"[Chaos]: Revert Completed\")\n\t\t\t\tos.Exit(1)\n\t\t\tcase <-endTime:\n\t\t\t\tlog.Infof(\"[Chaos]: Time is up for experiment: %v\", experimentsDetails.ExperimentName)\n\t\t\t\tendTime = nil\n\t\t\t\tbreak loop\n\t\t\t}\n\t\t}\n\t\tif err := killStressSerial(experimentsDetails.TargetContainer, pod.Name, experimentsDetails.AppNS, experimentsDetails.ChaosKillCmd, clients); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func enableSecretEngineInPod() {\n\tfirstPodName, firstPodIP := getFirstResponsivePod()\n\tsecretEnginesPodURL := \"http://\" + strings.TrimSpace(firstPodIP) + \":8200/v1/sys/mounts/\"\n\tif len(configMapObject.Data[\"secretEngines\"]) > 0 {\n\t\tvar secretEngineInterface map[string]map[string]interface{}\n\t\tjson.Unmarshal([]byte(configMapObject.Data[\"secretEngines\"]), &secretEngineInterface)\n\t\tfor engineName, payloadJsonStr := range secretEngineInterface {\n\t\t\tbyteArr, err := json.Marshal(payloadJsonStr)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"error while marshalling the payload for %s engine\", engineName)\n\t\t\t} else {\n\t\t\t\tlog.Debugf(\"proceeding to enable the engine path %s with the payload %s on the pod %s\", engineName, string(byteArr), firstPodName)\n\t\t\t\t_, err := FireRequest(string(byteArr), secretEnginesPodURL+strings.TrimSpace(engineName), getAuthTokenHeaders(), common.HttpMethodPUT)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"error while enabling the secret engine to pod %s as %s\", firstPodName, engineName)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func Install(name string) feature.StepFn {\n\timage := \"ko://knative.dev/eventing/test/test_images/heartbeats\"\n\n\treturn func(ctx context.Context, t feature.T) {\n\t\tenv := environment.FromContext(ctx)\n\n\t\tdeployment.Install(name, image,\n\t\t\tdeployment.WithSelectors(map[string]string{\"app\": name}),\n\t\t\tdeployment.WithEnvs(map[string]string{\n\t\t\t\t\"POD_NAME\": \"heartbeats\",\n\t\t\t\t\"POD_NAMESPACE\": env.Namespace(),\n\t\t\t}),\n\t\t\tdeployment.WithPort(8080))(ctx, t)\n\t}\n}", "func SetupHost(vmDriver string) {\n\tpreflightCheckAndFix(false,\n\t\tcheckOcBinaryCached,\n\t\tfixOcBinaryCached,\n\t\t\"Caching oc binary\",\n\t\tfalse,\n\t)\n}", "func newEchoServerPodSpecForHybrid(podName string, hostNetwork bool, isLinuxPod bool) *v1.Pod {\n\tvar port int\n\tvar clientImage, serverImage string\n\tvar commandStr []string\n\tvar nodeselector = map[string]string{}\n\thostNet := false\n\tvar env []v1.EnvVar\n\tone := int64(1)\n\twinVer := os.Getenv(\"WINDOWS_OS\")\n\tif winVer != \"\" && isLinuxPod != true {\n\t\tport = 8080\n\t\tclientImage = \"caltigera/hostexec:\" + winVer\n\t\tserverImage = \"caltigera/porter:\" + winVer\n\t\tnodeselector[\"beta.kubernetes.io/os\"] = \"windows\"\n\t\tenv = []v1.EnvVar{\n\t\t\t{\n\t\t\t\tName: fmt.Sprintf(\"SERVE_PORT_%d\", port),\n\t\t\t\tValue: \"Connection Succeeded\",\n\t\t\t},\n\t\t}\n\t} else {\n\t\tport = 8091\n\t\thostNet = hostNetwork\n\t\tclientImage = \"busybox\"\n\t\tserverImage = imageutils.GetE2EImage(imageutils.EchoServer)\n\t\tnodeselector[\"beta.kubernetes.io/os\"] = \"linux\"\n\t\tcommandStr = []string{\"/bin/sh\", \"-c\", \"trap \\\"echo Stopped; exit 0\\\" INT TERM EXIT; sleep 1000000\"}\n\t\tenv = []v1.EnvVar{}\n\t}\n\tpod := &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: podName,\n\t\t\tLabels: map[string]string{\"pod-name\": podName},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tContainers: []v1.Container{\n\t\t\t\t// Include a busybox container in the echo server. This is useful for doing loopback tests, where\n\t\t\t\t// a service pod accesses itself via the service cluster IP, for example. We make it the first\n\t\t\t\t// container so `kubectl exec` will choose it by default.\n\t\t\t\t{\n\t\t\t\t\tName: \"exec\",\n\t\t\t\t\tImage: clientImage,\n\t\t\t\t\tCommand: commandStr,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"echoserver\",\n\t\t\t\t\tImage: serverImage,\n\t\t\t\t\tEnv: env,\n\t\t\t\t\tPorts: []v1.ContainerPort{{ContainerPort: int32(port)}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t\tNodeSelector: nodeselector,\n\t\t\tHostNetwork: hostNet,\n\t\t\tTerminationGracePeriodSeconds: &one, // Speed up pod termination.\n\t\t},\n\t}\n\treturn pod\n}", "func Test_UniformRegistration_RegistrationOfKeptnIntegrationRemoteExecPlane(t *testing.T) {\n\tdefer func(t *testing.T) {\n\t\tPrintLogsOfPods(t, []string{\"shipyard-controller\"})\n\t}(t)\n\n\t// install echo integration\n\t// make sure the echo-service uses the same distributor as Keptn core\n\timageName, err := GetImageOfDeploymentContainer(\"lighthouse-service\", \"lighthouse-service\")\n\trequire.Nil(t, err)\n\tdistributorImage := strings.Replace(imageName, \"lighthouse-service\", \"distributor\", 1)\n\n\tapiToken, apiEndpoint, err := GetApiCredentials()\n\trequire.Nil(t, err)\n\n\techoServiceManifestContent := strings.ReplaceAll(echoServiceK8sManifest, \"${distributor-image}\", distributorImage)\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${queue-group}\", \"echo-service\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-endpoint}\", apiEndpoint)\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-token}\", apiToken)\n\n\ttmpFile, err := CreateTmpFile(\"echo-service-*.yaml\", echoServiceManifestContent)\n\tdefer func() {\n\t\tif err := os.Remove(tmpFile); err != nil {\n\t\t\tt.Logf(\"Could not delete file: %v\", err)\n\t\t}\n\t}()\n\ttestUniformIntegration(t, func() {\n\t\t// install echo integration\n\t\t_, err = KubeCtlApplyFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\n\t\terr = waitForDeploymentToBeRolledOut(false, echoServiceName, GetKeptnNameSpaceFromEnv())\n\t\trequire.Nil(t, err)\n\n\t}, func() {\n\t\terr := KubeCtlDeleteFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\t})\n}", "func (i *Installation) InstallKyma() (*Result, error) {\n\tif i.Options.CI || i.Options.NonInteractive {\n\t\ti.Factory.NonInteractive = true\n\t}\n\n\tvar err error\n\tif i.k8s, err = kube.NewFromConfig(\"\", i.Options.KubeconfigPath); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Could not initialize the Kubernetes client. Make sure your kubeconfig is valid\")\n\t}\n\n\ts := i.newStep(\"Validating configurations\")\n\tif err := i.validateConfigurations(); err != nil {\n\t\ts.Failure()\n\t\treturn nil, err\n\t}\n\ts.Successf(\"Configurations validated\")\n\n\ts = i.newStep(\"Checking installation source\")\n\tif i.Options.fromLocalSources {\n\t\ts.LogInfof(\"Installing Kyma from local path: '%s'\", i.Options.LocalSrcPath)\n\t} else {\n\t\tif i.Options.releaseVersion != i.Options.configVersion {\n\t\t\ts.LogInfof(\"Using the installation configuration from '%s'\", i.Options.configVersion)\n\t\t}\n\t\tif i.Options.remoteImage != \"\" {\n\t\t\ts.LogInfof(\"Installing Kyma with installer image '%s' \", i.Options.remoteImage)\n\t\t} else {\n\t\t\ts.LogInfof(\"Installing Kyma in version '%s' \", i.Options.releaseVersion)\n\t\t}\n\t}\n\ts.Successf(\"Installation source checked\")\n\n\ts = i.newStep(\"Installing Tiller\")\n\tif err := i.installTiller(); err != nil {\n\t\ts.Failure()\n\t\treturn nil, err\n\t}\n\ts.Successf(\"Tiller deployed\")\n\n\ts = i.newStep(\"Loading installation files\")\n\tresources, err := i.prepareFiles()\n\tif err != nil {\n\t\ts.Failure()\n\t\treturn nil, err\n\t}\n\ts.Successf(\"Installation files loaded\")\n\n\ts = i.newStep(\"Deploying Kyma Installer\")\n\tif err := i.installInstaller(resources); err != nil {\n\t\ts.Failure()\n\t\treturn nil, err\n\t}\n\ts.Successf(\"Kyma Installer deployed\")\n\n\tif !i.Options.CI {\n\t\ts = i.newStep(\"Configuring Helm\")\n\t\tif err := i.configureHelm(); err != nil {\n\t\t\ts.Failure()\n\t\t\treturn nil, err\n\t\t}\n\t\ts.Successf(\"Helm configured\")\n\t}\n\n\ts = i.newStep(\"Requesting Kyma Installer to install Kyma\")\n\tif err := i.activateInstaller(); err != nil {\n\t\ts.Failure()\n\t\treturn nil, err\n\t}\n\ts.Successf(\"Kyma Installer is installing Kyma\")\n\n\tif !i.Options.NoWait {\n\t\tif err := i.waitForInstaller(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tresult, err := i.buildResult()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}", "func setGPUEngine(clock, device int, name string) {\n\trequest := RpcRequest{(fmt.Sprintf(\"{\\\"command\\\":\\\"gpuengine\\\",\\\"parameter\\\":\\\"%v,%v\\\"}\", device, clock)), make(chan []byte), name}\n\trequest.Send()\n}", "func (r *GpuReconciler) SetupWithManager(mgr ctrl.Manager) error {\n\tr.Logger = ctrl.Log.WithName(\"gpu-controller\")\n\tr.Logger.V(1).Info(\"starting gpu controller\")\n\n\t// use clientSet to get resources from the API Server, not from Informer's cache\n\tclientSet, err := kubernetes.NewForConfig(mgr.GetConfig())\n\tif err != nil {\n\t\tr.Logger.Error(err, \"failed to init\")\n\t\treturn nil\n\t}\n\n\t// init node-gpu-info configmap\n\tr.Logger.V(1).Info(\"initializing node-gpu-info configmap\")\n\tif err := r.initGPUInfoCM(context.Background(), clientSet); err != nil {\n\t\treturn err\n\t}\n\n\t// build index for node which have GPU\n\tif err := mgr.GetFieldIndexer().IndexField(context.Background(), &corev1.Node{}, NodeIndexKey, func(rawObj client.Object) []string {\n\t\tnode := rawObj.(*corev1.Node)\n\t\tif _, ok := node.Labels[NvidiaGPUProduct]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\treturn []string{GPU}\n\t}); err != nil {\n\t\treturn err\n\t}\n\t// build index for pod which use GPU\n\tif err := mgr.GetFieldIndexer().IndexField(context.Background(), &corev1.Pod{}, PodIndexKey, func(rawObj client.Object) []string {\n\t\tpod := rawObj.(*corev1.Pod)\n\t\tif _, ok := pod.Spec.NodeSelector[NvidiaGPUProduct]; !ok {\n\t\t\treturn nil\n\t\t}\n\t\tif pod.Status.Phase == corev1.PodSucceeded {\n\t\t\treturn nil\n\t\t}\n\t\treturn []string{GPU}\n\t}); err != nil {\n\t\treturn err\n\t}\n\n\treturn ctrl.NewControllerManagedBy(mgr).\n\t\tFor(&corev1.Pod{}, builder.WithPredicates(predicate.Funcs{\n\t\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\t\treturn useGPU(event.Object)\n\t\t\t},\n\t\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\t\t_, ok := event.ObjectNew.(*corev1.Pod).Spec.NodeSelector[NvidiaGPUProduct]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tphaseOld := event.ObjectOld.(*corev1.Pod).Status.Phase\n\t\t\t\tphaseNew := event.ObjectNew.(*corev1.Pod).Status.Phase\n\t\t\t\treturn phaseOld != phaseNew\n\t\t\t},\n\t\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\t\treturn useGPU(event.Object)\n\t\t\t},\n\t\t})).\n\t\tWatches(&source.Kind{Type: &corev1.Node{}}, &handler.EnqueueRequestForObject{}, builder.WithPredicates(predicate.Funcs{\n\t\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\t\treturn hasGPU(event.Object)\n\t\t\t},\n\t\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\t\toldVal, oldOk := event.ObjectOld.(*corev1.Node).Status.Allocatable[NvidiaGPU]\n\t\t\t\tnewVal, newOk := event.ObjectNew.(*corev1.Node).Status.Allocatable[NvidiaGPU]\n\n\t\t\t\treturn oldOk && newOk && oldVal != newVal\n\t\t\t},\n\t\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\t\treturn hasGPU(event.Object)\n\t\t\t},\n\t\t})).\n\t\tComplete(r)\n}", "func (c *ClusterController) addSimulatorToPod(name string, pod corev1.Pod) error {\n\tcommand := fmt.Sprintf(\"onos devices add \\\"id: '%s', address: '%s:10161' version: '1.0.0' devicetype: 'Devicesim'\\\" --address 127.0.0.1:5150 --keyPath /etc/onos-config/certs/client1.key --certPath /etc/onos-config/certs/client1.crt\", name, name)\n\treturn c.execute(pod, []string{\"/bin/bash\", \"-c\", command})\n}", "func (a *Agent) UpgradeInstallChart(\n\tctx context.Context,\n\tconf *InstallChartConfig,\n\tdoAuth *oauth2.Config,\n\tdisablePullSecretsInjection bool,\n) (*release.Release, error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tfmt.Println(\"stacktrace from panic: \\n\" + string(debug.Stack()))\n\t\t}\n\t}()\n\n\tctx, span := telemetry.NewSpan(ctx, \"helm-upgrade-install-chart\")\n\tdefer span.End()\n\n\ttelemetry.WithAttributes(span,\n\t\ttelemetry.AttributeKV{Key: \"project-id\", Value: conf.Cluster.ProjectID},\n\t\ttelemetry.AttributeKV{Key: \"cluster-id\", Value: conf.Cluster.ID},\n\t\ttelemetry.AttributeKV{Key: \"chart-name\", Value: conf.Name},\n\t\ttelemetry.AttributeKV{Key: \"chart-namespace\", Value: conf.Namespace},\n\t)\n\n\tcmd := action.NewUpgrade(a.ActionConfig)\n\tcmd.Install = true\n\tif cmd.Version == \"\" && cmd.Devel {\n\t\tcmd.Version = \">0.0.0-0\"\n\t}\n\n\tcmd.Namespace = conf.Namespace\n\tcmd.Timeout = 300 * time.Second\n\n\tif err := checkIfInstallable(conf.Chart); err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error checking if installable\")\n\t}\n\n\tvar err error\n\n\tcmd.PostRenderer, err = NewPorterPostrenderer(\n\t\tconf.Cluster,\n\t\tconf.Repo,\n\t\ta.K8sAgent,\n\t\tconf.Namespace,\n\t\tconf.Registries,\n\t\tdoAuth,\n\t\tdisablePullSecretsInjection,\n\t)\n\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error getting post renderer\")\n\t}\n\n\tif req := conf.Chart.Metadata.Dependencies; req != nil {\n\t\tfor _, dep := range req {\n\t\t\tdepChart, err := loader.LoadChartPublic(ctx, dep.Repository, dep.Name, dep.Version)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, telemetry.Error(ctx, span, err, fmt.Sprintf(\"error retrieving chart dependency %s/%s-%s\", dep.Repository, dep.Name, dep.Version))\n\t\t\t}\n\n\t\t\tconf.Chart.AddDependency(depChart)\n\t\t}\n\t}\n\n\trelease, err := cmd.RunWithContext(ctx, conf.Name, conf.Chart, conf.Values)\n\tif err != nil {\n\t\treturn nil, telemetry.Error(ctx, span, err, \"error running helm upgrade\")\n\t}\n\n\treturn release, nil\n}", "func Install(ctx context.Context, toolkit *oceanv1.OceanToolkit, options *Options) error {\n\trenderValues := convertOceanToolkitSpecToValues(toolkit.Spec)\n\n\tb, err := yaml.Marshal(renderValues)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tf, err := ioutil.TempFile(os.TempDir(), \"ocean-toolkit\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer os.Remove(f.Name())\n\n\tf.Write(b)\n\tf.Close()\n\n\tchart := options.Chart\n\tif chart == \"\" {\n\t\tchart = chartPath(\"toolkit\", \"https://spotinst.github.io/ocean-charts/releases/stable\", \"0.0.1\")\n\t}\n\n\trenderOpts := &helm.Options{\n\t\tChart: chart,\n\t\tName: \"toolkit\",\n\t\tDebug: true,\n\t\tValues: options.Values,\n\t\tValueFiles: []string{f.Name()},\n\t\tNamespace: options.Namespace,\n\t}\n\n\tb, err = helm.Render(renderOpts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif options.Writer != nil {\n\t\toptions.Writer.Write(b)\n\t}\n\n\treturn nil\n}", "func chaosEventHandler(obj interface{}, eventType string, stream chan types.WorkflowEvent, startTime int64) {\n\tworkflowObj := obj.(*chaosTypes.ChaosEngine)\n\tif workflowObj.Labels[\"workflow_id\"] == \"\" {\n\t\tlogrus.WithFields(map[string]interface{}{\n\t\t\t\"uid\": string(workflowObj.ObjectMeta.UID),\n\t\t\t\"wf_id\": workflowObj.Labels[\"workflow_id\"],\n\t\t\t\"cluster_id\": workflowObj.Labels[\"cluster_id\"],\n\t\t}).Printf(\"CHAOSENGINE RUN IGNORED [INVALID METADATA]\")\n\t\treturn\n\t}\n\n\tif workflowObj.ObjectMeta.CreationTimestamp.Unix() < startTime {\n\t\treturn\n\t}\n\n\tcfg, err := k8s.GetKubeConfig()\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"could not get kube config\")\n\t}\n\n\tchaosClient, err := litmusV1alpha1.NewForConfig(cfg)\n\tif err != nil {\n\t\tlogrus.WithError(err).Fatal(\"could not get Chaos ClientSet\")\n\t}\n\n\tnodes := make(map[string]types.Node)\n\tlogrus.Print(\"STANDALONE CHAOSENGINE EVENT \", workflowObj.UID, \" \", eventType)\n\tvar cd *types.ChaosData = nil\n\n\t//extracts chaos data\n\tcd, err = getChaosData(v1alpha1.NodeStatus{StartedAt: workflowObj.ObjectMeta.CreationTimestamp}, workflowObj.Name, workflowObj.Namespace, chaosClient)\n\tif err != nil {\n\t\tlogrus.WithError(err).Print(\"FAILED PARSING CHAOS ENGINE CRD\")\n\t}\n\n\t// considering chaos events has only 1 artifact with manifest as raw data\n\tfinTime := int64(-1)\n\tif workflowObj.Status.EngineStatus == chaosTypes.EngineStatusCompleted || workflowObj.Status.EngineStatus == chaosTypes.EngineStatusStopped {\n\t\tif len(workflowObj.Status.Experiments) > 0 {\n\t\t\tfinTime = workflowObj.Status.Experiments[0].LastUpdateTime.Unix()\n\t\t}\n\t}\n\n\tnodes[workflowObj.Name] = types.Node{\n\t\tName: workflowObj.Name,\n\t\tPhase: \"Succeeded\",\n\t\tStartedAt: StrConvTime(workflowObj.CreationTimestamp.Unix()),\n\t\tFinishedAt: StrConvTime(finTime),\n\t\tChildren: []string{workflowObj.Name + \"-engine\"},\n\t\tType: \"Steps\",\n\t}\n\tdetails := types.Node{\n\t\tName: workflowObj.Name,\n\t\tPhase: mapStatus(workflowObj.Status.EngineStatus),\n\t\tType: \"ChaosEngine\",\n\t\tStartedAt: StrConvTime(workflowObj.CreationTimestamp.Unix()),\n\t\tFinishedAt: StrConvTime(finTime),\n\t\tChildren: []string{},\n\t\tChaosExp: cd,\n\t\tMessage: string(workflowObj.Status.EngineStatus),\n\t}\n\n\tif cd != nil && strings.ToLower(cd.ExperimentVerdict) == \"fail\" {\n\t\tdetails.Phase = \"Failed\"\n\t\tdetails.Message = \"Chaos Experiment Failed\"\n\t}\n\n\tnodes[workflowObj.Name+\"-engine\"] = details\n\tworkflow := types.WorkflowEvent{\n\t\tWorkflowType: \"chaosengine\",\n\t\tWorkflowID: workflowObj.Labels[\"workflow_id\"],\n\t\tEventType: eventType,\n\t\tUID: string(workflowObj.ObjectMeta.UID),\n\t\tNamespace: workflowObj.ObjectMeta.Namespace,\n\t\tName: workflowObj.ObjectMeta.Name,\n\t\tCreationTimestamp: StrConvTime(workflowObj.ObjectMeta.CreationTimestamp.Unix()),\n\t\tPhase: details.Phase,\n\t\tMessage: details.Message,\n\t\tStartedAt: details.StartedAt,\n\t\tFinishedAt: details.FinishedAt,\n\t\tNodes: nodes,\n\t}\n\n\t//stream\n\tstream <- workflow\n}", "func TestMemoryBackend(t *testing.T) {\n\tm, err := NewMemoryRepository(context.TODO())\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := m.PublishKey(context.TODO(), \"a\", \"akey\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := m.PublishKey(context.TODO(), \"b\", \"bkey\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tvar k string\n\tif k, err = m.LookupKey(context.TODO(), \"a\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif k != \"akey\" {\n\t\tt.Fatalf(\"Key for a: got %q, want %q\", k, \"akey\")\n\t}\n\tif k, err = m.LookupKey(context.TODO(), \"b\"); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif k != \"bkey\" {\n\t\tt.Fatalf(\"Key for b: got %q, want %q\", k, \"bkey\")\n\t}\n}", "func (b *Benchmark) SetUnifiedMemory() {\n\tpanic(\"unified memory is not supported by dnn workloads\")\n}", "func (b *Benchmark) SetUnifiedMemory() {\n\tpanic(\"unified memory is not supported by dnn workloads\")\n}", "func injectWorkerPara(pod *v1.Pod, workerPara *WorkerPara, object CommonInterface) {\n\t// inject our predefined volumes/envs\n\tvolumeMounts, volumes := CreateVolumeMap(workerPara)\n\tenvs := CreateEnvVars(workerPara.env)\n\tpod.Spec.Volumes = append(pod.Spec.Volumes, volumes...)\n\tfor idx := range pod.Spec.Containers {\n\t\tpod.Spec.Containers[idx].Env = append(\n\t\t\tpod.Spec.Containers[idx].Env, envs...,\n\t\t)\n\t\tpod.Spec.Containers[idx].VolumeMounts = append(\n\t\t\tpod.Spec.Containers[idx].VolumeMounts, volumeMounts...,\n\t\t)\n\t}\n\n\t// inject our labels\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tfor k, v := range GenerateLabels(object) {\n\t\tpod.Labels[k] = v\n\t}\n\n\tpod.GenerateName = object.GetName() + \"-\" + strings.ToLower(workerPara.workerType) + \"-\"\n\n\tpod.Namespace = object.GetNamespace()\n\n\tif workerPara.hostNetwork {\n\t\t// FIXME\n\t\t// force to set hostnetwork\n\t\tpod.Spec.HostNetwork = true\n\t}\n\n\tif pod.Spec.RestartPolicy == \"\" {\n\t\tpod.Spec.RestartPolicy = workerPara.restartPolicy\n\t}\n}", "func InstallCRD(cl client.Client) error {\n\tcrdMutex.Lock()\n\tdefer crdMutex.Unlock()\n\n\tfile, err := os.Open(\"config/iter8/iter8.tools_experiments.yaml\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer file.Close()\n\n\tbuf := &bytes.Buffer{}\n\tif _, err = buf.ReadFrom(file); err != nil {\n\t\treturn err\n\t}\n\n\tcrd, err := decodeCRD(string(buf.Bytes()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = createCRD(cl, crd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Test_UniformRegistration_RegistrationOfKeptnIntegration(t *testing.T) {\n\tdefer func(t *testing.T) {\n\t\tPrintLogsOfPods(t, []string{\"shipyard-controller\"})\n\t}(t)\n\n\t// make sure the echo-service uses the same distributor as Keptn core\n\timageName, err := GetImageOfDeploymentContainer(\"lighthouse-service\", \"lighthouse-service\")\n\trequire.Nil(t, err)\n\tdistributorImage := strings.Replace(imageName, \"lighthouse-service\", \"distributor\", 1)\n\n\techoServiceManifestContent := strings.ReplaceAll(echoServiceK8sManifest, \"${distributor-image}\", distributorImage)\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${queue-group}\", \"\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-endpoint}\", \"\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-token}\", \"\")\n\n\ttmpFile, err := CreateTmpFile(\"echo-service-*.yaml\", echoServiceManifestContent)\n\tdefer func() {\n\t\tif err := os.Remove(tmpFile); err != nil {\n\t\t\tt.Logf(\"Could not delete file: %v\", err)\n\t\t}\n\t}()\n\ttestUniformIntegration(t, func() {\n\t\t// install echo integration\n\t\t_, err = KubeCtlApplyFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\n\t\terr = waitForDeploymentToBeRolledOut(false, echoServiceName, GetKeptnNameSpaceFromEnv())\n\t\trequire.Nil(t, err)\n\n\t}, func() {\n\t\terr := KubeCtlDeleteFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\t})\n}", "func (m *AmbulanceMutation) AddEnginepower(i int) {\n\tif m.addenginepower != nil {\n\t\t*m.addenginepower += i\n\t} else {\n\t\tm.addenginepower = &i\n\t}\n}", "func experimentExecution(experimentsDetails *experimentTypes.ExperimentDetails, clients clients.ClientSets, resultDetails *types.ResultDetails, eventsDetails *types.EventDetails, chaosDetails *types.ChaosDetails) error {\n\n\t// Get the target pod details for the chaos execution\n\t// if the target pod is not defined it will derive the random target pod list using pod affected percentage\n\tif experimentsDetails.TargetPods == \"\" && chaosDetails.AppDetail.Label == \"\" {\n\t\treturn errors.Errorf(\"please provide either of the appLabel or TARGET_PODS\")\n\t}\n\ttargetPodList, err := common.GetPodList(experimentsDetails.TargetPods, experimentsDetails.PodsAffectedPerc, clients, chaosDetails)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tpodNames := []string{}\n\tfor _, pod := range targetPodList.Items {\n\t\tpodNames = append(podNames, pod.Name)\n\t}\n\tlog.Infof(\"Target pods list for chaos, %v\", podNames)\n\n\t//Get the target container name of the application pod\n\tif experimentsDetails.TargetContainer == \"\" {\n\t\texperimentsDetails.TargetContainer, err = common.GetTargetContainer(experimentsDetails.AppNS, targetPodList.Items[0].Name, clients)\n\t\tif err != nil {\n\t\t\treturn errors.Errorf(\"unable to get the target container name, err: %v\", err)\n\t\t}\n\t}\n\n\tswitch strings.ToLower(experimentsDetails.Sequence) {\n\tcase \"serial\":\n\t\tif err = injectChaosInSerialMode(experimentsDetails, targetPodList, clients, resultDetails, eventsDetails, chaosDetails); err != nil {\n\t\t\treturn err\n\t\t}\n\tcase \"parallel\":\n\t\tif err = injectChaosInParallelMode(experimentsDetails, targetPodList, clients, resultDetails, eventsDetails, chaosDetails); err != nil {\n\t\t\treturn err\n\t\t}\n\tdefault:\n\t\treturn errors.Errorf(\"%v sequence is not supported\", experimentsDetails.Sequence)\n\t}\n\n\treturn nil\n}", "func (c *client) SetupContainer(ctx context.Context, ctn *pipeline.Container) error {\n\tlogrus.Tracef(\"setting up for container %s\", ctn.ID)\n\n\t// create the container object for the pod\n\t//\n\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#Container\n\tcontainer := v1.Container{\n\t\tName: ctn.ID,\n\t\t// create the container with the kubernetes/pause image\n\t\t//\n\t\t// This is done due to the nature of how containers are\n\t\t// executed inside the pod. Kubernetes will attempt to\n\t\t// start and run all containers in the pod at once. We\n\t\t// want to control the execution of the containers\n\t\t// inside the pod so we use the pause image as the\n\t\t// default for containers, and then sequentially patch\n\t\t// the containers with the proper image.\n\t\t//\n\t\t// https://hub.docker.com/r/kubernetes/pause\n\t\tImage: image.Parse(\"kubernetes/pause:latest\"),\n\t\tEnv: []v1.EnvVar{},\n\t\tStdin: false,\n\t\tStdinOnce: false,\n\t\tTTY: false,\n\t\tWorkingDir: ctn.Directory,\n\t\tImagePullPolicy: v1.PullAlways,\n\t}\n\n\t// check if the environment is provided\n\tif len(ctn.Environment) > 0 {\n\t\t// iterate through each element in the container environment\n\t\tfor k, v := range ctn.Environment {\n\t\t\t// add key/value environment to container config\n\t\t\tcontainer.Env = append(container.Env, v1.EnvVar{Name: k, Value: v})\n\t\t}\n\t}\n\n\t// check if the entrypoint is provided\n\tif len(ctn.Entrypoint) > 0 {\n\t\t// add entrypoint to container config\n\t\tcontainer.Args = ctn.Entrypoint\n\t}\n\n\t// check if the commands are provided\n\tif len(ctn.Commands) > 0 {\n\t\t// add commands to container config\n\t\tcontainer.Args = append(container.Args, ctn.Commands...)\n\t}\n\n\t// add the container definition to the pod spec\n\t//\n\t// https://pkg.go.dev/k8s.io/api/core/v1?tab=doc#PodSpec\n\tc.pod.Spec.Containers = append(c.pod.Spec.Containers, container)\n\n\treturn nil\n}", "func (s *SidecarInjectField) Inject(pod *corev1.Pod) {\n\tlog.Info(fmt.Sprintf(\"inject pod : %s\", pod.GenerateName))\n\t// add initcontrainers to spec\n\tif pod.Spec.InitContainers != nil {\n\t\tpod.Spec.InitContainers = append(pod.Spec.InitContainers, s.Initcontainer)\n\t} else {\n\t\tpod.Spec.InitContainers = []corev1.Container{s.Initcontainer}\n\t}\n\n\t// add volume to spec\n\tif pod.Spec.Volumes == nil {\n\t\tpod.Spec.Volumes = []corev1.Volume{}\n\t}\n\tpod.Spec.Volumes = append(pod.Spec.Volumes, s.SidecarVolume)\n\n\t// choose a specific container to inject\n\ttargetContainers := s.findInjectContainer(pod.Spec.Containers)\n\n\t// add volumemount and env to container\n\tfor i := range targetContainers {\n\t\tlog.Info(fmt.Sprintf(\"inject container : %s\", targetContainers[i].Name))\n\t\tif (*targetContainers[i]).VolumeMounts == nil {\n\t\t\t(*targetContainers[i]).VolumeMounts = []corev1.VolumeMount{}\n\t\t}\n\n\t\t(*targetContainers[i]).VolumeMounts = append((*targetContainers[i]).VolumeMounts, s.SidecarVolumeMount)\n\n\t\tif (*targetContainers[i]).Env != nil {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, s.Env)\n\t\t} else {\n\t\t\t(*targetContainers[i]).Env = []corev1.EnvVar{s.Env}\n\t\t}\n\n\t\t// envs to be append\n\t\tvar envsTBA []corev1.EnvVar\n\t\tfor j, envInject := range s.Envs {\n\t\t\tisExists := false\n\t\t\tfor _, envExists := range targetContainers[i].Env {\n\t\t\t\tif strings.EqualFold(envExists.Name, envInject.Name) {\n\t\t\t\t\tisExists = true\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !isExists {\n\t\t\t\tenvsTBA = append(envsTBA, s.Envs[j])\n\t\t\t}\n\t\t}\n\t\tif len(s.Envs) > 0 {\n\t\t\t(*targetContainers[i]).Env = append((*targetContainers[i]).Env, envsTBA...)\n\t\t}\n\t}\n}", "func Test_UniformRegistration_RegistrationOfKeptnIntegrationMultiplePods(t *testing.T) {\n\tdefer func(t *testing.T) {\n\t\tPrintLogsOfPods(t, []string{\"shipyard-controller\"})\n\t}(t)\n\n\t// make sure the echo-service uses the same distributor as Keptn core\n\timageName, err := GetImageOfDeploymentContainer(\"lighthouse-service\", \"lighthouse-service\")\n\trequire.Nil(t, err)\n\tdistributorImage := strings.Replace(imageName, \"lighthouse-service\", \"distributor\", 1)\n\n\techoServiceManifestContent := strings.ReplaceAll(echoServiceK8sManifest, \"${distributor-image}\", distributorImage)\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"replicas: 1\", \"replicas: 3\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${queue-group}\", \"echo-service\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-endpoint}\", \"\")\n\techoServiceManifestContent = strings.ReplaceAll(echoServiceManifestContent, \"${api-token}\", \"\")\n\n\ttmpFile, err := CreateTmpFile(\"echo-service-*.yaml\", echoServiceManifestContent)\n\tdefer func() {\n\t\tif err := os.Remove(tmpFile); err != nil {\n\t\t\tt.Logf(\"Could not delete file: %v\", err)\n\t\t}\n\t}()\n\ttestUniformIntegration(t, func() {\n\t\t// install echo integration\n\t\t_, err = KubeCtlApplyFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\n\t\terr = waitForDeploymentToBeRolledOut(false, echoServiceName, GetKeptnNameSpaceFromEnv())\n\t\trequire.Nil(t, err)\n\n\t}, func() {\n\t\terr := KubeCtlDeleteFromURL(tmpFile)\n\t\trequire.Nil(t, err)\n\t}, true)\n}", "func elasticSearchContainerSpec(cr *wp.WebProject) corev1.Container {\n\timage := \"elasticsearch:7.10.1\"\n\tcontainer := corev1.Container{\n\t\tImage: image,\n\t\tName: \"search\",\n\t\tPorts: []corev1.ContainerPort{\n\t\t\t{\n\t\t\t\tContainerPort: int32(9200),\n\t\t\t\tName: \"reset-port\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerPort: int32(9300),\n\t\t\t\tName: \"intra-node-port\",\n\t\t\t},\n\t\t},\n\t\tLifecycle: &corev1.Lifecycle{\n\t\t\tPostStart: &corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t/*StartupProbe: &corev1.Probe{\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tPeriodSeconds: 2,\n\t\t\tHandler: corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},*/\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"discovery.type\",\n\t\t\t\tValue: \"single-node\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"ES_JAVA_OPTS\",\n\t\t\t\tValue: \"-Xms512m -Xmx512m\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAME\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.name\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_ID\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.uid\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAMESPACE\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tVolumeMounts: getElasticSearchVolumeMounts(cr),\n\n\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\tAllowPrivilegeEscalation: createBool(false),\n\t\t\tReadOnlyRootFilesystem: createBool(false),\n\t\t\tRunAsNonRoot: createBool(false),\n\t\t},\n\t}\n\n\tif cr.Spec.SearchSidecar.CronJob.Enabled {\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{\n\t\t\tName: \"search-cron-script\",\n\t\t\tMountPath: \"/opt/script\",\n\t\t})\n\t}\n\n\treturn container\n}", "func NewEngine(ctx context.Context, config *types.Config) (*Engine, error) {\n\tengine := &Engine{}\n\tdocker, err := utils.MakeDockerClient(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstore, err := corestore.NewClient(ctx, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// get self\n\tnode, err := store.GetNode(config.HostName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tengine.config = config\n\tengine.store = store\n\tengine.docker = docker\n\tengine.node = node\n\tengine.nodeIP = dockerengine.GetIP(node.Endpoint)\n\tif engine.nodeIP == \"\" {\n\t\tengine.nodeIP = common.LocalIP\n\t}\n\tlog.Infof(\"[NewEngine] Host IP %s\", engine.nodeIP)\n\tengine.dockerized = os.Getenv(common.DOCKERIZED) != \"\"\n\tif engine.dockerized {\n\t\tos.Setenv(\"HOST_PROC\", \"/hostProc\")\n\t}\n\tcpus, err := cpu.Info()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"[NewEngine] Host has %d cpus\", len(cpus))\n\tmemory, err := mem.VirtualMemory()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Infof(\"[NewEngine] Host has %d memory\", memory.Total)\n\tengine.cpuCore = float64(len(cpus))\n\tengine.memory = int64(memory.Total)\n\tengine.transfers = utils.NewHashBackends(config.Metrics.Transfers)\n\tengine.forwards = utils.NewHashBackends(config.Log.Forwards)\n\treturn engine, nil\n}", "func PodMemory(pod *api.Pod) *resource.Quantity {\n\tval := int64(0)\n\tfor j := range pod.Spec.Containers {\n\t\tval = val + pod.Spec.Containers[j].Resources.Limits.Memory().Value()\n\t}\n\treturn resource.NewQuantity(int64(val), resource.DecimalSI)\n}", "func installChartOrDie(ctx context.Context, cs *kubernetes.Clientset, domain, registry, name, namespace, chartPath string, appManagement bool) {\n\t// ensure namespace for chart exists\n\tif _, err := cs.CoreV1().Namespaces().Create(ctx,\n\t\t&corev1.Namespace{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: namespace,\n\t\t\t},\n\t\t},\n\t\tmetav1.CreateOptions{}); err != nil && !apierrors.IsAlreadyExists(err) {\n\t\tlog.Fatalf(\"Failed to create %s namespace: %v.\", namespace, err)\n\t}\n\n\tvars := helmValuesStringFromMap(map[string]string{\n\t\t\"domain\": domain,\n\t\t\"registry\": registry,\n\t\t\"project\": *project,\n\t\t\"app_management\": strconv.FormatBool(appManagement),\n\t\t\"cr_syncer\": strconv.FormatBool(*crSyncer),\n\t\t\"fluentd\": strconv.FormatBool(*fluentd),\n\t\t\"fluentbit\": strconv.FormatBool(*fluentbit),\n\t\t\"log_prefix_subdomain\": *logPrefixSubdomain,\n\t\t\"docker_data_root\": *dockerDataRoot,\n\t\t\"pod_cidr\": *podCIDR,\n\t\t\"robot_authentication\": strconv.FormatBool(*robotAuthentication),\n\t\t\"robot.name\": *robotName,\n\t})\n\tlog.Printf(\"Installing %s chart using Synk from %s\", name, chartPath)\n\n\toutput, err := exec.Command(\n\t\thelmPath,\n\t\t\"template\",\n\t\t\"--set-string\", vars,\n\t\t\"--name\", name,\n\t\t\"--namespace\", namespace,\n\t\tfilepath.Join(filesDir, chartPath),\n\t).CombinedOutput()\n\tif err != nil {\n\t\tlog.Fatalf(\"Synk install of %s failed: %v\\nHelm output:\\n%s\\n\", name, err, output)\n\t}\n\tcmd := exec.Command(\n\t\tsynkPath,\n\t\t\"apply\",\n\t\tname,\n\t\t\"-n\", namespace,\n\t\t\"-f\", \"-\",\n\t)\n\t// Helm writes the templated manifests and errors alike to stderr.\n\t// So we can just take the combined output as is.\n\tcmd.Stdin = bytes.NewReader(output)\n\n\tif output, err = cmd.CombinedOutput(); err != nil {\n\t\tlog.Fatalf(\"Synk install of %s failed: %v\\nSynk output:\\n%s\\n\", name, err, output)\n\t}\n}", "func (o *PacmanOS) InstallMQTT() error {\n\tcmd := NewCommand(\"ps aux |awk '/mosquitto/ {print $11}' | awk '/mosquit/ {print}'\")\n\tif err := cmd.Exec(); err != nil {\n\t\treturn err\n\t}\n\n\tif stdout := cmd.GetStdOut(); stdout != \"\" {\n\t\tfmt.Println(\"Host has\", stdout, \"already installed and running. Hence skipping the installation steps !!!\")\n\t\treturn nil\n\t}\n\n\t// Install mqttInst\n\tcmd = NewCommand(\"pacman -Syy --noconfirm mosquitto\")\n\tif err := cmd.Exec(); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(cmd.GetStdOut())\n\n\tfmt.Println(\"MQTT is installed in this host\")\n\n\treturn nil\n}", "func (e *engine) Setup(ctx context.Context, spec *Spec) error {\n\treturn nil\n}", "func (bench Recovery) Setup() error {\n\t// Start container on specific host.\n\n\tlog.Info(\"Setting up DC/OS recovery benchmark\")\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // ingore unsigned cert\n\t}\n\tconfig := marathon.NewDefaultConfig()\n\tconfig.URL = bench.Config[\"dcosurl\"]\n\tconfig.DCOSToken = bench.Config[\"dcosacstoken\"]\n\tconfig.HTTPClient = &http.Client{Transport: tr}\n\tclient, err := marathon.NewClient(config)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create a client for Marathon: %s\", err)\n\t}\n\t// create\n\t// TODO prefetch\n\tlog.Info(\"Deploying a new application\")\n\tapplication := new(marathon.Application).\n\t\tName(\"bench1\").\n\t\tCPU(0.5).\n\t\tMemory(64).\n\t\tStorage(0.0).\n\t\tCount(1).\n\t\tAddArgs(\"/bin/sleep\", \"100000\")\n\n\tapp, err := client.CreateApplication(application)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create application %s: %s\", application, err)\n\t}\n\tlog.Infof(\"Creating the application: %s\", application)\n\n\t// Wait for deployment with no timeout \n\terr = client.WaitOnDeployment(app.Deployments[0][\"id\"], 0)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to list application: %s\", err)\n\t}\n\treturn nil\n}", "func AddToManager(ctx context.Context, logger logr.Logger, lsMgr manager.Manager, hostMgr manager.Manager, config config.AgentConfiguration) error {\n\tlog := logger.WithName(\"agent\")\n\t// create direct client for the agent to ensure the landscaper resources\n\tlsClient, err := client.New(lsMgr.GetConfig(), client.Options{\n\t\tScheme: lsMgr.GetScheme(),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create direct landscaper kubernetes client: %w\", err)\n\t}\n\thostClient, err := client.New(hostMgr.GetConfig(), client.Options{\n\t\tScheme: hostMgr.GetScheme(),\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to create direct landscaper kubernetes client: %w\", err)\n\t}\n\tagent := New(log,\n\t\tlsMgr.GetClient(),\n\t\tlsMgr.GetConfig(),\n\t\tlsMgr.GetScheme(),\n\t\thostMgr.GetClient(),\n\t\thostMgr.GetConfig(),\n\t\thostMgr.GetScheme(),\n\t\tconfig,\n\t)\n\n\tif _, err := agent.EnsureLandscaperResources(ctx, lsClient, hostClient); err != nil {\n\t\treturn fmt.Errorf(\"unable to ensure landscaper resources: %w\", err)\n\t}\n\tif _, err := agent.EnsureHostResources(ctx, hostClient); err != nil {\n\t\treturn fmt.Errorf(\"unable to ensure host resources: %w\", err)\n\t}\n\n\terr = builder.ControllerManagedBy(lsMgr).\n\t\tFor(&lsv1alpha1.Environment{}).\n\t\tWithLogger(log).\n\t\tComplete(agent)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// register helm deployer.\n\thelmConfig := helmv1alpha1.Configuration{}\n\thelmConfig.Identity = fmt.Sprintf(\"agent-helm-deployer-%s\", config.Name)\n\thelmConfig.OCI = config.OCI\n\thelmConfig.TargetSelector = []lsv1alpha1.TargetSelector{\n\t\t{\n\t\t\tTargets: []lsv1alpha1.ObjectReference{{Name: config.Name}},\n\t\t},\n\t}\n\tif err := helmctlr.AddDeployerToManager(log, lsMgr, hostMgr, helmConfig); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func installAllHelm(root, profile string) error {\n\tparser := yaml.NewParser()\n\terr := parser.Parse(profile)\n\tif err != nil {\n\t\tlog.Fatalf(\"parser.Parse profile error: err=%s\", err)\n\t}\n\texec := exec.NewExec(root)\n\tfor _, su := range parser.Profile.ServiceUnits {\n\t\tfor _, app := range su.Applications {\n\t\t\tshell := exec.Install(su.Name, parser.Profile.Namespace, app.Name)\n\t\t\tlog.Infof(\"InstallAllCharts: root=%s, profile=%s, su=%s, app=%s, shell=%v\",\n\t\t\t\troot, profile, su.Name, app.Name, shell)\n\t\t\terr := exec.Do(shell)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Helm install error: err=%s\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func newEchoServerPodSpec(podName string) *api.Pod {\n\tport := 8080\n\tpod := &api.Pod{\n\t\tObjectMeta: api.ObjectMeta{\n\t\t\tName: podName,\n\t\t},\n\t\tSpec: api.PodSpec{\n\t\t\tContainers: []api.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"echoserver\",\n\t\t\t\t\tImage: \"gcr.io/google_containers/echoserver:1.4\",\n\t\t\t\t\tPorts: []api.ContainerPort{{ContainerPort: int32(port)}},\n\t\t\t\t},\n\t\t\t},\n\t\t\tRestartPolicy: api.RestartPolicyNever,\n\t\t},\n\t}\n\treturn pod\n}", "func RegisterEngine(name string, e Engine) {\n\tengines[name] = e\n}", "func helmUpgrade() error {\n\tprojectName := projectConfig.GetString(\"project_name\")\n\tenvironment := projectConfig.GetString(\"environment\")\n\n\tcolor.Cyan(\"Installing project chart via helm...\")\n\n\tvar waitFlag string\n\tif projectConfig.GetBool(\"wait\") {\n\t\t// Intended for CI, wait for updated infrastructure to apply fully so subsequent commands (drush) run against new infra\n\t\twaitFlag = \"--wait\"\n\t\tcolor.Cyan(\"Using wait, command will take a moment...\")\n\t}\n\n\tvar helmValues HelmValues\n\n\thelmValues.appendValue(\"general.project_name\", projectName, true);\n\thelmValues.appendValue(\"general.environment\", environment, true);\n\n\t// These come from environment vars\n\t// TODO - Blackfire credential management? Currently deploying to both environments - MEA\n\thelmValues.appendProjectValue(\"applications.blackfire.server_id\", \"BLACKFIRE_SERVER_ID\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.server_token\", \"BLACKFIRE_SERVER_TOKEN\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.client_id\", \"BLACKFIRE_CLIENT_ID\", false)\n\thelmValues.appendProjectValue(\"applications.blackfire.client_token\", \"BLACKFIRE_CLIENT_TOKEN\", false)\n\n\t// Derived values\n\tif environment == \"local\" {\n\t\t// Using https://github.com/mstrzele/minikube-nfs\n\t\t// Creates a persistent volume with contents of /Users mounted from an nfs share from host\n\t\t// So rather than using /Users directly, grab the path within the project\n\t\t// Check the helm chart mounts\n\t\tprojectPath, _ := util.ExecCmdChain(\"printf ${PWD#/Users/}\")\n\t\thelmValues.appendValue(\"applications.drupal.local.project_root\", projectPath, true)\n\t\tlocalIp, _ := util.ExecCmdChain(\"ifconfig | grep \\\"inet \\\" | grep -v 127.0.0.1 | awk '{print $2}' | sed -n 1p\")\n\t\thelmValues.appendValue(\"applications.xdebug.host_ip\", localIp, true)\n\t} else {\n\t\t// Obtain the git commit from env vars if present in CircleCI\n\t\t// TODO - Make this a required argument rather than inferred environment variable\n\t\tif circleSha := projectConfig.GetString(\"CIRCLE_SHA1\"); len(circleSha) > 0 {\n\t\t\thelmValues.appendValue(\"general.git_commit\", circleSha, false)\n\t\t} else {\n\t\t\tif approve := util.GetApproval(\"No CIRCLE_SHA1 environment variable set (should be git sha1 hash of commit), use 'latest' tag for application container?\"); !approve {\n\t\t\t\tcolor.Red(\"User exited. Please run 'export CIRCLE_SHA1=' adding your targetted git commit hash, or run again and agree to use 'latest.'\")\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t}\n\t}\n\n\tchartConfigPath := fmt.Sprintf(\"charts.%s\", environment)\n\thelmChartPath := projectConfig.GetString(chartConfigPath)\n\n\tcommand := fmt.Sprintf(\"helm upgrade --install --values %s %s %s-%s %s --set %s\",\n\t\tenvConfig.ConfigFileUsed(),\n\t\twaitFlag,\n\t\tprojectName,\n\t\tenvironment,\n\t\thelmChartPath,\n\t\tstrings.Join(helmValues.values, \",\"))\n\tout, err := util.ExecCmdChainCombinedOut(command)\n\tif (err != nil) {\n\t\tcolor.Red(out)\n\t\tif (projectConfig.GetBool(\"rollback-on-failure\")) {\n\t\t\tcolor.Yellow(\"Your helm upgrade resulted in a failure, attempting to rollback...\")\n\t\t\trollbackCmd.Run(nil, nil)\n\t\t\tcolor.Yellow(\"Successfully rolled back attempted update, exiting with error. You will want to correct this.\")\n\t\t\tos.Exit(1)\n\t\t} else {\n\t\t\tos.Exit(1)\n\t\t}\n\t} else if debugMode := viper.GetString(\"debug\"); len(debugMode) > 0 {\n\t\tcolor.Green(out)\n\t}\n\treturn err\n}", "func (j *ServiceTestJig) launchEchoserverPodOnNode(f *framework.Framework, nodeName, podName string) {\n\tframework.Logf(\"Creating echo server pod %q in namespace %q\", podName, f.Namespace.Name)\n\tpod := newEchoServerPodSpec(podName)\n\tpod.Spec.NodeName = nodeName\n\tpod.ObjectMeta.Labels = j.Labels\n\tpodClient := f.Client.Pods(f.Namespace.Name)\n\t_, err := podClient.Create(pod)\n\tframework.ExpectNoError(err)\n\tframework.ExpectNoError(f.WaitForPodRunning(podName))\n\tframework.Logf(\"Echo server pod %q in namespace %q running\", pod.Name, f.Namespace.Name)\n}", "func GetGPUMemoryFromPodAnnotation(pod *v1.Pod) (gpuMemory uint) {\n\tif len(pod.ObjectMeta.Annotations) > 0 {\n\t\tvalue, found := pod.ObjectMeta.Annotations[EnvResourceByPod]\n\t\tif found {\n\t\t\ts, _ := strconv.Atoi(value)\n\t\t\tif s < 0 {\n\t\t\t\ts = 0\n\t\t\t}\n\n\t\t\tgpuMemory += uint(s)\n\t\t}\n\t}\n\n\tlog.V(100).Info(\"debug: pod %s in ns %s with status %v has GPU Mem %d\",\n\t\tpod.Name,\n\t\tpod.Namespace,\n\t\tpod.Status.Phase,\n\t\tgpuMemory)\n\treturn gpuMemory\n}", "func initEngine() {\n\tgo measureSystemRessources()\n}", "func (view *ViewPodDemo) DemoCrashContainer() {\n\n\tpod := view.randomPod()\n\tlog.Printf(\"Random pod: %v\", pod)\n\tview.updateStatus(pod, PodStatusSequenceCrash)\n}", "func RunPod(ctx context.Context, pod corev1.Pod,\n\tts oauth2.TokenSource, watcherImage, project, zone, machineType string) error {\n\n\tsvc, err := compute.NewService(ctx, option.WithTokenSource(ts))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb, err := yaml.Marshal(pod)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpodstr := string(b)\n\tlog.Println(\"POD MANIFEST:\\n\", podstr) // TODO remove\n\n\tregion := zone[:strings.LastIndex(zone, \"-\")]\n\n\twatcherPod := fmt.Sprintf(watcherPodFmt, watcherImage)\n\n\tname := \"instance-\" + uuid.New().String()[:4]\n\tlog.Printf(\"creating %q...\", name)\n\top, err := svc.Instances.Insert(project, zone, &compute.Instance{\n\t\tName: name,\n\t\tZone: zone,\n\t\tMachineType: fmt.Sprintf(\"projects/%s/zones/%s/machineTypes/%s\", project, zone, machineType),\n\t\tDisks: []*compute.AttachedDisk{{\n\t\t\tInitializeParams: &compute.AttachedDiskInitializeParams{\n\t\t\t\tSourceImage: \"projects/cos-cloud/global/images/family/cos-stable\",\n\t\t\t},\n\t\t\tBoot: true,\n\t\t}},\n\t\tNetworkInterfaces: []*compute.NetworkInterface{{\n\t\t\tSubnetwork: fmt.Sprintf(\"projects/%s/regions/%s/subnetworks/default\", project, region),\n\t\t\tAccessConfigs: []*compute.AccessConfig{{\n\t\t\t\tName: \"External NAT\",\n\t\t\t\tType: \"ONE_TO_ONE_NAT\",\n\t\t\t\tNetworkTier: \"PREMIUM\",\n\t\t\t}},\n\t\t}},\n\t\tServiceAccounts: []*compute.ServiceAccount{{\n\t\t\tEmail: \"[email protected]\",\n\t\t\tScopes: []string{\n\t\t\t\t// Permiission to pull private images (watcher)\n\t\t\t\t\"https://www.googleapis.com/auth/devstorage.read_only\",\n\n\t\t\t\t// Permission to write logs and metrics (google-fluentd)\n\t\t\t\t\"https://www.googleapis.com/auth/logging.write\",\n\t\t\t\t\"https://www.googleapis.com/auth/monitoring.write\",\n\t\t\t},\n\t\t}},\n\t\tMetadata: &compute.Metadata{\n\t\t\tItems: []*compute.MetadataItems{{\n\t\t\t\tKey: \"user-data\",\n\t\t\t\tValue: &cloudConfig,\n\t\t\t}, {\n\t\t\t\tKey: \"watcher\",\n\t\t\t\tValue: &watcherPod,\n\t\t\t}, {\n\t\t\t\tKey: \"pod\",\n\t\t\t\tValue: &podstr,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert\",\n\t\t\t\tValue: &caCert,\n\t\t\t}, {\n\t\t\t\tKey: \"ca-cert-key\",\n\t\t\t\tValue: &caCertKey,\n\t\t\t}, {\n\t\t\t\tKey: \"cos-metrics-enabled\",\n\t\t\t\tValue: &trueString,\n\t\t\t}},\n\t\t},\n\t\tTags: &compute.Tags{Items: []string{\"https-server\"}},\n\t\tShieldedInstanceConfig: &compute.ShieldedInstanceConfig{\n\t\t\tEnableSecureBoot: true,\n\t\t},\n\t}).Do()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstart := time.Now()\n\tfor ; ; time.Sleep(time.Second) {\n\t\top, err = svc.ZoneOperations.Get(project, zone, op.Name).Do()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"operation is %q...\", op.Status)\n\t\tif op.Status == \"DONE\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tlog.Println(\"startup took\", time.Since(start))\n\treturn nil\n}", "func (engineDetails EngineDetails) GetChaosEngine(clients ClientSets) (*v1alpha1.ChaosEngine, error) {\n\texpEngine, err := clients.LitmusClient.LitmuschaosV1alpha1().ChaosEngines(engineDetails.AppNamespace).Get(engineDetails.Name, metav1.GetOptions{})\n\tif err != nil {\n\n\t\treturn nil, errors.Wrapf(err, \"Unable to get ChaosEngine Name: %v, in namespace: %v, due to error: %v\", engineDetails.Name, engineDetails.AppNamespace, err)\n\t}\n\treturn expEngine, nil\n}", "func (e *Evaluator) Allocate(pod *manifest.Pod, env map[string]string) {\n\tgo func() {\n\t\tvar alloc allocation.Pod\n\t\tif err := alloc.FromManifest(pod, env); err != nil {\n\t\t\treturn\n\t\t}\n\t\tselect {\n\t\tcase <-e.Control.Ctx().Done():\n\t\t\te.log.Errorf(`skip allocate %s: %v`, pod.Name, e.Control.Ctx().Err())\n\t\tcase e.allocateChan <- &alloc:\n\t\t\te.log.Tracef(`allocate: %s %d`, pod.Name, pod.Mark())\n\t\t}\n\t}()\n}", "func InstallCapability(client client.Client, mapper discoverymapper.DiscoveryMapper, centerName, capabilityName string, ioStreams cmdutil.IOStreams) error {\n\tdir, _ := system.GetCapCenterDir()\n\trepoDir := filepath.Join(dir, centerName)\n\ttp, err := GetCapabilityFromCenter(mapper, centerName, capabilityName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefDir, _ := system.GetCapabilityDir()\n\tfileContent, err := ioutil.ReadFile(filepath.Clean(filepath.Join(repoDir, tp.Name+\".yaml\")))\n\tif err != nil {\n\t\treturn err\n\t}\n\tswitch tp.Type {\n\tcase types.TypeComponentDefinition:\n\t\terr = InstallComponentDefinition(client, fileContent, ioStreams, &tp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase types.TypeTrait:\n\t\terr = InstallTraitDefinition(client, mapper, fileContent, ioStreams, &tp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\tcase types.TypeScope:\n\t\t// TODO(wonderflow): support install scope here\n\tcase types.TypeWorkload:\n\t\treturn fmt.Errorf(\"unsupported capability type %v\", types.TypeWorkload)\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported type: %v\", tp.Type)\n\t}\n\n\tsuccess := plugins.SinkTemp2Local([]types.Capability{tp}, defDir)\n\tif success == 1 {\n\t\tioStreams.Infof(\"Successfully installed capability %s from %s\\n\", capabilityName, centerName)\n\t}\n\treturn nil\n}", "func NewEngine() error {\n\t\n\treturn nil\n}", "func (e *Engine) PreStartGPU() error {\n\tdocker, err := getDockerClient()\n\tif err != nil {\n\t\treturn dockerError(err)\n\t}\n\tenvVariables := docker.LoadEnvVars()\n\tif val, ok := envVariables[config.GPUSupportEnvVar]; ok {\n\t\tif val == \"true\" {\n\t\t\tlog.Info(\"pre-start: setting up GPUs\")\n\t\t\tdefer log.Info(\"pre-start: done setting up GPUs\")\n\t\t\terr := e.nvidiaGPUManager.Setup()\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Nvidia GPU Manager: %v\", err)\n\t\t\t\treturn engineError(\"Nvidia GPU Manager\", err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func Install() error { return mageextras.Install() }", "func (addon *DockerregistryAddon) Install(args ...string) {\n\tnode := *addon.masterNode\n\t_, err := addon.communicator.RunCmd(node, \"helm install --set persistence.enabled=true stable/docker-registry\")\n\tFatalOnError(err)\n\tlog.Println(\"docker-registry installed\")\n}", "func installPCMarkComponents(ctx context.Context, uiDevice *ui.Device) (*ui.Object, error) {\n\t// PCMark needs in-app installation before it can show the RUN button.\n\t// Check if RUN or \"INSTALL\" button is available.\n\tvar btnRun, btnInstall *ui.Object\n\tif err := testing.Poll(ctx, func(ctx context.Context) error {\n\t\tif btnRun = buttonWithText(ctx, uiDevice, \"RUN\"); btnRun != nil {\n\t\t\treturn nil\n\t\t}\n\t\tif btnInstall = buttonWithRegex(ctx, uiDevice, `INSTALL\\(.*\\)`); btnInstall != nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"Neither RUN nor INSTALL button is available\")\n\t}, &testing.PollOptions{Timeout: 1 * time.Minute, Interval: 1 * time.Second}); err != nil {\n\t\treturn nil, err\n\t}\n\tif btnRun == nil && btnInstall != nil {\n\t\ttesting.ContextLog(ctx, \"Installing PCMark component\")\n\t\tif err := btnInstall.Click(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to intsall PCMark component\")\n\t\t}\n\t\tbtnConfirm := buttonWithText(ctx, uiDevice, \"INSTALL\")\n\t\tif btnConfirm == nil {\n\t\t\treturn nil, errors.New(\"failed to find install confirm button\")\n\t\t}\n\t\tif err := btnConfirm.Click(ctx); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to confirm PCMark component installation\")\n\t\t}\n\n\t\tif err := testing.Poll(ctx, func(context.Context) error {\n\t\t\t// RUN button will shown after the installation has finished.\n\t\t\tif btnRun = buttonWithText(ctx, uiDevice, \"RUN\"); btnRun == nil {\n\t\t\t\treturn errors.New(\"component installation has not completed yet\")\n\t\t\t}\n\t\t\treturn nil\n\t\t}, &testing.PollOptions{Timeout: 5 * time.Minute, Interval: 1 * time.Second}); err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to wait for component installation to complete\")\n\t\t}\n\t}\n\treturn btnRun, nil\n}", "func (m *manager) Install(ctx context.Context) error {\n\tsteps := map[api.InstallPhase][]steps.Step{\n\t\tapi.InstallPhaseBootstrap: m.bootstrap(),\n\t\tapi.InstallPhaseRemoveBootstrap: {\n\t\t\tsteps.Action(m.initializeKubernetesClients),\n\t\t\tsteps.Action(m.initializeOperatorDeployer), // depends on kube clients\n\t\t\tsteps.Action(m.removeBootstrap),\n\t\t\tsteps.Action(m.removeBootstrapIgnition),\n\t\t\tsteps.Action(m.configureAPIServerCertificate),\n\t\t\tsteps.Condition(m.apiServersReady, 30*time.Minute, true),\n\t\t\tsteps.Condition(m.minimumWorkerNodesReady, 30*time.Minute, true),\n\t\t\tsteps.Condition(m.operatorConsoleExists, 30*time.Minute, true),\n\t\t\tsteps.Action(m.updateConsoleBranding),\n\t\t\tsteps.Condition(m.operatorConsoleReady, 20*time.Minute, true),\n\t\t\tsteps.Action(m.disableSamples),\n\t\t\tsteps.Action(m.disableOperatorHubSources),\n\t\t\tsteps.Action(m.disableUpdates),\n\t\t\tsteps.Condition(m.clusterVersionReady, 30*time.Minute, true),\n\t\t\tsteps.Condition(m.aroDeploymentReady, 20*time.Minute, true),\n\t\t\tsteps.Action(m.updateClusterData),\n\t\t\tsteps.Action(m.configureIngressCertificate),\n\t\t\tsteps.Condition(m.ingressControllerReady, 30*time.Minute, true),\n\t\t\tsteps.Action(m.configureDefaultStorageClass),\n\t\t\tsteps.Action(m.finishInstallation),\n\t\t},\n\t}\n\n\terr := m.startInstallation(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif steps[m.doc.OpenShiftCluster.Properties.Install.Phase] == nil {\n\t\treturn fmt.Errorf(\"unrecognised phase %s\", m.doc.OpenShiftCluster.Properties.Install.Phase)\n\t}\n\tm.log.Printf(\"starting phase %s\", m.doc.OpenShiftCluster.Properties.Install.Phase)\n\treturn m.runSteps(ctx, steps[m.doc.OpenShiftCluster.Properties.Install.Phase], \"install\")\n}", "func getPodDefinition(configMapName string, test v1alpha3.TestConfiguration, r PodTestRunner) *v1.Pod {\n\n\treturn &v1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: fmt.Sprintf(\"scorecard-test-%s\", rand.String(4)),\n\t\t\tNamespace: r.Namespace,\n\t\t\tLabels: map[string]string{\n\t\t\t\t\"app\": \"scorecard-test\",\n\t\t\t\t\"testrun\": configMapName,\n\t\t\t},\n\t\t},\n\t\tSpec: v1.PodSpec{\n\t\t\tServiceAccountName: r.ServiceAccount,\n\t\t\tRestartPolicy: v1.RestartPolicyNever,\n\t\t\tContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"scorecard-test\",\n\t\t\t\t\tImage: test.Image,\n\t\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\t\tCommand: test.Entrypoint,\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMountPath: PodBundleRoot,\n\t\t\t\t\t\t\tName: \"scorecard-untar\",\n\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tEnv: []v1.EnvVar{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"SCORECARD_NAMESPACE\",\n\t\t\t\t\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\t\t\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tInitContainers: []v1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"scorecard-untar\",\n\t\t\t\t\tImage: r.UntarImage,\n\t\t\t\t\tImagePullPolicy: v1.PullIfNotPresent,\n\t\t\t\t\tArgs: []string{\n\t\t\t\t\t\t\"tar\",\n\t\t\t\t\t\t\"xvzf\",\n\t\t\t\t\t\t\"/scorecard/bundle.tar.gz\",\n\t\t\t\t\t\t\"-C\",\n\t\t\t\t\t\t\"/scorecard-bundle\",\n\t\t\t\t\t},\n\t\t\t\t\tVolumeMounts: []v1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMountPath: \"/scorecard\",\n\t\t\t\t\t\t\tName: \"scorecard-bundle\",\n\t\t\t\t\t\t\tReadOnly: true,\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tMountPath: \"/scorecard-bundle\",\n\t\t\t\t\t\t\tName: \"scorecard-untar\",\n\t\t\t\t\t\t\tReadOnly: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []v1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: \"scorecard-bundle\",\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tConfigMap: &v1.ConfigMapVolumeSource{\n\t\t\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\t\t\tName: configMapName,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"scorecard-untar\",\n\t\t\t\t\tVolumeSource: v1.VolumeSource{\n\t\t\t\t\t\tEmptyDir: &v1.EmptyDirVolumeSource{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func UpgradeInstallE(t *testing.T, options *helm.Options, chart string, releaseName string) error {\n\t// If the chart refers to a path, convert to absolute path. Otherwise, pass straight through as it may be a remote\n\t// chart.\n\tif files.FileExists(chart) {\n\t\tabsChartDir, err := filepath.Abs(chart)\n\t\tif err != nil {\n\t\t\treturn errors.WithStackTrace(err)\n\t\t}\n\t\tchart = absChartDir\n\t}\n\n\tvar err error\n\targs := []string{\"--install\", \"--force\"}\n\targs = append(args, getNamespaceArgs(options)...)\n\targs, err = getValuesArgsE(t, options, args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\targs = append(args, releaseName, chart)\n\t_, err = helm.RunHelmCommandAndGetOutputE(t, options, \"upgrade\", args...)\n\treturn err\n}", "func Install(releaseName, namespace string) error {\n\tvals, err := yaml.Marshal(map[string]interface{}{\n\t\t\"accessKey\": uniuri.NewLen(20),\n\t\t\"secretKey\": uniuri.NewLen(40),\n\t\t\"minioConfig\": map[string]interface{}{\n\t\t\t\"webhook\": map[string]interface{}{\n\t\t\t\t\"enable\": true,\n\t\t\t\t\"endpoint\": \"http://service-adapter.fission/minio/\" + namespace,\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\thelmClient := helm.NewClient(helm.Host(tillerHost))\n\t_, err = helmClient.InstallRelease(chartPath, namespace, helm.ReleaseName(releaseName), helm.ValueOverrides(vals))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func genpod(namespace, name, image string) *corev1.Pod {\n\tvar userID int64 = 65534\n\n\treturn &corev1.Pod{\n\t\tMetadata: &metav1.ObjectMeta{\n\t\t\tName: k8s.String(name),\n\t\t\tNamespace: k8s.String(namespace),\n\t\t\tLabels: map[string]string{\"generator\": \"kboom\"},\n\t\t},\n\t\tSpec: &corev1.PodSpec{\n\t\t\tContainers: []*corev1.Container{\n\t\t\t\t&corev1.Container{\n\t\t\t\t\tName: k8s.String(\"main\"),\n\t\t\t\t\tImage: k8s.String(image),\n\t\t\t\t\tCommand: []string{\"/bin/sh\", \"-ec\", \"sleep 3600\"},\n\t\t\t\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\t\t\t\tRunAsUser: &userID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (n *mockAgent) memHotplugByProbe(addr uint64, sizeMB uint32, memorySectionSizeMB uint32) error {\n\treturn nil\n}", "func (m *AmbulanceMutation) AddedEnginepower() (r int, exists bool) {\n\tv := m.addenginepower\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (o ElastigroupIntegrationDockerSwarmAutoscaleHeadroomOutput) MemoryPerUnit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationDockerSwarmAutoscaleHeadroom) *int { return v.MemoryPerUnit }).(pulumi.IntPtrOutput)\n}", "func (r *Release) install(p *plan) {\n\tbefore, after := r.checkHooks(\"install\")\n\n\tif r.Test.Value {\n\t\tr.test(&after)\n\t}\n\n\tcmd := helmCmd(r.getHelmArgsFor(\"install\"), \"Install release [ \"+r.Name+\" ] version [ \"+r.Version+\" ] in namespace [ \"+r.Namespace+\" ]\")\n\tp.addCommand(cmd, r.Priority, r, before, after)\n}", "func CoreOSBasic(c cluster.TestCluster, version, runtime string) {\n\tk := setupCluster(c, 2, version, runtime)\n\n\t// start nginx pod and curl endpoint\n\tif err := nginxCheck(c, k.master, k.workers); err != nil {\n\t\tc.Fatal(err)\n\t}\n\n\t// http://kubernetes.io/v1.0/docs/user-guide/secrets/ Also, ensures\n\t// https://github.com/coreos/bugs/issues/447 does not re-occur.\n\tif err := secretCheck(c, k.master, k.workers); err != nil {\n\t\tc.Fatal(err)\n\t}\n}", "func (c baseClient) startEngineOnContainerd(ctx context.Context, imageName, configFile string) error {\n\tctx = namespaces.WithNamespace(ctx, engineNamespace)\n\timage, err := c.cclient.GetImage(ctx, imageName)\n\tif err != nil {\n\t\tif errdefs.IsNotFound(err) {\n\t\t\treturn fmt.Errorf(\"engine image missing: %s\", imageName)\n\t\t}\n\t\treturn errors.Wrap(err, \"failed to check for engine image\")\n\t}\n\n\t// Make sure we have a valid config file\n\terr = c.verifyDockerConfig(configFile)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tengineSpec.Process.Args = append(engineSpec.Process.Args,\n\t\t\"--config-file\", configFile,\n\t)\n\n\tcOpts := []containerd.NewContainerOpts{\n\t\tcontainerized.WithNewSnapshot(image),\n\t\trestart.WithStatus(containerd.Running),\n\t\trestart.WithLogPath(\"/var/log/engine.log\"), // TODO - better!\n\t\tgenSpec(),\n\t\tcontainerd.WithRuntime(\"io.containerd.runtime.process.v1\", nil),\n\t}\n\n\t_, err = c.cclient.NewContainer(\n\t\tctx,\n\t\tengineContainerName,\n\t\tcOpts...,\n\t)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create engine container\")\n\t}\n\n\treturn nil\n}", "func HelmInstallOpt(path string, releaseName string) features.Func {\n\treturn func(ctx context.Context, t *testing.T, envConf *envconf.Config) context.Context {\n\t\tctx = ctxopts.WithHelmRelease(ctx, releaseName)\n\n\t\terr := helm.InstallE(t, ctxopts.HelmOptions(ctx), path, releaseName)\n\t\tif err != nil {\n\t\t\t// Print setup job logs if installation failed.\n\t\t\tk8s.RunKubectl(t, ctxopts.KubectlOptions(ctx),\n\t\t\t\t\"logs\", fmt.Sprintf(\"-ljob-name=%s-sumologic-setup\", releaseName),\n\t\t\t)\n\n\t\t\trequire.NoError(t, err)\n\t\t}\n\n\t\treturn ctx\n\t}\n}", "func RunInstall(cmd *cobra.Command, args []string) {\n\tc := LoadOperatorConf(cmd)\n\tutil.KubeCreateSkipExisting(c.NS)\n\tutil.KubeCreateSkipExisting(c.SA)\n\tutil.KubeCreateSkipExisting(c.SAEndpoint)\n\tutil.KubeCreateSkipExisting(c.Role)\n\tutil.KubeCreateSkipExisting(c.RoleEndpoint)\n\tutil.KubeCreateSkipExisting(c.RoleBinding)\n\tutil.KubeCreateSkipExisting(c.RoleBindingEndpoint)\n\tutil.KubeCreateSkipExisting(c.ClusterRole)\n\tutil.KubeCreateSkipExisting(c.ClusterRoleBinding)\n\n\ttestEnv, _ := cmd.Flags().GetBool(\"test-env\")\n\tif testEnv {\n\t\toperatorContainer := c.Deployment.Spec.Template.Spec.Containers[0]\n\t\toperatorContainer.Env = append(operatorContainer.Env, corev1.EnvVar{\n\t\t\tName: \"TEST_ENV\",\n\t\t\tValue: \"true\",\n\t\t})\n\t\tc.Deployment.Spec.Template.Spec.Containers[0].Env = operatorContainer.Env\n\t}\n\n\tadmission, _ := cmd.Flags().GetBool(\"admission\")\n\tif admission {\n\t\tLoadAdmissionConf(c)\n\t\tAdmissionWebhookSetup(c)\n\t\tutil.KubeCreateSkipExisting(c.WebhookConfiguration)\n\t\tutil.KubeCreateSkipExisting(c.WebhookSecret)\n\t\tutil.KubeCreateSkipExisting(c.WebhookService)\n\t\toperatorContainer := c.Deployment.Spec.Template.Spec.Containers[0]\n\t\toperatorContainer.Env = append(operatorContainer.Env, corev1.EnvVar{\n\t\t\tName: \"ENABLE_NOOBAA_ADMISSION\",\n\t\t\tValue: \"true\",\n\t\t})\n\t\tc.Deployment.Spec.Template.Spec.Containers[0].Env = operatorContainer.Env\n\t}\n\n\tnoDeploy, _ := cmd.Flags().GetBool(\"no-deploy\")\n\tif !noDeploy {\n\t\toperatorContainer := c.Deployment.Spec.Template.Spec.Containers[0]\n\t\toperatorContainer.Env = append(\n\t\t\toperatorContainer.Env,\n\t\t\tcorev1.EnvVar{\n\t\t\t\tName: \"NOOBAA_CLI_DEPLOYMENT\",\n\t\t\t\tValue: \"true\",\n\t\t\t},\n\t\t)\n\t\tc.Deployment.Spec.Template.Spec.Containers[0].Env = operatorContainer.Env\n\t\tutil.KubeCreateSkipExisting(c.Deployment)\n\t}\n}", "func InjectChaos(experimentDetails *experimentTypes.ExperimentDetails, pid int) error {\n\n\tnetemCommands := os.Getenv(\"NETEM_COMMAND\")\n\ttargetIPs := os.Getenv(\"TARGET_IPs\")\n\n\tif targetIPs == \"\" {\n\t\ttc := fmt.Sprintf(\"nsenter -t %d -n tc qdisc add dev %s root netem %v\", pid, experimentDetails.NetworkInterface, netemCommands)\n\t\tcmd := exec.Command(\"/bin/bash\", \"-c\", tc)\n\t\tout, err := cmd.CombinedOutput()\n\t\tlog.Info(cmd.String())\n\t\tif err != nil {\n\t\t\tlog.Error(string(out))\n\t\t\treturn err\n\t\t}\n\t} else {\n\n\t\tips := strings.Split(targetIPs, \",\")\n\t\tvar uniqueIps []string\n\n\t\t// removing duplicates ips from the list, if any\n\t\tfor i := range ips {\n\t\t\tisPresent := false\n\t\t\tfor j := range uniqueIps {\n\t\t\t\tif ips[i] == uniqueIps[j] {\n\t\t\t\t\tisPresent = true\n\t\t\t\t}\n\t\t\t}\n\t\t\tif !isPresent {\n\t\t\t\tuniqueIps = append(uniqueIps, ips[i])\n\t\t\t}\n\n\t\t}\n\n\t\t// Create a priority-based queue\n\t\t// This instantly creates classes 1:1, 1:2, 1:3\n\t\tpriority := fmt.Sprintf(\"nsenter -t %v -n tc qdisc add dev %v root handle 1: prio\", pid, experimentDetails.NetworkInterface)\n\t\tcmd := exec.Command(\"/bin/bash\", \"-c\", priority)\n\t\tout, err := cmd.CombinedOutput()\n\t\tlog.Info(cmd.String())\n\t\tif err != nil {\n\t\t\tlog.Error(string(out))\n\t\t\treturn err\n\t\t}\n\n\t\t// Add queueing discipline for 1:3 class.\n\t\t// No traffic is going through 1:3 yet\n\t\ttraffic := fmt.Sprintf(\"nsenter -t %v -n tc qdisc add dev %v parent 1:3 netem %v\", pid, experimentDetails.NetworkInterface, netemCommands)\n\t\tcmd = exec.Command(\"/bin/bash\", \"-c\", traffic)\n\t\tout, err = cmd.CombinedOutput()\n\t\tlog.Info(cmd.String())\n\t\tif err != nil {\n\t\t\tlog.Error(string(out))\n\t\t\treturn err\n\t\t}\n\n\t\tfor _, ip := range uniqueIps {\n\n\t\t\t// redirect traffic to specific IP through band 3\n\t\t\t// It allows ipv4 addresses only\n\t\t\tif !strings.Contains(ip, \":\") {\n\t\t\t\ttc := fmt.Sprintf(\"nsenter -t %v -n tc filter add dev %v protocol ip parent 1:0 prio 3 u32 match ip dst %v flowid 1:3\", pid, experimentDetails.NetworkInterface, ip)\n\t\t\t\tcmd = exec.Command(\"/bin/bash\", \"-c\", tc)\n\t\t\t\tout, err = cmd.CombinedOutput()\n\t\t\t\tlog.Info(cmd.String())\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(string(out))\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func main() {\n\n\t// Parse The Flags For Local Development Usage\n\tflag.Parse()\n\n\t// Initialize A Knative Injection Lite Context (K8S Client & Logger)\n\tctx := commonk8s.LoggingContext(context.Background(), constants.Component, *masterURL, *kubeconfig)\n\n\t// Get The Logger From The Context & Defer Flushing Any Buffered Log Entries On Exit\n\tlogger = logging.FromContext(ctx).Desugar()\n\tdefer func() { _ = logger.Sync() }()\n\n\t// Load Environment Variables\n\tenvironment, err := env.GetEnvironment(logger)\n\tif err != nil {\n\t\tlogger.Fatal(\"Invalid / Missing Environment Variables - Terminating\", zap.Error(err))\n\t}\n\n\t// Initialize Tracing (Watching config-tracing ConfigMap, Assumes Context Came From LoggingContext With Embedded K8S Client Key)\n\tcommonk8s.InitializeTracing(logger.Sugar(), ctx, environment.ServiceName)\n\n\t// Start The Liveness And Readiness Servers\n\thealthServer := channelhealth.NewChannelHealthServer(environment.HealthPort)\n\thealthServer.Start(logger)\n\n\t// Start The Prometheus Metrics Server (Prometheus)\n\tmetricsServer := prometheus.NewMetricsServer(logger, environment.MetricsPort, \"/metrics\")\n\tmetricsServer.Start()\n\n\t// Initialize The KafkaChannel Lister Used To Validate Events\n\terr = channel.InitializeKafkaChannelLister(ctx, *masterURL, *kubeconfig, healthServer)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed To Initialize KafkaChannel Lister\", zap.Error(err))\n\t}\n\tdefer channel.Close()\n\n\t// Initialize The Kafka Producer In Order To Start Processing Status Events\n\tkafkaProducer, err = producer.NewProducer(logger, environment.KafkaBrokers, environment.KafkaUsername, environment.KafkaPassword, metricsServer, healthServer)\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed To Initialize Kafka Producer\", zap.Error(err))\n\t}\n\tdefer kafkaProducer.Close()\n\n\t// Create A New Knative Eventing MessageReceiver (Parses The Channel From The Host Header)\n\tmessageReceiver, err := eventingchannel.NewMessageReceiver(handleMessage, logger, eventingchannel.ResolveMessageChannelFromHostHeader(eventingchannel.ParseChannel))\n\tif err != nil {\n\t\tlogger.Fatal(\"Failed To Create MessageReceiver\", zap.Error(err))\n\t}\n\n\t// Set The Liveness Flag - Readiness Is Set By Individual Components\n\thealthServer.SetAlive(true)\n\n\t// Start The Message Receiver (Blocking)\n\terr = messageReceiver.Start(ctx)\n\tif err != nil {\n\t\tlogger.Error(\"Failed To Start MessageReceiver\", zap.Error(err))\n\t}\n\n\t// Reset The Liveness and Readiness Flags In Preparation For Shutdown\n\thealthServer.Shutdown()\n\n\t// Shutdown The Prometheus Metrics Server\n\tmetricsServer.Stop()\n\n\t// Stop The Liveness And Readiness Servers\n\thealthServer.Stop(logger)\n}", "func (o ElastigroupIntegrationDockerSwarmAutoscaleHeadroomPtrOutput) MemoryPerUnit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationDockerSwarmAutoscaleHeadroom) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MemoryPerUnit\n\t}).(pulumi.IntPtrOutput)\n}", "func Setup() {\n\tengine = &Engine{\n\t\tmodelManager: &models.Manager{},\n\t\tcontrollerManager: &controllers.Manager{},\n\t\tviewManager: &views.Manager{},\n\t\tactorManager: &actors.Manager{},\n\t}\n\n\tengine.modelManager.Setup()\n\tengine.viewManager.Setup()\n\tengine.controllerManager.Setup(ViewManager())\n\tengine.actorManager.Setup(ViewManager())\n\n\tserveStats()\n}", "func newPodForCR(cr *operatorv1alpha1.Minecraft) *corev1.Pod {\n\tvar envVars []corev1.EnvVar\n\tenvVars = []corev1.EnvVar {\n\t\tcorev1.EnvVar {\n\t\tName: \"EULA\",\n\t\tValue: cr.Spec.Uela,\n\t\t},\n\t}\n\n\tvar fsType int64\n\tfsType = int64(1000)\n\n\tlabels := map[string]string{\n\t\t\"app\": cr.Name,\n \"version\": cr.Spec.Version,\n\t\t\"uela\": cr.Spec.Uela,\n\t}\n\treturn &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: cr.Name + \"-pod\",\n\t\t\tNamespace: cr.Namespace,\n\t\t\tLabels: labels,\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tSecurityContext: &corev1.PodSecurityContext{\n\t\t\t\tFSGroup: &fsType,\n\t\t\t\tRunAsUser: &fsType,\n\t\t\t},\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"minecraft\",\n\t\t\t\t\tImage: \"hoeghh/minecraft:\" + cr.Spec.Version,\n\t\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tContainerPort: 25565,\n\t\t\t\t\t\t\tName: \"minecraft\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tEnv: envVars,\n\t\t\t\t\tVolumeMounts: []corev1.VolumeMount{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tName: \"minecraft-volume\",\n\t\t\t\t\t\t\tMountPath: \"/minecraft-data\",\n\t\t\t\t\t\t\tReadOnly: false,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tVolumes: []corev1.Volume{\n\t\t\t\t{\n\t\t\t\t\tName: \"minecraft-volume\",\n\t\t\t\t\tVolumeSource: corev1.VolumeSource{\n\t\t\t\t\t\tPersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{\n\t\t\t\t\t\t\tClaimName: cr.Name + \"-pvc\", //cr.Spec.StorageClassName\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func AddDeviceInRuntime(k string, cfg *config.SnmpDeviceCfg) {\n\t// Initialize each SNMP device and put pointer to the global map devices\n\tdev := device.New(cfg)\n\tdev.AttachToBus(Bus)\n\tdev.InitCatalogVar(DBConfig.VarCatalog)\n\tdev.SetSelfMonitoring(selfmonProc)\n\n\t// send a db map to initialize each one its own db if needed\n\toutdb, _ := dev.GetOutSenderFromMap(influxdb)\n\toutdb.Init()\n\toutdb.StartSender(&senderWg)\n\n\tmutex.Lock()\n\tdevices[k] = dev\n\t// Start gather goroutine for device and add it to the wait group for gather goroutines\n\tgatherWg.Add(1)\n\tgo func() {\n\t\tdefer gatherWg.Done()\n\t\tdev.StartGather()\n\t\tlog.Infof(\"Device %s finished\", cfg.ID)\n\t\t// If device goroutine has finished, leave the bus so it won't get blocked trying\n\t\t// to send messages to a not running device.\n\t\tdev.LeaveBus(Bus)\n\t}()\n\tmutex.Unlock()\n}", "func setGPUMemory(clock, device int, name string) {\n\trequest := RpcRequest{(fmt.Sprintf(\"{\\\"command\\\":\\\"gpumem\\\",\\\"parameter\\\":\\\"%v,%v\\\"}\", device, clock)), make(chan []byte), name}\n\trequest.Send()\n}", "func (b *Benchmark) SetUnifiedMemory() {\n\tb.useUnifiedMemory = true\n}", "func ConfigureTPUEmbeddingMemory(scope *Scope, common_config tf.Output) (memory_config tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"ConfigureTPUEmbeddingMemory\",\n\t\tInput: []tf.Input{\n\t\t\tcommon_config,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (s *TestSuite) SetupTestSuite(c *input.Context) error {\n\n\tregistry := c.GetArg(\"registry\").String(\"\")\n\terr := helm.Chart(onosTopoComponentName, onostest.OnosChartRepo).\n\t\tRelease(onosTopoComponentName).\n\t\tSet(\"image.tag\", \"latest\").\n\t\tSet(\"global.image.registry\", registry).\n\t\tInstall(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func HackForStandardTrait(tp types.Capability, client client.Client) error {\n\tswitch tp.Name {\n\tcase \"metrics\":\n\t\t// metrics trait will rely on a Prometheus instance to be installed\n\t\t// make sure the chart is a prometheus operator\n\t\tif tp.Install == nil {\n\t\t\tbreak\n\t\t}\n\t\tif tp.Install.Helm.Namespace == \"monitoring\" && tp.Install.Helm.Name == \"kube-prometheus-stack\" {\n\t\t\tif err := InstallPrometheusInstance(client); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\tdefault:\n\t}\n\treturn nil\n}", "func BuildTestPod(name string, cpu int64, mem int64) *kube_api.Pod {\n\tpod := &kube_api.Pod{\n\t\tObjectMeta: kube_api.ObjectMeta{\n\t\t\tNamespace: \"default\",\n\t\t\tName: name,\n\t\t},\n\t\tSpec: kube_api.PodSpec{\n\t\t\tContainers: []kube_api.Container{\n\t\t\t\t{\n\t\t\t\t\tResources: kube_api.ResourceRequirements{\n\t\t\t\t\t\tRequests: kube_api.ResourceList{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tif cpu >= 0 {\n\t\tpod.Spec.Containers[0].Resources.Requests[kube_api.ResourceCPU] = *resource.NewMilliQuantity(cpu, resource.DecimalSI)\n\t}\n\tif mem >= 0 {\n\t\tpod.Spec.Containers[0].Resources.Requests[kube_api.ResourceMemory] = *resource.NewQuantity(mem, resource.DecimalSI)\n\t}\n\n\treturn pod\n}", "func (addon *CertmanagerAddon) Install(args ...string) {\n\tnode := *addon.masterNode\n\t_, err := addon.communicator.RunCmd(node, \"helm install --name cert-manager --namespace ingress stable/cert-manager\")\n\tFatalOnError(err)\n\tlog.Println(\"cert-manager installed\")\n}", "func makePodSpecPatch(\n\tcontainer *pipelinespec.PipelineDeploymentConfig_PipelineContainerSpec,\n\tcomponentSpec *pipelinespec.ComponentSpec,\n\texecutorInput *pipelinespec.ExecutorInput,\n\texecutionID int64,\n\tpipelineName string,\n\trunID string,\n) (string, error) {\n\texecutorInputJSON, err := protojson.Marshal(executorInput)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to make podSpecPatch: %w\", err)\n\t}\n\tcomponentJSON, err := protojson.Marshal(componentSpec)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to make podSpecPatch: %w\", err)\n\t}\n\n\tuserCmdArgs := make([]string, 0, len(container.Command)+len(container.Args))\n\tuserCmdArgs = append(userCmdArgs, container.Command...)\n\tuserCmdArgs = append(userCmdArgs, container.Args...)\n\tlauncherCmd := []string{\n\t\t// TODO(Bobgy): workaround argo emissary executor bug, after we upgrade to an argo version with the bug fix, we can remove the following line.\n\t\t// Reference: https://github.com/argoproj/argo-workflows/issues/7406\n\t\t\"/var/run/argo/argoexec\", \"emissary\", \"--\",\n\t\tcomponent.KFPLauncherPath,\n\t\t// TODO(Bobgy): no need to pass pipeline_name and run_id, these info can be fetched via pipeline context and pipeline run context which have been created by root DAG driver.\n\t\t\"--pipeline_name\", pipelineName,\n\t\t\"--run_id\", runID,\n\t\t\"--execution_id\", fmt.Sprintf(\"%v\", executionID),\n\t\t\"--executor_input\", string(executorInputJSON),\n\t\t\"--component_spec\", string(componentJSON),\n\t\t\"--pod_name\",\n\t\tfmt.Sprintf(\"$(%s)\", component.EnvPodName),\n\t\t\"--pod_uid\",\n\t\tfmt.Sprintf(\"$(%s)\", component.EnvPodUID),\n\t\t\"--mlmd_server_address\",\n\t\tfmt.Sprintf(\"$(%s)\", component.EnvMetadataHost),\n\t\t\"--mlmd_server_port\",\n\t\tfmt.Sprintf(\"$(%s)\", component.EnvMetadataPort),\n\t\t\"--\", // separater before user command and args\n\t}\n\tres := k8score.ResourceRequirements{\n\t\tLimits: map[k8score.ResourceName]k8sres.Quantity{},\n\t}\n\tmemoryLimit := container.GetResources().GetMemoryLimit()\n\tif memoryLimit != 0 {\n\t\tq, err := k8sres.ParseQuantity(fmt.Sprintf(\"%vG\", memoryLimit))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tres.Limits[k8score.ResourceMemory] = q\n\t}\n\tcpuLimit := container.GetResources().GetCpuLimit()\n\tif cpuLimit != 0 {\n\t\tq, err := k8sres.ParseQuantity(fmt.Sprintf(\"%v\", cpuLimit))\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tres.Limits[k8score.ResourceCPU] = q\n\t}\n\taccelerator := container.GetResources().GetAccelerator()\n\tif accelerator != nil {\n\t\treturn \"\", fmt.Errorf(\"accelerator resources are not supported yet: https://github.com/kubeflow/pipelines/issues/7043\")\n\t}\n\tpodSpec := &k8score.PodSpec{\n\t\tContainers: []k8score.Container{{\n\t\t\tName: \"main\", // argo task user container is always called \"main\"\n\t\t\tCommand: launcherCmd,\n\t\t\tArgs: userCmdArgs,\n\t\t\tImage: container.Image,\n\t\t\tResources: res,\n\t\t}},\n\t}\n\tpodSpecPatchBytes, err := json.Marshal(podSpec)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"JSON marshaling pod spec patch: %w\", err)\n\t}\n\treturn string(podSpecPatchBytes), nil\n}", "func (o OceanLaunchSpecAutoscaleHeadroomOutput) MemoryPerUnit() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v OceanLaunchSpecAutoscaleHeadroom) *int { return v.MemoryPerUnit }).(pulumi.IntPtrOutput)\n}", "func AddPod() {\n\tpodsWatched.Inc()\n}", "func newMemPCApp(logger log.Logger, db dbm.DB, baseAppOptions ...func(*bam.BaseApp)) *memoryPCApp {\n\tapp := newMemoryPCBaseApp(logger, db, baseAppOptions...)\n\t// setup subspaces\n\tauthSubspace := sdk.NewSubspace(auth.DefaultParamspace)\n\tnodesSubspace := sdk.NewSubspace(nodesTypes.DefaultParamspace)\n\tappsSubspace := sdk.NewSubspace(appsTypes.DefaultParamspace)\n\tpocketSubspace := sdk.NewSubspace(pocketTypes.DefaultParamspace)\n\t// The AuthKeeper handles address -> account lookups\n\tapp.accountKeeper = auth.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[auth.StoreKey],\n\t\tauthSubspace,\n\t\tmoduleAccountPermissions,\n\t)\n\t// The nodesKeeper keeper handles pocket core nodes\n\tapp.nodesKeeper = nodesKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[nodesTypes.StoreKey],\n\t\tapp.accountKeeper,\n\t\tnodesSubspace,\n\t\tnodesTypes.DefaultCodespace,\n\t)\n\t// The apps keeper handles pocket core applications\n\tapp.appsKeeper = appsKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[appsTypes.StoreKey],\n\t\tapp.nodesKeeper,\n\t\tapp.accountKeeper,\n\t\tappsSubspace,\n\t\tappsTypes.DefaultCodespace,\n\t)\n\t// The main pocket core\n\tapp.pocketKeeper = pocketKeeper.NewPocketCoreKeeper(\n\t\tapp.keys[pocketTypes.StoreKey],\n\t\tapp.cdc,\n\t\tapp.nodesKeeper,\n\t\tapp.appsKeeper,\n\t\tgetInMemHostedChains(),\n\t\tpocketSubspace,\n\t)\n\t// The governance keeper\n\tapp.govKeeper = govKeeper.NewKeeper(\n\t\tapp.cdc,\n\t\tapp.keys[pocketTypes.StoreKey],\n\t\tapp.tkeys[pocketTypes.StoreKey],\n\t\tgovTypes.DefaultCodespace,\n\t\tapp.accountKeeper,\n\t\tauthSubspace, nodesSubspace, appsSubspace, pocketSubspace,\n\t)\n\tapp.pocketKeeper.Keybase = getInMemoryKeybase()\n\tapp.pocketKeeper.TmNode = getInMemoryTMClient()\n\tapp.mm = module.NewManager(\n\t\tauth.NewAppModule(app.accountKeeper),\n\t\tnodes.NewAppModule(app.nodesKeeper),\n\t\tapps.NewAppModule(app.appsKeeper),\n\t\tpocket.NewAppModule(app.pocketKeeper),\n\t\tgov.NewAppModule(app.govKeeper),\n\t)\n\tapp.mm.SetOrderBeginBlockers(nodesTypes.ModuleName, appsTypes.ModuleName, pocketTypes.ModuleName)\n\tapp.mm.SetOrderEndBlockers(nodesTypes.ModuleName, appsTypes.ModuleName)\n\tapp.mm.SetOrderInitGenesis(\n\t\tnodesTypes.ModuleName,\n\t\tappsTypes.ModuleName,\n\t\tpocketTypes.ModuleName,\n\t\tauth.ModuleName,\n\t\tgov.ModuleName,\n\t)\n\tapp.mm.RegisterRoutes(app.Router(), app.QueryRouter())\n\tapp.SetInitChainer(app.InitChainer)\n\tapp.SetAnteHandler(auth.NewAnteHandler(app.accountKeeper))\n\tapp.SetBeginBlocker(app.BeginBlocker)\n\tapp.SetEndBlocker(app.EndBlocker)\n\tapp.MountKVStores(app.keys)\n\tapp.MountTransientStores(app.tkeys)\n\terr := app.LoadLatestVersion(app.keys[bam.MainStoreKey])\n\tif err != nil {\n\t\tcmn.Exit(err.Error())\n\t}\n\treturn app\n}", "func (hs *HelmSuite) TestObjectStoreOnRookInstalledViaHelm() {\n\trunObjectE2ETestLite(hs.helper, hs.kh, hs.Suite, hs.namespace, \"default\", 3)\n}", "func setupMainEngine() *gin.Engine {\n\tr := gin.Default()\n\n\t// healthz\n\thealthz := &healthz{}\n\tr.GET(\"/healthz\", healthz.getHealthz)\n\n\tsources := defaultSources\n\tsourcesFromEnv := strings.Split(os.Getenv(\"NEWS_SOURCES\"), \",\")\n\tif len(sourcesFromEnv) != 0 {\n\t\tsources = sourcesFromEnv\n\t}\n\tnews := &news{\n\t\tapiKey: os.Getenv(\"NEWS_API_KEY\"),\n\t\turl: \"https://newsapi.org/v2\",\n\t\tsources: sources,\n\t}\n\tr.GET(\"/\", news.articleURL)\n\tr.GET(\"/slack\", news.articleForSlack)\n\n\treturn r\n}", "func InitHelmOnCluster(c *gin.Context) {\n\tlog := logger.WithFields(logrus.Fields{\"tag\": constants.TagHelmInstall})\n\tlog.Info(\"Start helm install\")\n\n\tcommonCluster, ok := GetCommonClusterFromRequest(c)\n\tif ok != true {\n\t\treturn\n\t}\n\n\tkubeConfig, err := commonCluster.GetK8sConfig()\n\tif err != nil {\n\t\tlog.Errorf(\"Error during getting kubeconfig: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error getting kubeconfig\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\t// bind request body to struct\n\tvar helmInstall htype.Install\n\tif err := c.BindJSON(&helmInstall); err != nil {\n\t\t// bind failed\n\t\tlog.Errorf(\"Required field is empty: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error parsing request\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\terr = helm.Install(&helmInstall, kubeConfig, commonCluster.GetName())\n\tif err != nil {\n\t\tlog.Errorf(\"Unable to install chart: %s\", err.Error())\n\t\tc.JSON(http.StatusBadRequest, htype.ErrorResponse{\n\t\t\tCode: http.StatusBadRequest,\n\t\t\tMessage: \"Error installing helm\",\n\t\t\tError: err.Error(),\n\t\t})\n\t\treturn\n\t}\n\tmessage := \"helm initialising\"\n\tc.JSON(http.StatusCreated, htype.InstallResponse{\n\t\tStatus: http.StatusCreated,\n\t\tMessage: message,\n\t})\n\tlog.Info(message)\n\treturn\n}" ]
[ "0.63641816", "0.56511396", "0.53460056", "0.50905603", "0.50905275", "0.5051243", "0.50034815", "0.49334112", "0.4880717", "0.48790643", "0.48434487", "0.48180932", "0.47843823", "0.4771143", "0.47543284", "0.46859667", "0.46632564", "0.4648786", "0.46440202", "0.46144024", "0.4614267", "0.46005407", "0.45876142", "0.4547389", "0.45454517", "0.45412177", "0.45403752", "0.4528947", "0.44989556", "0.44872093", "0.44843838", "0.44804472", "0.4475131", "0.4475131", "0.44685233", "0.4459582", "0.43900555", "0.43792337", "0.43303344", "0.43191722", "0.43152112", "0.4313947", "0.42991057", "0.42975536", "0.4291135", "0.4284604", "0.42787912", "0.42732742", "0.42624837", "0.42580467", "0.4249732", "0.4248395", "0.42428026", "0.42329413", "0.4228328", "0.4224984", "0.4223991", "0.42137942", "0.4205661", "0.42051864", "0.42016372", "0.41970727", "0.41773972", "0.4175772", "0.41625854", "0.41572878", "0.41553625", "0.4153221", "0.41503793", "0.41490006", "0.4143437", "0.41375616", "0.41340283", "0.41248375", "0.41170442", "0.41142902", "0.41019815", "0.40970138", "0.40923604", "0.4092316", "0.40878505", "0.40866214", "0.40855238", "0.40796208", "0.4076973", "0.4075428", "0.40753773", "0.4056304", "0.40383387", "0.40344483", "0.40336213", "0.4033544", "0.40263006", "0.4022372", "0.40219212", "0.40205392", "0.40188247", "0.40186334", "0.40184852", "0.40076247" ]
0.82798386
0
setPodMemoryHogExperimentENV will set the ENVs for podmemoryhog experiment
func setPodMemoryHogExperimentENV(experimentsDetails *types.ExperimentDetails) *common.ENVDetails { // contains all the envs envDetails := common.ENVDetails{ ENV: map[string]string{}, } // Add Experiment ENV's envDetails.SetEnv("CONTAINER_RUNTIME", experimentsDetails.ContainerRuntime). SetEnv("SOCKET_PATH", experimentsDetails.SocketPath). SetEnv("TARGET_PODS", experimentsDetails.TargetPods). SetEnv("PODS_AFFECTED_PERC", strconv.Itoa(experimentsDetails.PodsAffectedPerc)). SetEnv("MEMORY_CONSUMPTION", strconv.Itoa(experimentsDetails.MemoryConsumption)) return &envDetails }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func setExperimentVar(chaosExperiment *v1alpha1.ChaosExperiment, testsDetails *types.TestDetails) {\n\n\t// contains all the envs\n\tenvDetails := ENVDetails{\n\t\tENV: map[string]string{},\n\t}\n\n\t// Modify the ExperimentImage\n\tchaosExperiment.Spec.Definition.Image = testsDetails.ExperimentImage\n\t// Modify experiment imagePullPolicy\n\tchaosExperiment.Spec.Definition.ImagePullPolicy = corev1.PullPolicy(testsDetails.ExperimentImagePullPolicy)\n\n\t// Get lib image\n\tvar libImage string\n\tfor _, value := range chaosExperiment.Spec.Definition.ENVList {\n\t\tif value.Name == \"LIB_IMAGE\" {\n\t\t\tlibImage = value.Value\n\t\t}\n\t}\n\n\t// Modify LIB Image\n\tif testsDetails.LibImage == \"\" && strings.Contains(libImage, \"go-runner\") {\n\t\ttestsDetails.LibImage = testsDetails.ExperimentImage\n\t} else {\n\t\ttestsDetails.LibImage = libImage\n\t}\n\n\t// Modify Args\n\tif testsDetails.Args != \"\" {\n\t\tchaosExperiment.Spec.Definition.Args = strings.Split(testsDetails.Args, \",\")\n\t}\n\n\t// Modify Image Command\n\tif testsDetails.Command != \"\" {\n\t\tchaosExperiment.Spec.Definition.Command = strings.Split(testsDetails.Command, \",\")\n\t}\n\n\t// Modify ENV's\n\tenvDetails.SetEnv(\"SEQUENCE\", testsDetails.Sequence).\n\t\tSetEnv(\"PODS_AFFECTED_PERC\", testsDetails.PodsAffectedPercentage).\n\t\tSetEnv(\"TARGET_PODS\", testsDetails.TargetPod).\n\t\tSetEnv(\"LIB\", testsDetails.Lib).\n\t\tSetEnv(\"LIB_IMAGE\", testsDetails.LibImage)\n\n\tlog.Info(\"[LIB Image]: Lib image is \" + testsDetails.LibImage + \" !!!\")\n\n\t// update all the values corresponding to keys from the ENV's in Experiment\n\tfor key, value := range chaosExperiment.Spec.Definition.ENVList {\n\t\t_, ok := envDetails.ENV[value.Name]\n\t\tif ok {\n\t\t\tchaosExperiment.Spec.Definition.ENVList[key].Value = envDetails.ENV[value.Name]\n\t\t}\n\t}\n}", "func setEngineVar(chaosEngine *v1alpha1.ChaosEngine, testsDetails *types.TestDetails) {\n\n\t// contains all the envs\n\tenvDetails := ENVDetails{\n\t\tENV: map[string]string{},\n\t}\n\n\t// Add JobCleanUpPolicy of chaos-runner to retain\n\tchaosEngine.Spec.JobCleanUpPolicy = v1alpha1.CleanUpPolicy(testsDetails.JobCleanUpPolicy)\n\n\t// Add ImagePullPolicy of chaos-runner to Always\n\tchaosEngine.Spec.Components.Runner.ImagePullPolicy = corev1.PullPolicy(testsDetails.ImagePullPolicy)\n\n\t// Modify the spec of engine file\n\tchaosEngine.ObjectMeta.Name = testsDetails.EngineName\n\tchaosEngine.ObjectMeta.Namespace = testsDetails.ChaosNamespace\n\n\t// If ChaosEngine contain App Info then update it\n\tif chaosEngine.Spec.Appinfo.Appns != \"\" && chaosEngine.Spec.Appinfo.Applabel != \"\" {\n\t\tchaosEngine.Spec.Appinfo.Appns = testsDetails.AppNS\n\t\tchaosEngine.Spec.Appinfo.Applabel = testsDetails.AppLabel\n\t}\n\tif testsDetails.ChaosServiceAccount != \"\" {\n\t\tchaosEngine.Spec.ChaosServiceAccount = testsDetails.ChaosServiceAccount\n\t} else {\n\t\tchaosEngine.Spec.ChaosServiceAccount = testsDetails.ExperimentName + \"-sa\"\n\t}\n\tchaosEngine.Spec.Experiments[0].Name = testsDetails.NewExperimentName\n\tchaosEngine.Spec.AnnotationCheck = testsDetails.AnnotationCheck\n\n\tswitch testsDetails.ExperimentName {\n\tcase \"ec2-terminate-by-id\":\n\t\tenvDetails.SetEnv(\"EC2_INSTANCE_ID\", testsDetails.InstanceID).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ec2-terminate-by-tag\":\n\t\tenvDetails.SetEnv(\"INSTANCE_TAG\", testsDetails.InstanceTag).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ebs-loss-by-id\":\n\t\tenvDetails.SetEnv(\"EBS_VOLUME_ID\", testsDetails.EBSVolumeID).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"ebs-loss-by-tag\":\n\t\tenvDetails.SetEnv(\"EBS_VOLUME_TAG\", testsDetails.EBSVolumeTag).\n\t\t\tSetEnv(\"REGION\", testsDetails.Region)\n\tcase \"disk-fill\":\n\t\tif testsDetails.FillPercentage != 80 {\n\t\t\tenvDetails.SetEnv(\"FILL_PERCENTAGE\", strconv.Itoa(testsDetails.FillPercentage))\n\t\t}\n\t\t// Here not using SetEnv function as SetEnv will not add new variables\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"EPHEMERAL_STORAGE_MEBIBYTES\",\n\t\t\tValue: \"200\",\n\t\t})\n\tcase \"pod-cpu-hog-exec\":\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"CHAOS_KILL_COMMAND\",\n\t\t\tValue: testsDetails.CPUKillCommand,\n\t\t})\n\tcase \"pod-memory-hog-exec\":\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"CHAOS_KILL_COMMAND\",\n\t\t\tValue: testsDetails.MemoryKillCommand,\n\t\t})\n\tcase \"azure-instance-stop\":\n\t\tenvDetails.SetEnv(\"RESOURCE_GROUP\", testsDetails.AzureResourceGroup).\n\t\t\tSetEnv(\"AZURE_INSTANCE_NAME\", testsDetails.AzureInstanceName).\n\t\t\tSetEnv(\"AZURE_SCALE_SET\", testsDetails.AzureScaleSet)\n\tcase \"azure-disk-loss\":\n\t\tenvDetails.SetEnv(\"RESOURCE_GROUP\", testsDetails.AzureResourceGroup).\n\t\t\tSetEnv(\"AZURE_SCALE_SET\", testsDetails.AzureScaleSet).\n\t\t\tSetEnv(\"VIRTUAL_DISK_NAMES\", testsDetails.AzureDiskName)\n\tcase \"gcp-vm-instance-stop\":\n\t\tenvDetails.SetEnv(\"GCP_PROJECT_ID\", testsDetails.GCPProjectID).\n\t\t\tSetEnv(\"VM_INSTANCE_NAMES\", testsDetails.VMInstanceNames).\n\t\t\tSetEnv(\"INSTANCE_ZONES\", testsDetails.InstanceZones)\n\tcase \"gcp-vm-disk-loss\":\n\t\tenvDetails.SetEnv(\"GCP_PROJECT_ID\", testsDetails.GCPProjectID).\n\t\t\tSetEnv(\"DISK_VOLUME_NAMES\", testsDetails.DiskVolumeNames).\n\t\t\tSetEnv(\"DISK_ZONES\", testsDetails.DiskZones).\n\t\t\tSetEnv(\"DEVICE_NAMES\", testsDetails.DeviceNames)\n\tcase \"vm-poweroff\":\n\t\tenvDetails.SetEnv(\"APP_VM_MOIDS\", testsDetails.VMIds)\n\tcase \"process-kill\":\n\t\tenvDetails.SetEnv(\"PROCESS_IDS\", testsDetails.ProcessIds)\n\t}\n\n\t// for experiments like pod network latency\n\tenvDetails.SetEnv(\"NETWORK_LATENCY\", testsDetails.NetworkLatency)\n\n\t// update App Node Details\n\tif testsDetails.ApplicationNodeName != \"\" {\n\t\tenvDetails.SetEnv(\"TARGET_NODE\", testsDetails.ApplicationNodeName)\n\t\tif chaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector == nil {\n\t\t\tchaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector = map[string]string{}\n\t\t}\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.NodeSelector[\"kubernetes.io/hostname\"] = testsDetails.NodeSelectorName\n\t}\n\n\t// update Target Node Details\n\tif testsDetails.TargetNodes != \"\" {\n\t\tlog.Infof(\"[Info] Target Nodes: %v\", testsDetails.TargetNodes)\n\t\tenvDetails.SetEnv(\"TARGET_NODES\", testsDetails.TargetNodes)\n\t}\n\n\t// NODE_LABEL for Node-memory-hog and node-cpu-hog\n\tif testsDetails.NodeLabel != \"\" {\n\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV = append(chaosEngine.Spec.Experiments[0].Spec.Components.ENV, corev1.EnvVar{\n\t\t\tName: \"NODE_LABEL\",\n\t\t\tValue: testsDetails.NodeLabel,\n\t\t})\n\t}\n\n\t// update all the value corresponding to keys from the ENV's in Engine\n\tfor key, value := range chaosEngine.Spec.Experiments[0].Spec.Components.ENV {\n\t\t_, ok := envDetails.ENV[value.Name]\n\t\tif ok {\n\t\t\tchaosEngine.Spec.Experiments[0].Spec.Components.ENV[key].Value = envDetails.ENV[value.Name]\n\t\t}\n\t}\n}", "func GetENV(experimentDetails *experimentTypes.ExperimentDetails) {\n\texperimentDetails.ExperimentName = Getenv(\"EXPERIMENT_NAME\", \"\")\n\texperimentDetails.AppNS = Getenv(\"APP_NS\", \"\")\n\texperimentDetails.TargetContainer = Getenv(\"APP_CONTAINER\", \"\")\n\texperimentDetails.TargetPods = Getenv(\"APP_POD\", \"\")\n\texperimentDetails.AppLabel = Getenv(\"APP_LABEL\", \"\")\n\texperimentDetails.ChaosDuration, _ = strconv.Atoi(Getenv(\"TOTAL_CHAOS_DURATION\", \"30\"))\n\texperimentDetails.ChaosNamespace = Getenv(\"CHAOS_NAMESPACE\", \"litmus\")\n\texperimentDetails.EngineName = Getenv(\"CHAOS_ENGINE\", \"\")\n\texperimentDetails.ChaosUID = clientTypes.UID(Getenv(\"CHAOS_UID\", \"\"))\n\texperimentDetails.ChaosPodName = Getenv(\"POD_NAME\", \"\")\n\texperimentDetails.ContainerRuntime = Getenv(\"CONTAINER_RUNTIME\", \"\")\n\texperimentDetails.NetworkInterface = Getenv(\"NETWORK_INTERFACE\", \"eth0\")\n\texperimentDetails.TargetIPs = Getenv(\"TARGET_IPs\", \"\")\n}", "func InstallPodMemoryHogEngine(experimentsDetails *types.ExperimentDetails, chaosEngine *v1alpha1.ChaosEngine, clients environment.ClientSets) error {\n\n\texperimentENV := setPodMemoryHogExperimentENV(experimentsDetails)\n\tif err := common.InstallChaosEngine(experimentsDetails, chaosEngine, experimentENV, clients); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func TestInjectEnvironment(t *testing.T) {\n\tspec := func(containers ...corev1.Container) appsv1.DeploymentSpec {\n\t\treturn appsv1.DeploymentSpec{\n\t\t\tTemplate: corev1.PodTemplateSpec{\n\t\t\t\tSpec: corev1.PodSpec{\n\t\t\t\t\tContainers: containers,\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t}\n\n\ttests := []struct {\n\t\tname string\n\t\tin *appsv1.Deployment\n\t\tdeployment string\n\t\tcontainer string\n\t\tenvs []corev1.EnvVar\n\t\tcommonEnvs []corev1.EnvVar\n\t\twant *appsv1.Deployment\n\t}{{\n\t\tname: \"ignore\",\n\t\tdeployment: \"foo\",\n\t\tcontainer: \"container1\",\n\t\tenvs: []corev1.EnvVar{envVar(\"foo\", \"bar\")},\n\t\tcommonEnvs: []corev1.EnvVar{envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\tin: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\")},\n\t\t\t}),\n\t\t},\n\t\twant: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\"), envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\t\t}),\n\t\t},\n\t}, {\n\t\tname: \"append\",\n\t\tdeployment: \"test\",\n\t\tcontainer: \"container1\",\n\t\tenvs: []corev1.EnvVar{envVar(\"foo\", \"bar\")},\n\t\tcommonEnvs: []corev1.EnvVar{envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\tin: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\")},\n\t\t\t}, corev1.Container{\n\t\t\t\tName: \"container2\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"2\", \"2\")},\n\t\t\t}),\n\t\t},\n\t\twant: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\"), envVar(\"foo\", \"bar\"), envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\t\t}, corev1.Container{\n\t\t\t\tName: \"container2\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"2\", \"2\"), envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\t\t}),\n\t\t},\n\t}, {\n\t\tname: \"update\",\n\t\tdeployment: \"test\",\n\t\tcontainer: \"container2\",\n\t\tenvs: []corev1.EnvVar{envVar(\"2\", \"bar\")},\n\t\tcommonEnvs: []corev1.EnvVar{envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\tin: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\")},\n\t\t\t}, corev1.Container{\n\t\t\t\tName: \"container2\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"2\", \"2\")},\n\t\t\t}),\n\t\t},\n\t\twant: &appsv1.Deployment{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: \"test\",\n\t\t\t},\n\t\t\tSpec: spec(corev1.Container{\n\t\t\t\tName: \"container1\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"1\", \"1\"), envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\t\t}, corev1.Container{\n\t\t\t\tName: \"container2\",\n\t\t\t\tEnv: []corev1.EnvVar{envVar(\"2\", \"bar\"), envVar(\"KUBERNETES_MIN_VERSION\", \"v1.0.0\")},\n\t\t\t}),\n\t\t},\n\t}}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tu := &unstructured.Unstructured{}\n\t\t\tif err := scheme.Scheme.Convert(test.in, u, nil); err != nil {\n\t\t\t\tt.Fatal(\"Failed to convert deployment to unstructured\", err)\n\t\t\t}\n\n\t\t\tif err := InjectEnvironmentIntoDeployment(test.deployment, test.container, test.envs...)(u); err != nil {\n\t\t\t\tt.Fatal(\"Unexpected error from transformer\", err)\n\t\t\t}\n\n\t\t\tif err := InjectCommonEnvironment(test.commonEnvs...)(u); err != nil {\n\t\t\t\tt.Fatal(\"Unexpected error from transformer\", err)\n\t\t\t}\n\n\t\t\tgot := &appsv1.Deployment{}\n\t\t\tif err := scheme.Scheme.Convert(u, got, nil); err != nil {\n\t\t\t\tt.Fatal(\"Failed to convert unstructured to deployment\", err)\n\t\t\t}\n\n\t\t\tif !cmp.Equal(got, test.want) {\n\t\t\t\tt.Errorf(\"Got = %v, want: %v, diff:\\n%s\", got, test.want, cmp.Diff(got, test.want))\n\t\t\t}\n\t\t})\n\t}\n}", "func setupEnv(stack []byte) {\n\targs := stack\n\tbo := binary.LittleEndian\n\tbo.PutUint64(args, 1) // 1 argument, the process name.\n\targs = args[8:]\n\t// First argument, address of binary name.\n\tbinAddr := args[:8]\n\targs = args[8:]\n\tbo.PutUint64(args, 0) // NULL separator.\n\targs = args[8:]\n\tbo.PutUint64(args, 0) // No envp.\n\targs = args[8:]\n\t// Build auxillary vector.\n\t// Page size.\n\tbo.PutUint64(args, _AT_PAGESZ)\n\targs = args[8:]\n\tbo.PutUint64(args, pageSize)\n\targs = args[8:]\n\t// End of auxv.\n\tbo.PutUint64(args, _AT_NULL)\n\targs = args[8:]\n\tbo.PutUint64(args, 0)\n\t// Binary name.\n\tbo.PutUint64(binAddr, uint64(uintptr(unsafe.Pointer(&args[0]))))\n\tn := copy(args, []byte(\"kernel\\x00\"))\n\targs = args[n:]\n}", "func SetEnv(e EnvType) {\n\tif e == EnvTypeDev ||\n\t\te == EnvTypeProd ||\n\t\te == EnvTypeTest {\n\t\tenv.Store(e)\n\t}\n}", "func SetGoMemLimitWithEnv() {\n\t_, _ = SetGoMemLimitWithOpts(WithEnv())\n}", "func assertEnv(ctx context.Context, client client.Client, spec corev1.PodSpec, component, container, key, expectedValue string) error {\n\tvalue, err := getEnv(ctx, client, spec, component, container, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value != nil && strings.ToLower(*value) != expectedValue {\n\t\treturn ErrIncompatibleCluster{\n\t\t\terr: fmt.Sprintf(\"%s=%s is not supported\", key, *value),\n\t\t\tcomponent: component,\n\t\t\tfix: fmt.Sprintf(\"remove the %s env var or set it to '%s'\", key, expectedValue),\n\t\t}\n\t}\n\n\treturn nil\n}", "func setVMElem(vms *VMs) {\n\tfor i := range vms.vm {\n\t\tvm := &vms.vm[i]\n\t\tvm.MemoryAssigned = vm.MemoryAssigned / 1024 / 1024 // MB\n\t\tvm.StateDesc, vm.IsRunning = parseState(vm.State)\n\t\tvm.HHMMSS = toHHMMSS(&vm.Uptime)\n\t}\n}", "func GetGPUMemoryFromPodEnv(pod *v1.Pod) (gpuMemory uint) {\n\tfor _, container := range pod.Spec.Containers {\n\t\tgpuMemory += getGPUMemoryFromContainerEnv(container)\n\t}\n\tlog.V(100).Info(\"debug: pod %s in ns %s with status %v has GPU Mem %d\",\n\t\tpod.Name,\n\t\tpod.Namespace,\n\t\tpod.Status.Phase,\n\t\tgpuMemory)\n\treturn gpuMemory\n}", "func (cg *colorChartController) setEnv(linearMatDataPath, dataPath, deviceQEDataPath string, ill models.IlluminationCode) {\n\t// initalize response controller\n\tcg.resController = NewResponseController()\n\n\t// light source setup\n\tcg.lithSource = ill\n\n\t// read Linear Matrix elements\n\tcg.linearMatrixElm = cg.readLinearMatElmFromCSV(linearMatDataPath)\n\n\t// set file path\n\tcg.filepath = cg.setReadingFile(dataPath, deviceQEDataPath)\n\n\t// read filepath\n\tcg.resController.ReadResponseData(cg.filepath)\n\n\t// clean up\n\tcg.cleanUp()\n\n}", "func TestEnvAddOnManagedNodeGroupsCNI(t *testing.T) {\n\tcfg := NewDefault()\n\tdefer func() {\n\t\tos.RemoveAll(cfg.ConfigPath)\n\t\tos.RemoveAll(cfg.KubectlCommandsOutputPath)\n\t\tos.RemoveAll(cfg.RemoteAccessCommandsOutputPath)\n\t}()\n\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_ENABLE\", `true`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_ENABLE\")\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_REMOTE_ACCESS_PRIVATE_KEY_PATH\", `a`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_REMOTE_ACCESS_PRIVATE_KEY_PATH\")\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_MNGS\", `{\"test-mng-for-cni\":{\"name\":\"test-mng-for-cni\",\"remote-access-user-name\":\"ec2-user\",\"tags\":{\"group\":\"amazon-vpc-cni-k8s\"},\"ami-type\":\"AL2_x86_64\",\"asg-min-size\":3,\"asg-max-size\":3,\"asg-desired-capacity\":3,\"instance-types\":[\"c5.xlarge\"]}}`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_MNGS\")\n\n\tif err := cfg.UpdateFromEnvs(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif err := cfg.ValidateAndSetDefaults(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tif cfg.RemoteAccessPrivateKeyPath != \"a\" {\n\t\tt.Fatalf(\"unexpected cfg.RemoteAccessPrivateKeyPath %q\", cfg.RemoteAccessPrivateKeyPath)\n\t}\n\texpectedMNGs := map[string]MNG{\n\t\t\"test-mng-for-cni\": {\n\t\t\tName: \"test-mng-for-cni\",\n\t\t\tRemoteAccessUserName: \"ec2-user\",\n\t\t\tTags: map[string]string{\"group\": \"amazon-vpc-cni-k8s\"},\n\t\t\tAMIType: \"AL2_x86_64\",\n\t\t\tASGMinSize: 3,\n\t\t\tASGMaxSize: 3,\n\t\t\tASGDesiredCapacity: 3,\n\t\t\tInstanceTypes: []string{\"c5.xlarge\"},\n\t\t\tVolumeSize: 40,\n\t\t},\n\t}\n\tif !reflect.DeepEqual(cfg.AddOnManagedNodeGroups.MNGs, expectedMNGs) {\n\t\tt.Fatalf(\"expected cfg.AddOnManagedNodeGroups.MNGs %+v, got %+v\", expectedMNGs, cfg.AddOnManagedNodeGroups.MNGs)\n\t}\n}", "func (b *taskBuilder) env(key, value string) {\n\tif b.Spec.Environment == nil {\n\t\tb.Spec.Environment = map[string]string{}\n\t}\n\tb.Spec.Environment[key] = value\n}", "func setupEnv(args *execdriver.InitArgs) error {\n\t// Get env\n\tvar env []string\n\tcontent, err := ioutil.ReadFile(\".dockerenv\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Unable to load environment variables: %v\", err)\n\t}\n\tif err := json.Unmarshal(content, &env); err != nil {\n\t\treturn fmt.Errorf(\"Unable to unmarshal environment variables: %v\", err)\n\t}\n\t// Propagate the plugin-specific container env variable\n\tenv = append(env, \"container=\"+os.Getenv(\"container\"))\n\n\targs.Env = env\n\n\tos.Clearenv()\n\tfor _, kv := range args.Env {\n\t\tparts := strings.SplitN(kv, \"=\", 2)\n\t\tif len(parts) == 1 {\n\t\t\tparts = append(parts, \"\")\n\t\t}\n\t\tos.Setenv(parts[0], parts[1])\n\t}\n\n\treturn nil\n}", "func (c *KubeTestPlatform) SetAppEnv(name, key, value string) error {\n\tapp := c.AppResources.FindActiveResource(name)\n\tappManager := app.(*kube.AppManager)\n\n\tif err := appManager.SetAppEnv(key, value); err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := appManager.WaitUntilDeploymentState(appManager.IsDeploymentDone); err != nil {\n\t\treturn err\n\t}\n\n\tappManager.StreamContainerLogs()\n\n\treturn nil\n}", "func (ci MrbCallInfo) EnvSet(e *REnv) {\n\tif e == nil {\n\t\tC.mrb_vm_ci_env_set(ci.p, nil)\n\t\treturn\n\t}\n\tC.mrb_vm_ci_env_set(ci.p, e.p)\n}", "func addEnvironmentFlag(cmd *cobra.Command) {\n\tcmd.Flags().StringArrayVarP(&environment, \"env\", \"e\", []string{}, \"environment variables to pass to container\")\n}", "func (p RProc) SetEnv(stackItems ...Value) {\n\tif len(stackItems) == 0 {\n\t\tC._mrb_create_env(p.mrb.p, p.p, 0, nil)\n\t\treturn\n\t}\n\n\tC._mrb_create_env(p.mrb.p, p.p, C.mrb_int(len(stackItems)), &(stackItems[0].v))\n}", "func (w *WebGl) SetEnv() (rerr error) {\n\tlog.Debug(\"Setting emscripten environment variables\")\n\temsdkEnv := filepath.Join(conf.EmscriptenSDKRoot, \"emsdk_env.sh\")\n\toutput, err := sys.ExecuteEx(\"bash\", \"\", true, \"-c\", emsdkEnv)\n\tif err != nil {\n\t\treturn errorx.Decorate(err, \"failed to call emsdk_env.sh: \"+output)\n\t}\n\temsdkSetEnv := filepath.Join(conf.EmscriptenSDKRoot, \"emsdk_set_env.sh\")\n\tfile, err := os.Open(emsdkSetEnv)\n\tif err != nil {\n\t\treturn errorx.Decorate(err, \"could not open emsdk_set_env.sh\")\n\t}\n\tdefer func() {\n\t\tif err := file.Close(); err != nil {\n\t\t\trerr = err\n\t\t}\n\t}()\n\n\tscanner := bufio.NewScanner(file)\n\tre := regexp.MustCompile(\"export (.*)=\\\"(.*)\\\"\")\n\tlineNumber := 0\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tlineNumber++\n\t\tif !re.MatchString(line) {\n\t\t\treturn fmt.Errorf(\"could not parse line %d of emsdk_set_env.sh: %s\", lineNumber, line)\n\t\t}\n\t\tenvVarName := re.FindStringSubmatch(line)[1]\n\t\tenvVarValue := re.FindStringSubmatch(line)[2]\n\t\tlog.Debugf(\"%s=%s\", envVarName, envVarValue)\n\t\tif err = os.Setenv(envVarName, envVarValue); err != nil {\n\t\t\treturn errorx.Decorate(err, \"failed to set environment variable %s to %s\", envVarName, envVarValue)\n\t\t}\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn errorx.Decorate(err, \"could not read lines of emsdk_set_env.sh\")\n\t}\n\treturn nil\n}", "func (c *Context) SetEnvironment(e string) { c.envName = e }", "func TestENV(t *testing.T) {\n\tif confy.GetEnvironment() != \"test\" {\n\t\tt.Skipf(\"skipping test. Env should be test when running `go test`, instead env is %v\", confy.GetEnvironment())\n\t}\n\n\tos.Setenv(\"CONFY_ENV\", \"production\")\n\tdefer os.Setenv(\"CONFY_ENV\", \"\")\n\tconfy.DefaultConfy = confy.NewConfy()\n\tif confy.GetEnvironment() != \"production\" {\n\t\tt.Errorf(\"Env should be production when set it with CONFY_ENV\")\n\t}\n}", "func EnvVarTest(resourceName string, sourceType string, envString string) {\n\n\tif sourceType == \"git\" {\n\t\t// checking the values of the env vars pairs in bc\n\t\tenvVars := runCmd(\"oc get bc \" + resourceName + \" -o go-template='{{range .spec.strategy.sourceStrategy.env}}{{.name}}{{.value}}{{end}}'\")\n\t\tExpect(envVars).To(Equal(envString))\n\t}\n\n\t// checking the values of the env vars pairs in dc\n\tenvVars := runCmd(\"oc get dc \" + resourceName + \" -o go-template='{{range .spec.template.spec.containers}}{{range .env}}{{.name}}{{.value}}{{end}}{{end}}'\")\n\tExpect(envVars).To(Equal(envString))\n}", "func SetEnv(addr, pemCert, token, role string) {\n\tos.Setenv(\"ADDR\", addr)\n\tos.Setenv(\"CACERT\", pemCert)\n\tos.Setenv(\"TOKEN\", token)\n\tos.Setenv(\"ROLE\", role)\n}", "func eventMonitorBindEnv(config Config, key string) {\n\temConfigKey := \"DD_\" + strings.Replace(strings.ToUpper(key), \".\", \"_\", -1)\n\truntimeSecKey := strings.Replace(emConfigKey, \"EVENT_MONITORING_CONFIG\", \"RUNTIME_SECURITY_CONFIG\", 1)\n\n\tconfig.BindEnv(key, emConfigKey, runtimeSecKey)\n}", "func Setenv(key, value string) error", "func setDefaultEnvironment() {\n\tdefaultAppEnv := os.Getenv(\"APP_ENV\")\n\tif defaultAppEnv == \"\" {\n\t\tdefaultAppEnv = \"production\"\n\t}\n\n\tdefaultConfigPathEnv := os.Getenv(\"ROOM_CALC_CONFIG_DIRECTORY\")\n\tif defaultConfigPathEnv == \"\" {\n\t\tdefaultConfigPathEnv = \".\"\n\t}\n\n\tviper.SetDefault(\"APP_ENV\", defaultAppEnv)\n\tviper.SetDefault(\"ROOM_CALC_CONFIG_DIRECTORY\", defaultConfigPathEnv)\n\tviper.SetDefault(\"VERSION\", Version)\n\tviper.SetDefault(\"BUILD\", Build)\n\n\tviper.SetDefault(\"log.file\", \"./logs/gutils.log\")\n\tviper.SetDefault(\"log.level\", \"INFO\")\n\tcmd.SetDefaults()\n}", "func setPulumiAccessTokenEvnVariable(token string) error {\n\t// Set the token.\n\terr := os.Setenv(pulumiAccessTokenEnvName, token)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting Pulumi Access Token Environment Variable: %v\", err)\n\t}\n\n\t// Validate the token is set.\n\terr = validateAccessToken(token)\n\tif err != nil {\n\t\terr = os.Unsetenv(pulumiAccessTokenEnvName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Error unsetting invalid Pulumi Access Token: %v\", err)\n\t\t}\n\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func SetProdEnv() {\n\tos.Setenv(\"ENV\", \"prod\")\n\tos.Setenv(\"PG_USER\", \"root\")\n\tos.Setenv(\"PG_HOST\", \"26257\")\n\tos.Setenv(\"PG_PORT\", \"203.151.50.153\")\n\tos.Setenv(\"PG_DATABASENAME\", \"qa_irecruit\")\n\tos.Setenv(\"PG_PASSWORD\", \"1412\")\n}", "func setupEnvironment(ctx context.Context) {\n\tEnv = os.Getenv(\"ENV\")\n\tif Env == \"\" {\n\t\tfmt.Printf(\"ENV not configured\\n\")\n\t}\n\tAppConfigPath = os.Getenv(\"APP_CONFIG_PATH\")\n\tif AppConfigPath == \"\" {\n\t\tfmt.Printf(\"APP_CONFIG_PATH not configured'n\")\n\t}\n\n\tparams, err := getParamsFromSSM(ctx)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to get from SSM: %v\\n\", err)\n\t}\n\n\tClients = params.Clients\n\tfor i, v := range Clients {\n\t\tClients[i] = strings.ToUpper(v)\n\t}\n\tfmt.Printf(\"Loaded %d devices\\n\", len(Clients))\n\n\tOpenhabURL = params.OpenhabURL\n\tauthString := fmt.Sprintf(\"%s:%s\", params.OpenhabUser, params.OpenhabPwd)\n\tOpenhabAuth = base64.StdEncoding.EncodeToString([]byte(authString))\n\n\tSecret = params.Secret\n}", "func envAppend(flag *pflag.Flag, envvar string) {\n\tif err := flag.Value.Set(envvar); err != nil {\n\t\tsylog.Warningf(\"Unable to set %s to environment variable value %s\", flag.Name, envvar)\n\t} else {\n\t\tflag.Changed = true\n\t\tsylog.Debugf(\"Update flag Value to: %s\", flag.Value)\n\t}\n}", "func SetEnvs(iface interface{}) error {\n\tv := reflect.Indirect(reflect.ValueOf(iface))\n\tif v.Kind() != reflect.Struct {\n\t\treturn errors.Errorf(\"expected struct, received %v\", v.Type())\n\t}\n\tfor i := 0; i < v.Type().NumField(); i++ {\n\t\tfv := v.Field(i)\n\t\ttv, ok := v.Type().Field(i).Tag.Lookup(\"env\")\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif v, ok := os.LookupEnv(strings.ToUpper(tv)); ok {\n\t\t\tif err := setValue(fv, v); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (ev Vars) Set(envVar, value string) {\n\tev[envVar] = value\n}", "func TestEnvAddOnManagedNodeGroupsInvalidInstanceType(t *testing.T) {\n\tcfg := NewDefault()\n\tdefer func() {\n\t\tos.RemoveAll(cfg.ConfigPath)\n\t\tos.RemoveAll(cfg.KubectlCommandsOutputPath)\n\t\tos.RemoveAll(cfg.RemoteAccessCommandsOutputPath)\n\t}()\n\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_ENABLE\", `true`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_ENABLE\")\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_REMOTE_ACCESS_PRIVATE_KEY_PATH\", `a`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_REMOTE_ACCESS_PRIVATE_KEY_PATH\")\n\tos.Setenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_MNGS\", `{\"test-mng-for-cni\":{\"name\":\"test-mng-for-cni\",\"tags\":{\"group\":\"amazon-vpc-cni-k8s\"},\"ami-type\":\"AL2_x86_64\",\"asg-min-size\":3,\"asg-max-size\":3,\"asg-desired-capacity\":3,\"instance-types\":[\"m3.xlarge\"]}}`)\n\tdefer os.Unsetenv(\"AWS_K8S_TESTER_EKS_ADD_ON_MANAGED_NODE_GROUPS_MNGS\")\n\n\tif err := cfg.UpdateFromEnvs(); err != nil {\n\t\tt.Fatal(err)\n\t}\n\terr := cfg.ValidateAndSetDefaults()\n\tif err == nil {\n\t\tt.Fatal(\"expected error\")\n\t}\n\tif !strings.Contains(err.Error(), \"older instance type InstanceTypes\") {\n\t\tt.Fatalf(\"unexpected error %v\", err)\n\t}\n}", "func (ctx *Context) AddEnv(cmd *exec.Cmd) {\n\tcmd.Env = append(cmd.Environ(),\n\t\tfmt.Sprintf(\"PX_CLOUD_ADDR=%s\", ctx.cloudAddr),\n\t\tfmt.Sprintf(\"PX_API_KEY=%s\", ctx.apiKey),\n\t)\n}", "func (e *Environ) Set(key, val string) {\n\te.Unset(key)\n\t*e = append(*e, key+\"=\"+val)\n}", "func setEnv() {\n\tos.Setenv(\"MYSQL_DB_ENDPOINT\", \"db-mysql:3306\")\n\tos.Setenv(\"MYSQL_DB_PORT\", \"3306\")\n\tos.Setenv(\"MYSQL_DB_SCHEMA\", \"instagram_bot\")\n\tos.Setenv(\"MYSQL_DB_USER\", \"root\")\n\tos.Setenv(\"MYSQL_DB_PASSWORD\", \"root\")\n}", "func SetCustomEnvs(credentialsDir string) {\n\n\tsecretsByte, err := ioutil.ReadFile(\"../\" + credentialsDir + \"/secret.json\")\n\tvar secrets Secrets\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.Unmarshal(secretsByte, &secrets)\n\t// fmt.Print(string(secretsByte))\n\n\tenvByte, err := ioutil.ReadFile(\"../\" + credentialsDir + \"/env.json\")\n\tvar envs Envs\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tjson.Unmarshal(envByte, &envs)\n\t// fmt.Print(string(envByte))\n\n\tos.Setenv(global_environment.ENV_KEY_FIREBASE_DB_URL, envs.Fb_database_url)\n\tos.Setenv(global_environment.ENV_KEY_WW_JWT_PEPPER_OBJ, secrets.Ww_jwt_pepper_encoded)\n\tos.Setenv(global_environment.ENV_KEY_FIREBASE_CREDENTIALS, secrets.Fb_admin)\n\n}", "func assertEnvIsSet(ctx context.Context, client client.Client, spec corev1.PodSpec, component, container, key, expectedValue string) error {\n\tvalue, err := getEnv(ctx, client, spec, component, container, key)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif value == nil || strings.ToLower(*value) != expectedValue {\n\t\treturn ErrIncompatibleCluster{\n\t\t\terr: fmt.Sprintf(\"%s=%s is not supported\", key, *value),\n\t\t\tcomponent: component,\n\t\t\tfix: fmt.Sprintf(\"remove the %s env var or set it to '%s'\", key, expectedValue),\n\t\t}\n\t}\n\n\treturn nil\n}", "func addEnv(s *scope, arg pyObject, target *core.BuildTarget) {\n\tenvPy, ok := asDict(arg)\n\ts.Assert(ok, \"env must be a dict\")\n\n\tenv := make(map[string]string, len(envPy))\n\tfor name, val := range envPy {\n\t\tv, ok := val.(pyString)\n\t\ts.Assert(ok, \"Values of env must be strings, found %v at key %v\", val.Type(), name)\n\t\tenv[name] = string(v)\n\t}\n\n\ttarget.Env = env\n}", "func (s) TestJSONEnvVarSet(t *testing.T) {\n\tconfigJSON := `{\n\t\t\"project_id\": \"fake\"\n\t}`\n\tcleanup, err := createTmpConfigInFileSystem(configJSON)\n\tdefer cleanup()\n\n\tif err != nil {\n\t\tt.Fatalf(\"failed to create config in file system: %v\", err)\n\t}\n\tctx, cancel := context.WithTimeout(context.Background(), defaultTestTimeout)\n\tdefer cancel()\n\tif err := Start(ctx); err != nil {\n\t\tt.Fatalf(\"error starting observability with valid config through file system: %v\", err)\n\t}\n\tdefer End()\n}", "func (e *environ) Set(key, val string) {\n\te.Unset(key)\n\t*e = append(*e, key+\"=\"+val)\n}", "func TestE2ESuites(t *testing.T) {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err := os.Setenv(\"APISIX_MESH_AGENT_E2E_HOME\", pwd); err != nil {\n\t\tpanic(err)\n\t}\n\n\tginkgo.RunSpecs(t, \"apisix-mesh-agent e2e test cases\")\n}", "func SetEnv() {\r\n\tvar error error\r\n\r\n\tif error = godotenv.Load(); error != nil {\r\n\t\tlog.Fatal(error)\r\n\t}\r\n\r\n\tPort, error = strconv.Atoi(os.Getenv(\"APP_PORT\"))\r\n\tif error != nil {\r\n\t\tlog.Fatal(error)\r\n\t}\r\n\r\n\tAPIURL = os.Getenv(\"API_URL\")\r\n\tHashKey = []byte(os.Getenv(\"HASH_KEY\"))\r\n\tBlockKey = []byte(os.Getenv(\"BLOCK_KEY\"))\r\n}", "func (em envmap) set() error {\n\tfor k, v := range em {\n\t\terr := os.Setenv(k, v)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func setupMemory(ctx context.Context, r types.Resources, s *specs.Spec) {\n\tmemory := &specs.LinuxMemory{}\n\tif r.Memory > 0 {\n\t\tv := r.Memory\n\t\tmemory.Limit = &v\n\t}\n\n\tif r.MemorySwap != 0 {\n\t\tv := r.MemorySwap\n\t\tmemory.Swap = &v\n\t}\n\n\tif r.MemorySwappiness != nil {\n\t\tv := uint64(*r.MemorySwappiness)\n\t\tmemory.Swappiness = &v\n\t}\n\n\tif r.OomKillDisable != nil {\n\t\tv := bool(*r.OomKillDisable)\n\t\tmemory.DisableOOMKiller = &v\n\t}\n\n\ts.Linux.Resources.Memory = memory\n}", "func eventMonitorBindEnvAndSetDefault(config Config, key string, val interface{}) {\n\t// Uppercase, replace \".\" with \"_\" and add \"DD_\" prefix to key so that we follow the same environment\n\t// variable convention as the core agent.\n\temConfigKey := \"DD_\" + strings.Replace(strings.ToUpper(key), \".\", \"_\", -1)\n\truntimeSecKey := strings.Replace(emConfigKey, \"EVENT_MONITORING_CONFIG\", \"RUNTIME_SECURITY_CONFIG\", 1)\n\n\tenvs := []string{emConfigKey, runtimeSecKey}\n\tconfig.BindEnvAndSetDefault(key, val, envs...)\n}", "func GetUpdatedPodEnvSpec(oldPod *v1.Pod, devId int, totalGPUMemByDev int) (newPod *v1.Pod) {\n\tnewPod = oldPod.DeepCopy()\n\tfor i, c := range newPod.Spec.Containers {\n\t\tgpuMem := GetGPUMemoryFromContainerResource(c)\n\n\t\tif gpuMem > 0 {\n\t\t\tenvs := []v1.EnvVar{\n\t\t\t\t// v1.EnvVar{Name: EnvNVGPU, Value: fmt.Sprintf(\"%d\", devId)},\n\t\t\t\tv1.EnvVar{Name: EnvResourceIndex, Value: fmt.Sprintf(\"%d\", devId)},\n\t\t\t\tv1.EnvVar{Name: EnvResourceByPod, Value: fmt.Sprintf(\"%d\", gpuMem)},\n\t\t\t\tv1.EnvVar{Name: EnvResourceByDev, Value: fmt.Sprintf(\"%d\", totalGPUMemByDev)},\n\t\t\t\tv1.EnvVar{Name: EnvAssignedFlag, Value: \"false\"},\n\t\t\t}\n\n\t\t\tfor _, env := range envs {\n\t\t\t\tnewPod.Spec.Containers[i].Env = append(newPod.Spec.Containers[i].Env,\n\t\t\t\t\tenv)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn newPod\n}", "func NewEnv(context *libcoap.Context) *Env {\n return &Env{\n context,\n nil,\n make(chan Event, 32),\n nil,\n }\n}", "func SetEnvironment(e *Environment) {\n\tenv = e\n}", "func toEnv(spec *engine.Spec, step *engine.Step) []v1.EnvVar {\n\tvar to []v1.EnvVar\n\tfor k, v := range step.Envs {\n\t\tto = append(to, v1.EnvVar{\n\t\t\tName: k,\n\t\t\tValue: v,\n\t\t})\n\t}\n\tto = append(to, v1.EnvVar{\n\t\tName: \"KUBERNETES_NODE\",\n\t\tValueFrom: &v1.EnvVarSource{\n\t\t\tFieldRef: &v1.ObjectFieldSelector{\n\t\t\t\tFieldPath: \"spec.nodeName\",\n\t\t\t},\n\t\t},\n\t})\n\tfor _, secret := range step.Secrets {\n\t\tsec, ok := engine.LookupSecret(spec, secret)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\toptional := true\n\t\tto = append(to, v1.EnvVar{\n\t\t\tName: secret.Env,\n\t\t\tValueFrom: &v1.EnvVarSource{\n\t\t\t\tSecretKeyRef: &v1.SecretKeySelector{\n\t\t\t\t\tLocalObjectReference: v1.LocalObjectReference{\n\t\t\t\t\t\tName: sec.Metadata.UID,\n\t\t\t\t\t},\n\t\t\t\t\tKey: sec.Metadata.UID,\n\t\t\t\t\tOptional: &optional,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\treturn to\n}", "func GetInitiatorEnvArr(svctype string, embedded bool, chunkCacheSize resource.Quantity, resources v1.ResourceRequirements) []v1.EnvVar {\n\tretArr := []v1.EnvVar{}\n\trMemLim := resources.Limits.Memory()\n\tif !rMemLim.IsZero() {\n\t\t// adjust chunk cache maximum size\n\t\tcacheSize := rMemLim.Value() * 75 / 100\n\t\tif embedded {\n\t\t\t// embedded default case, 100mb\n\t\t\tcacheSize = 100 * 1024 * 1024\n\t\t}\n\n\t\tif !chunkCacheSize.IsZero() && chunkCacheSize.CmpInt64(cacheSize) < 0 {\n\t\t\t// user wants to set custom cache size\n\t\t\t// It might be lowered below\n\t\t\tcacheSize = chunkCacheSize.Value()\n\t\t}\n\n\t\tif svctype == \"target\" {\n\t\t\t// adjust target's built-in cgroup\n\t\t\tcgroupTgt := rMemLim.Value() * 95 / 100\n\t\t\tif cgroupTgt <= cacheSize {\n\t\t\t\t// in targets case chunk cache only needed for\n\t\t\t\t// background operations. This was probably not\n\t\t\t\t// a user's intent, so adjust to a much lower values\n\t\t\t\tcacheSize = cgroupTgt / 8\n\t\t\t}\n\t\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\t\tName: \"CCOWD_CGROUP_MEMLIM\",\n\t\t\t\tValue: strconv.FormatInt(cgroupTgt, 10),\n\t\t\t})\n\t\t} else if svctype == \"isgw\" {\n\t\t\t// ISGW doesn't need large chunk cache\n\t\t\tcacheSize = rMemLim.Value() * 25 / 100\n\t\t} else if svctype == \"s3\" || svctype == \"swift\" {\n\t\t\t// adjust restapi's node.js GC settings. This memory\n\t\t\t// will be shared among all the HTTP worker processes\n\t\t\t// and will be used to calculate optimal # of workers too.\n\t\t\tsvcMem := rMemLim.Value() * 95 / 100\n\t\t\tif svcMem <= cacheSize {\n\t\t\t\tcacheSize = svcMem / 2\n\t\t\t}\n\t\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\t\tName: \"SVC_MEM_LIMIT\",\n\t\t\t\tValue: strconv.FormatInt(svcMem, 10),\n\t\t\t})\n\t\t\tsvcMemPerWorker := int64(1 * 1024 * 1024 * 1024)\n\t\t\tif embedded {\n\t\t\t\tsvcMemPerWorker = int64(256 * 1024 * 1024)\n\t\t\t}\n\t\t\tif svcMem < svcMemPerWorker {\n\t\t\t\tsvcMemPerWorker = svcMem / 2\n\t\t\t}\n\t\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\t\tName: \"SVC_MEM_PER_WORKER\",\n\t\t\t\tValue: strconv.FormatInt(svcMemPerWorker, 10),\n\t\t\t})\n\t\t}\n\n\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\tName: \"CCOW_MEMORY_LIMIT\",\n\t\t\tValue: strconv.FormatInt(cacheSize, 10),\n\t\t})\n\t}\n\trCpuLim := resources.Limits.Cpu()\n\tif !rCpuLim.IsZero() {\n\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\tName: \"SVC_CPU_LIMIT\",\n\t\t\tValue: strconv.FormatInt(rCpuLim.Value(), 10),\n\t\t})\n\t}\n\n\tif embedded {\n\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\tName: \"CCOW_EMBEDDED\",\n\t\t\tValue: \"1\",\n\t\t})\n\t\tretArr = append(retArr, v1.EnvVar{\n\t\t\tName: \"JE_MALLOC_CONF\",\n\t\t\tValue: \"tcache:false\",\n\t\t})\n\t}\n\n\treturn retArr\n}", "func addEnv(cmd *exec.Cmd, inName, inValue string) {\n\te := fmt.Sprintf(EnvPattern, strings.ToUpper(inName), inValue)\n\tcmd.Env = append(cmd.Env, e)\n}", "func NewEnv(name string, gp *pool.GoroutinePool) adapter.Env {\n\treturn env{\n\t\t// logger: newLogger(name),\n\t\tgp: gp,\n\t\tdaemons: new(int64),\n\t\tworkers: new(int64),\n\t}\n}", "func (hc ApplicationsController) EnvSet(w http.ResponseWriter, r *http.Request) APIErrors {\n\tctx := r.Context()\n\tlog := tracelog.Logger(ctx)\n\n\tparams := httprouter.ParamsFromContext(ctx)\n\torgName := params.ByName(\"org\")\n\tappName := params.ByName(\"app\")\n\n\tlog.Info(\"processing environment variable assignment\",\n\t\t\"org\", orgName, \"app\", appName)\n\n\tcluster, err := kubernetes.GetCluster(ctx)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\texists, err := organizations.Exists(ctx, cluster, orgName)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn OrgIsNotKnown(orgName)\n\t}\n\n\tapp := models.NewAppRef(appName, orgName)\n\n\texists, err = application.Exists(ctx, cluster, app)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tif !exists {\n\t\treturn AppIsNotKnown(appName)\n\t}\n\n\tdefer r.Body.Close()\n\tbodyBytes, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\tvar setRequest models.EnvVariableList\n\terr = json.Unmarshal(bodyBytes, &setRequest)\n\tif err != nil {\n\t\treturn BadRequest(err)\n\t}\n\n\terr = application.EnvironmentSet(ctx, cluster, app, setRequest)\n\tif err != nil {\n\t\treturn InternalError(err)\n\t}\n\n\treturn nil\n}", "func LoadTestEnv() *core.Engine {\n\tengine := new(core.Engine)\n\n\t_, dir, _, _ := runtime.Caller(0)\n\tconfigJSON := filepath.Join(filepath.Dir(dir), \"../..\", \"env\", \"tdd.json\")\n\n\tjsonFile, err := os.Open(configJSON)\n\n\tif err != nil {\n\t\tlog.Fatalln(err, \"can't open the config file\", dir+\"/regularenvs.json\")\n\t}\n\n\tdefer jsonFile.Close()\n\n\tbyteValue, _ := ioutil.ReadAll(jsonFile)\n\n\terr = json.Unmarshal(byteValue, &engine.Env)\n\tif err != nil {\n\t\tlog.Fatalln(err, \"error in unmarshal JSON\")\n\t}\n\n\tif engine.Env.MachineID, err = machineid.ProtectedID(\"SigmaMono\"); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn engine\n}", "func InjectEnvIntoDeployment(podSpec *corev1.PodSpec, envVars []corev1.EnvVar) error {\n\tif podSpec == nil {\n\t\treturn errors.New(\"no pod spec provided\")\n\t}\n\n\tfor i := range podSpec.Containers {\n\t\tcontainer := &podSpec.Containers[i]\n\t\tcontainer.Env = merge(container.Env, envVars)\n\t}\n\n\treturn nil\n}", "func newTestEnvironment(eventJSONFilePath string, shipyardPath string, jobConfigPath string) (*testEnvironment, error) {\n\n\t// Create K8s clientset\n\tclientset, err := NewK8sClient()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to build k8s clientset: %w\", err)\n\t}\n\n\t// Create a new Keptn api for the use of the E2E test\n\tkeptnAPI, err := NewKeptnAPI(readKeptnConnectionDetailsFromEnv())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to create the keptn API: %w\", err)\n\t}\n\n\t// Read the event we want to trigger and extract the project, service and stage\n\tkeptnEvent, err := readKeptnContextExtendedCE(eventJSONFilePath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable parse JSON event file: %w\", err)\n\t}\n\n\teventData, err := parseKeptnEventData(keptnEvent)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable parse event data of the JSON event: %w\", err)\n\t}\n\n\t// Load shipyard file and create the project in Keptn\n\tshipyardFile, err := ioutil.ReadFile(shipyardPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the shipyard file: %w\", err)\n\t}\n\n\t// Load the job configuration for the E2E test\n\tjobConfigYaml, err := ioutil.ReadFile(jobConfigPath)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the job configuration file: %w\", err)\n\t}\n\n\treturn &testEnvironment{\n\t\tK8s: clientset,\n\t\tAPI: keptnAPI,\n\t\tEventData: eventData,\n\t\tEvent: keptnEvent,\n\t\tNamespace: \"keptn\",\n\t\tshipyard: shipyardFile,\n\t\tjobConfig: jobConfigYaml,\n\t}, nil\n}", "func (b *Benchmark) SetUnifiedMemory() {\n\tpanic(\"unified memory is not supported by dnn workloads\")\n}", "func (b *Benchmark) SetUnifiedMemory() {\n\tpanic(\"unified memory is not supported by dnn workloads\")\n}", "func setAWSEnv(c *cli.Context) {\n\tconst errmsg = \"could not set %s environment variable\"\n\terr := os.Setenv(awsRegionEnv, c.String(awsRegion))\n\tif err != nil {\n\t\tlogger.Get().Errorw(fmt.Sprintf(errmsg, awsRegionEnv), \"error\", err.Error())\n\t}\n\terr = os.Setenv(awsAccessKeyEnv, c.String(awsAccessKey))\n\tif err != nil {\n\t\tlogger.Get().Errorw(fmt.Sprintf(errmsg, awsAccessKeyEnv), \"error\", err.Error())\n\t}\n\terr = os.Setenv(awsSecretKeyEnv, c.String(awsSecretKey))\n\tif err != nil {\n\t\tlogger.Get().Errorw(fmt.Sprintf(errmsg, awsSecretKeyEnv), \"error\", err.Error())\n\t}\n}", "func Test_Customized_Env(t *testing.T) {\n\tRegisterFailHandler(Fail)\n\tRunSpecs(t, \"Customized Env Svc Suite\")\n}", "func (r *CheckedDaemonSet) assertEnv(ctx context.Context, client client.Client, container, key, expectedValue string) error {\n\tif err := assertEnv(ctx, client, r.Spec.Template.Spec, ComponentCalicoNode, container, key, expectedValue); err != nil {\n\t\treturn err\n\t}\n\tr.ignoreEnv(container, key)\n\treturn nil\n}", "func Set() error {\n\tvar err error\n\tmyEnv, err = godotenv.Read()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Cli) EnvInt64Var(p *int64, name string, value int64, usage string) error {\n\tc.env[name] = &EnvAttribute{\n\t\tName: name,\n\t\tType: fmt.Sprintf(\"%T\", value),\n\t\tInt64Value: value,\n\t\tUsage: usage,\n\t}\n\tp = &c.env[name].Int64Value\n\t_, ok := c.env[name]\n\tif ok == false {\n\t\treturn fmt.Errorf(\"%q could not be added to environment attributes\", name)\n\t}\n\treturn nil\n}", "func init() {\n\tenvironments = make(map[string]string)\n\n\tfor _, e := range os.Environ() {\n\t\tspl := strings.SplitN(e, \"=\", 2)\n\t\tenvironments[spl[0]] = spl[1]\n\t}\n}", "func setupEnvConfigViper(environmentFlag string) *viper.Viper {\n\tconfig := viper.New()\n\tconfig.SetConfigName(environmentFlag)\n\tconfig.AddConfigPath(\"./.argo/environments\")\n\tif err := config.ReadInConfig(); err != nil {\n\t\tcolor.Red(\"%s\",err)\n\t\tcolor.Red(\"Error locating or parsing %s env's helm value file (should be ./argo/environments/%s.yaml!\", environmentFlag)\n\t\tos.Exit(1)\n\t}\n\treturn config\n}", "func (c *ProcConfig) Envs() []string {\n\tconst format = \"%s=%s\"\n\treturn append(c.ProcEnvs, fmt.Sprintf(format, EnvProcConfig, string(c.encodeJSON())))\n}", "func SetEnv() {\n\tos.Setenv(\"ENV\", \"dev\")\n\tos.Setenv(\"DB_HOST\", \"mysql.faceit-test.local:3306\")\n\tos.Setenv(\"DB_USER\", \"faceit\")\n\tos.Setenv(\"DB_PASSWORD\", \"faceit\")\n\tos.Setenv(\"DB_NAME\", \"faceit\")\n\tos.Setenv(\"TZ\", \"Europe/London\")\n\tvar sb strings.Builder\n\tsb.WriteString(os.Getenv(\"DB_USER\"))\n\tsb.WriteString(\":\")\n\tsb.WriteString(os.Getenv(\"DB_PASSWORD\"))\n\tsb.WriteString(\"@tcp(\")\n\tsb.WriteString(os.Getenv(\"DB_HOST\"))\n\tsb.WriteString(\")/\")\n\tsb.WriteString(os.Getenv(\"DB_NAME\"))\n\tos.Setenv(\"DB_URL\", sb.String())\n}", "func SetPodAnnotationsBaseContainerEnvs(container corev1.Container, podAnnotations map[string]string) {\n\tif podAnnotations == nil {\n\t\tpodAnnotations = make(map[string]string)\n\t}\n\n\tfor _, env := range container.Env {\n\t\tif annotationKey := util.ParseAnnotationFromEnv(env.Name); annotationKey != \"\" {\n\t\t\tpodAnnotations[annotationKey] = env.Value\n\t\t}\n\t}\n}", "func (ccc *CustomCloudConfig) SetEnvironment() error {\n\tvar cmd *exec.Cmd\n\tvar err error\n\n\t// Add to python cert store the self-signed root CA generated by Azure Stack's CI\n\t// as azure-cli complains otherwise\n\tazsSelfSignedCaPath := \"/aks-engine/Certificates.pem\"\n\tif _, err = os.Stat(azsSelfSignedCaPath); err == nil {\n\t\t// latest dev_image has an azure-cli version that requires python3\n\t\tcert_command := fmt.Sprintf(`VER=$(python3 -V | grep -o [0-9].[0-9]*. | grep -o [0-9].[0-9]*);\n\t\tCA=/usr/local/lib/python${VER}/dist-packages/certifi/cacert.pem;\n\t\tif [ -f ${CA} ]; then cat %s >> ${CA}; fi;`, azsSelfSignedCaPath)\n\t\t// include cacert.pem from python2.7 path for upgrade scenario\n\t\tif _, err := os.Stat(\"/usr/local/lib/python2.7/dist-packages/certifi/cacert.pem\"); err == nil {\n\t\t\tcert_command = fmt.Sprintf(`CA=/usr/local/lib/python2.7/dist-packages/certifi/cacert.pem;\n\t\t\tif [ -f ${CA} ]; then cat %s >> ${CA}; fi;`, azsSelfSignedCaPath)\n\t\t}\n\n\t\tcmd := exec.Command(\"/bin/bash\", \"-c\", cert_command)\n\n\t\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\t\tlog.Printf(\"output:%s\\n\", out)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tenvironmentName := fmt.Sprintf(\"AzureStack%v\", time.Now().Unix())\n\tif ccc.TimeoutCommands {\n\t\tcmd = exec.Command(\"timeout\", \"60\", \"az\", \"cloud\", \"register\",\n\t\t\t\"-n\", environmentName,\n\t\t\t\"--endpoint-resource-manager\", ccc.ResourceManagerEndpoint,\n\t\t\t\"--suffix-storage-endpoint\", ccc.StorageEndpointSuffix,\n\t\t\t\"--suffix-keyvault-dns\", ccc.KeyVaultDNSSuffix,\n\t\t\t\"--endpoint-active-directory-resource-id\", ccc.ServiceManagementEndpoint,\n\t\t\t\"--endpoint-active-directory\", ccc.ActiveDirectoryEndpoint,\n\t\t\t\"--endpoint-active-directory-graph-resource-id\", ccc.GraphEndpoint)\n\t} else {\n\t\tcmd = exec.Command(\"az\", \"cloud\", \"register\",\n\t\t\t\"-n\", environmentName,\n\t\t\t\"--endpoint-resource-manager\", ccc.ResourceManagerEndpoint,\n\t\t\t\"--suffix-storage-endpoint\", ccc.StorageEndpointSuffix,\n\t\t\t\"--suffix-keyvault-dns\", ccc.KeyVaultDNSSuffix,\n\t\t\t\"--endpoint-active-directory-resource-id\", ccc.ServiceManagementEndpoint,\n\t\t\t\"--endpoint-active-directory\", ccc.ActiveDirectoryEndpoint,\n\t\t\t\"--endpoint-active-directory-graph-resource-id\", ccc.GraphEndpoint)\n\t}\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tlog.Printf(\"output:%s\\n\", out)\n\t\treturn err\n\t}\n\n\tif ccc.TimeoutCommands {\n\t\tcmd = exec.Command(\"timeout\", \"60\", \"az\", \"cloud\", \"set\", \"-n\", environmentName)\n\t} else {\n\t\tcmd = exec.Command(\"az\", \"cloud\", \"set\", \"-n\", environmentName)\n\t}\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tlog.Printf(\"output:%s\\n\", out)\n\t\treturn err\n\t}\n\n\tif ccc.TimeoutCommands {\n\t\tcmd = exec.Command(\"timeout\", \"60\", \"az\", \"cloud\", \"update\", \"--profile\", ccc.APIProfile)\n\t} else {\n\t\tcmd = exec.Command(\"az\", \"cloud\", \"update\", \"--profile\", ccc.APIProfile)\n\t}\n\tif out, err := cmd.CombinedOutput(); err != nil {\n\t\tlog.Printf(\"output:%s\\n\", out)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestEnviron(t *testing.T) {\n\ttests := map[string]string{\n\t\t\"KEY_0\": \"Abc\",\n\t\t\"KEY_1\": \"Def\",\n\t}\n\n\t// Set test data.\n\tos.Clearenv()\n\tfor key, value := range tests {\n\t\tif err := os.Setenv(key, value); err != nil {\n\t\t\tt.Error(err)\n\t\t}\n\t}\n\n\t// Test function.\n\tfor i, str := range Environ() {\n\t\ttmp := strings.Split(str, \"=\")\n\t\tkey, value := tmp[0], tmp[1]\n\t\tif v, ok := tests[key]; v != value || !ok {\n\t\t\tif !ok {\n\t\t\t\tt.Errorf(\"test %v. extra key`%v`\", i, key)\n\t\t\t} else {\n\t\t\t\tt.Errorf(\"test %v. expected `%v` but `%v`\", i, v, value)\n\t\t\t}\n\t\t}\n\t}\n}", "func injectWorkerPara(pod *v1.Pod, workerPara *WorkerPara, object CommonInterface) {\n\t// inject our predefined volumes/envs\n\tvolumeMounts, volumes := CreateVolumeMap(workerPara)\n\tenvs := CreateEnvVars(workerPara.env)\n\tpod.Spec.Volumes = append(pod.Spec.Volumes, volumes...)\n\tfor idx := range pod.Spec.Containers {\n\t\tpod.Spec.Containers[idx].Env = append(\n\t\t\tpod.Spec.Containers[idx].Env, envs...,\n\t\t)\n\t\tpod.Spec.Containers[idx].VolumeMounts = append(\n\t\t\tpod.Spec.Containers[idx].VolumeMounts, volumeMounts...,\n\t\t)\n\t}\n\n\t// inject our labels\n\tif pod.Labels == nil {\n\t\tpod.Labels = make(map[string]string)\n\t}\n\tfor k, v := range GenerateLabels(object) {\n\t\tpod.Labels[k] = v\n\t}\n\n\tpod.GenerateName = object.GetName() + \"-\" + strings.ToLower(workerPara.workerType) + \"-\"\n\n\tpod.Namespace = object.GetNamespace()\n\n\tif workerPara.hostNetwork {\n\t\t// FIXME\n\t\t// force to set hostnetwork\n\t\tpod.Spec.HostNetwork = true\n\t}\n\n\tif pod.Spec.RestartPolicy == \"\" {\n\t\tpod.Spec.RestartPolicy = workerPara.restartPolicy\n\t}\n}", "func AddToPodDefinitionMemory(pod *corev1.Pod, amountLimit, amountRequest, containerNumber int64) *corev1.Pod {\n\tif nil == pod.Spec.Containers[containerNumber].Resources.Limits {\n\t\tpod.Spec.Containers[containerNumber].Resources.Limits = make(map[corev1.ResourceName]resource.Quantity)\n\t}\n\n\tif nil == pod.Spec.Containers[containerNumber].Resources.Requests {\n\t\tpod.Spec.Containers[containerNumber].Resources.Requests = make(map[corev1.ResourceName]resource.Quantity)\n\t}\n\n\tpod.Spec.Containers[containerNumber].Resources.Limits[\"memory\"] = *resource.NewQuantity(amountLimit*1024*1024*1024, resource.BinarySI)\n\tpod.Spec.Containers[containerNumber].Resources.Requests[\"memory\"] = *resource.NewQuantity(amountRequest*1024*1024*1024, resource.BinarySI)\n\n\treturn pod\n}", "func (e *echo) Env(val string) *echo {\n\tvars := e.declareVars(val)\n\tfor k, v := range vars {\n\t\tif err := os.Setenv(k, v); err != nil {\n\t\t\te.shouldPanic(err.Error())\n\t\t} else {\n\t\t\tdelete(e.vars, k) // overwrite local var\n\t\t}\n\t}\n\treturn e\n}", "func SetEnvironment(envar string) {\n\tc.setEnvironment(envar)\n}", "func (gf *genericFramework) Env(key, value string) error {\n\tif gf.adam.Variables == nil {\n\t\tgf.adam.Variables = jsonutil.NewVariableMap(\"\", nil)\n\t}\n\tif _, ok := gf.adam.Variables.Get(key); ok {\n\t\treturn fmt.Errorf(\"%v has been defined\", key)\n\t}\n\tgf.adam.Variables.Set(key, jsonutil.NewStringVariable(key, value))\n\treturn nil\n}", "func Setenv(t testing.TB, name, val string) {\n\tNew(t).Setenv(name, val)\n}", "func (swagger *MgwSwagger) SetEnvVariables(apiHashValue string) {\n\tproductionEndpoints, sandboxEndpoints := retrieveEndpointsFromEnv(apiHashValue)\n\tif len(productionEndpoints) > 0 {\n\t\tlogger.LoggerOasparser.Infof(\"Applying production endpoints provided in env variables for API %v : %v\", swagger.title, swagger.version)\n\t\tswagger.productionEndpoints.EndpointPrefix = constants.ProdClustersConfigNamePrefix\n\t\tswagger.productionEndpoints.Endpoints = productionEndpoints\n\t\tswagger.productionEndpoints.EndpointType = constants.LoadBalance\n\n\t}\n\tif len(sandboxEndpoints) > 0 {\n\t\tlogger.LoggerOasparser.Infof(\"Applying sandbox endpoints provided in env variables for API %v : %v\", swagger.title, swagger.version)\n\t\tswagger.sandboxEndpoints.EndpointPrefix = constants.SandClustersConfigNamePrefix\n\t\tswagger.sandboxEndpoints.Endpoints = sandboxEndpoints\n\t\tswagger.sandboxEndpoints.EndpointType = constants.LoadBalance\n\t}\n\n\t// retrieving security credentials from environment variables\n\tif swagger.productionEndpoints != nil && swagger.productionEndpoints.SecurityConfig.Enabled {\n\t\tswagger.productionEndpoints.SecurityConfig = RetrieveEndpointBasicAuthCredentialsFromEnv(apiHashValue,\n\t\t\t\"prod\", swagger.productionEndpoints.SecurityConfig)\n\t}\n\tif swagger.sandboxEndpoints != nil && swagger.sandboxEndpoints.SecurityConfig.Enabled {\n\t\tswagger.sandboxEndpoints.SecurityConfig = RetrieveEndpointBasicAuthCredentialsFromEnv(apiHashValue, \"sand\",\n\t\t\tswagger.sandboxEndpoints.SecurityConfig)\n\t}\n}", "func (m *etcdMinion) setEnvironment(name string) error {\n\tlog.Printf(\"Setting environment to %s\\n\", name)\n\n\tif _, err := m.gitRepo.CheckoutDetached(name); err != nil {\n\t\treturn err\n\t}\n\n\thead, err := m.gitRepo.Head()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"Environment set to %s@%s\\n\", name, head)\n\n\treturn nil\n}", "func TestGetEnvAsInt64(t *testing.T) {\n for i := 0; i < len(testInt64s); i++ {\n // set environment variables\n if testInt64s[i].ShouldSet {\n os.Setenv(\n testInt64s[i].Key,\n testInt64s[i].Value,\n )\n }\n\n // get environment variables\n if v := GetEnvAsInt64(\n testInt64s[i].Key,\n testInt64s[i].Default,\n ); v != testInt64s[i].Expected {\n t.Errorf(\n \"ENV %s is %d; expected %d\",\n testInt64s[i].Key,\n v,\n testInt64s[i].Expected,\n )\n }\n }\n}", "func elasticSearchContainerSpec(cr *wp.WebProject) corev1.Container {\n\timage := \"elasticsearch:7.10.1\"\n\tcontainer := corev1.Container{\n\t\tImage: image,\n\t\tName: \"search\",\n\t\tPorts: []corev1.ContainerPort{\n\t\t\t{\n\t\t\t\tContainerPort: int32(9200),\n\t\t\t\tName: \"reset-port\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tContainerPort: int32(9300),\n\t\t\t\tName: \"intra-node-port\",\n\t\t\t},\n\t\t},\n\t\tLifecycle: &corev1.Lifecycle{\n\t\t\tPostStart: &corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t/*StartupProbe: &corev1.Probe{\n\t\t\tInitialDelaySeconds: 5,\n\t\t\tPeriodSeconds: 2,\n\t\t\tHandler: corev1.Handler{\n\t\t\t\tExec: &corev1.ExecAction{\n\t\t\t\t\tCommand: []string{\"sh\", \"-c\", \"chown -R 1000:1000 /usr/share/elasticsearch/data\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},*/\n\t\tEnv: []corev1.EnvVar{\n\t\t\t{\n\t\t\t\tName: \"discovery.type\",\n\t\t\t\tValue: \"single-node\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"ES_JAVA_OPTS\",\n\t\t\t\tValue: \"-Xms512m -Xmx512m\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAME\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.name\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_ID\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.uid\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"POD_NAMESPACE\",\n\t\t\t\tValueFrom: &corev1.EnvVarSource{\n\t\t\t\t\tFieldRef: &corev1.ObjectFieldSelector{\n\t\t\t\t\t\tFieldPath: \"metadata.namespace\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\n\t\tVolumeMounts: getElasticSearchVolumeMounts(cr),\n\n\t\tSecurityContext: &corev1.SecurityContext{\n\t\t\tAllowPrivilegeEscalation: createBool(false),\n\t\t\tReadOnlyRootFilesystem: createBool(false),\n\t\t\tRunAsNonRoot: createBool(false),\n\t\t},\n\t}\n\n\tif cr.Spec.SearchSidecar.CronJob.Enabled {\n\t\tcontainer.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{\n\t\t\tName: \"search-cron-script\",\n\t\t\tMountPath: \"/opt/script\",\n\t\t})\n\t}\n\n\treturn container\n}", "func setEnv(d interface{}) {\n\tVCAP := os.Getenv(\"VCAP_SERVICES\")\n\tif VCAP == \"\" {\n\t\treturn // no environment found so use whatever DBURL is set to\n\t}\n\tb := []byte(VCAP)\n\terr := json.Unmarshal(b, d) \n\tif err != nil {\n\t\tfmt.Printf(\"dbhandler:setEnv:ERROR:%s\", err)\n\t}\n}", "func (e *OverlayEnv) Setenv(key, value string) error {\n\t// do we have a stack?\n\tif e == nil {\n\t\treturn ErrNilPointer{\"OverlayEnv.Setenv\"}\n\t}\n\n\t// do we have any environments in the stack?\n\tif len(e.envs) == 0 {\n\t\treturn ErrEmptyOverlayEnv{\"OverlayEnv.Setenv\"}\n\t}\n\n\t// are we updating an existing variable?\n\tfor _, env := range e.envs {\n\t\t_, ok := env.LookupEnv(key)\n\t\tif ok {\n\t\t\treturn env.Setenv(key, value)\n\t\t}\n\t}\n\n\t// nope, it's a brand new variable\n\treturn e.envs[0].Setenv(key, value)\n}", "func RunE2ETests(t *testing.T) {\n\tlogs.InitLogs()\n\tdefer logs.FlushLogs()\n\n\tgomega.RegisterFailHandler(ginkgo.Fail)\n\t// Disable skipped tests unless they are explicitly requested.\n\tif config.GinkgoConfig.FocusString == \"\" && config.GinkgoConfig.SkipString == \"\" {\n\t\tconfig.GinkgoConfig.SkipString = `\\[Flaky\\]|\\[Feature:.+\\]`\n\t}\n\n\tglog.Infof(\"Installing cert-manager helm chart\")\n\tvar extraArgs []string\n\tif os.Getenv(\"DISABLE_WEBHOOK\") == \"true\" {\n\t\textraArgs = append(extraArgs, \"--set\", \"webhook.enabled=false\")\n\t}\n\tInstallHelmChart(t, releaseName, \"./contrib/charts/cert-manager\", certManagerDeploymentNamespace, \"./test/fixtures/cert-manager-values.yaml\", extraArgs...)\n\n\tglog.Infof(\"Installing pebble chart\")\n\t// 10 minute timeout for pebble install due to large images\n\textraArgs = []string{\"--timeout\", \"600\"}\n\tif framework.TestContext.PebbleImageRepo != \"\" {\n\t\textraArgs = append(extraArgs, \"--set\", \"image.repository=\"+framework.TestContext.PebbleImageRepo)\n\t}\n\tif framework.TestContext.PebbleImageTag != \"\" {\n\t\textraArgs = append(extraArgs, \"--set\", \"image.tag=\"+framework.TestContext.PebbleImageTag)\n\t}\n\tInstallHelmChart(t, \"pebble\", \"./contrib/charts/pebble\", \"pebble\", \"./test/fixtures/pebble-values.yaml\", extraArgs...)\n\n\tvaultExtraArgs := []string{\"--set\", \"vault.privateKey=\" + string(vault.VaultCertPrivateKey), \"--set\", \"vault.publicKey=\" + string(vault.VaultCert)}\n\tInstallHelmChart(t, \"vault\", \"./contrib/charts/vault\", \"vault\", \"./test/fixtures/vault-values.yaml\", vaultExtraArgs...)\n\n\tglog.Infof(\"Starting e2e run %q on Ginkgo node %d\", framework.RunId, config.GinkgoConfig.ParallelNode)\n\n\tvar r []ginkgo.Reporter\n\tif framework.TestContext.ReportDir != \"\" {\n\t\tr = append(r, reporters.NewJUnitReporter(path.Join(framework.TestContext.ReportDir, \"junit_00.xml\")))\n\t}\n\tif !ginkgo.RunSpecsWithDefaultAndCustomReporters(t, \"cert-manager e2e suite\", r) {\n\t\tPrintPodLogs(t)\n\t}\n}", "func (c *Cli) EnvUint64Var(p *uint64, name string, value uint64, usage string) error {\n\tc.env[name] = &EnvAttribute{\n\t\tName: name,\n\t\tType: fmt.Sprintf(\"%T\", value),\n\t\tUint64Value: value,\n\t\tUsage: usage,\n\t}\n\tp = &c.env[name].Uint64Value\n\t_, ok := c.env[name]\n\tif ok == false {\n\t\treturn fmt.Errorf(\"%q could not be added to environment attributes\", name)\n\t}\n\treturn nil\n}", "func NewEnv() (*Env, error) {\n\tctx := context.Background()\n\tdomainID := fmt.Sprintf(\"domain %d\", rand.Int()) // nolint: gas\n\tdb, err := testdb.New(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: failed to open database: %v\", err)\n\t}\n\n\t// Map server\n\tmapEnv, err := maptest.NewMapEnv(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: failed to create trillian map server: %v\", err)\n\t}\n\n\ttlog := fake.NewTrillianLogClient()\n\n\t// Configure domain, which creates new map and log trees.\n\tdomainStorage, err := domain.NewStorage(db)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: failed to create domain storage: %v\", err)\n\t}\n\tadminSvr := adminserver.New(tlog, mapEnv.Map, mapEnv.Admin, mapEnv.Admin, domainStorage, vrfKeyGen)\n\tdomainPB, err := adminSvr.CreateDomain(ctx, &pb.CreateDomainRequest{\n\t\tDomainId: domainID,\n\t\tMinInterval: ptypes.DurationProto(1 * time.Second),\n\t\tMaxInterval: ptypes.DurationProto(5 * time.Second),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: CreateDomain(): %v\", err)\n\t}\n\n\tmapID := domainPB.Map.TreeId\n\tlogID := domainPB.Log.TreeId\n\tmapPubKey, err := der.UnmarshalPublicKey(domainPB.Map.GetPublicKey().GetDer())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: Failed to load signing keypair: %v\", err)\n\t}\n\tvrfPub, err := p256.NewVRFVerifierFromRawKey(domainPB.Vrf.GetDer())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: Failed to load vrf pubkey: %v\", err)\n\t}\n\n\t// Common data structures.\n\tmutations, err := mutationstorage.New(db)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"env: Failed to create mutations object: %v\", err)\n\t}\n\tauth := authentication.NewFake()\n\tauthz := authorization.New()\n\n\tqueue := mutator.MutationQueue(mutations)\n\tserver := keyserver.New(tlog, mapEnv.Map, mapEnv.Admin, mapEnv.Admin,\n\t\tentry.New(), auth, authz, domainStorage, queue, mutations)\n\tgsvr := grpc.NewServer()\n\tpb.RegisterKeyTransparencyServer(gsvr, server)\n\n\t// Sequencer\n\tseq := sequencer.New(tlog, mapEnv.Map, entry.New(), domainStorage, mutations, queue)\n\t// Only sequence when explicitly asked with receiver.Flush()\n\td := &domaindef.Domain{\n\t\tDomainID: domainID,\n\t\tLogID: logID,\n\t\tMapID: mapID,\n\t}\n\treceiver := seq.NewReceiver(ctx, d, 60*time.Hour, 60*time.Hour)\n\treceiver.Flush(ctx)\n\n\taddr, lis, err := Listen()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tgo gsvr.Serve(lis)\n\n\t// Client\n\tcc, err := grpc.Dial(addr, grpc.WithInsecure())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Dial(%v) = %v\", addr, err)\n\t}\n\tktClient := pb.NewKeyTransparencyClient(cc)\n\tclient := grpcc.New(ktClient, domainID, vrfPub, mapPubKey, coniks.Default, fake.NewFakeTrillianLogVerifier())\n\tclient.RetryCount = 0\n\n\treturn &Env{\n\t\tEnv: &integration.Env{\n\t\t\tClient: client,\n\t\t\tCli: ktClient,\n\t\t\tDomain: domainPB,\n\t\t\tReceiver: receiver,\n\t\t},\n\t\tmapEnv: mapEnv,\n\t\tgrpcServer: gsvr,\n\t\tgrpcCC: cc,\n\t\tdb: db,\n\t}, nil\n}", "func (o VirtualDatabaseSpecBuildOutput) Env() VirtualDatabaseSpecBuildEnvArrayOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecBuild) []VirtualDatabaseSpecBuildEnv { return v.Env }).(VirtualDatabaseSpecBuildEnvArrayOutput)\n}", "func SetEnv(clusterID, namespace string) error {\n\tenv.ClusterID = clusterID\n\tenv.Namespace = namespace\n\n\tvar file *os.File\n\tvar err error\n\tfile, err = os.OpenFile(envPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)\n\tdefer func() {\n\t\t_ = file.Close()\n\t}()\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"set env error, open file error: %v\", err)\n\t}\n\n\tvar bEnv []byte\n\t_ = codec.EncJson(env, &bEnv)\n\n\t_, err = io.WriteString(file, string(bEnv))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"set env error, write file error: %v\", err)\n\t}\n\n\treturn nil\n}", "func (d *Docker) AddEnv(e Env) {\n\tfor k, v := range e {\n\t\td.AddArgs(\"-e\", fmt.Sprintf(\"%s=%s\", k, v))\n\t}\n}", "func (o VirtualDatabaseSpecOutput) Env() VirtualDatabaseSpecEnvArrayOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpec) []VirtualDatabaseSpecEnv { return v.Env }).(VirtualDatabaseSpecEnvArrayOutput)\n}", "func (b *addPushNotificationsOnChannelsBuilder) Environment(env PNPushEnvironment) *addPushNotificationsOnChannelsBuilder {\n\tb.opts.Environment = env\n\treturn b\n}", "func (env Environment) Add(otherenv Environment) {\n\tfor k, v := range otherenv {\n\t\tenv[k] = v\n\t}\n}", "func TestEnvironment_DashesInTaskName(t *testing.T) {\n\ta := mock.Alloc()\n\ttask := a.Job.TaskGroups[0].Tasks[0]\n\ttask.Env = map[string]string{\"test-one-two\": \"three-four\"}\n\tenvMap := NewBuilder(mock.Node(), a, task, \"global\").Build().Map()\n\n\tif envMap[\"test_one_two\"] != \"three-four\" {\n\t\tt.Fatalf(\"Expected test_one_two=three-four in TaskEnv; found:\\n%#v\", envMap)\n\t}\n}", "func (c *CmdReal) SetEnv(env []string) {\n\tc.cmd.Env = env\n}", "func updatePMM(c corev1.Container, with *api.PerconaXtraDBCluster) corev1.Container {\n\tpmm := with.Spec.PMM\n\n\tc.Image = pmm.Image\n\n\tfor k, v := range c.Env {\n\t\tswitch v.Name {\n\t\tcase \"PMM_SERVER\":\n\t\t\tc.Env[k].Value = pmm.ServerHost\n\t\tcase \"PMM_USER\":\n\t\t\tc.Env[k].Value = pmm.ServerUser\n\t\tcase \"PMM_PASSWORD\":\n\t\t\tc.Env[k].ValueFrom = &corev1.EnvVarSource{\n\t\t\t\tSecretKeyRef: app.SecretKeySelector(with.Spec.SecretsName, \"pmmserver\"),\n\t\t\t}\n\t\t}\n\t}\n\treturn c\n}", "func (l *Logger) SetEnvironmentFromString(env string) {\r\n\tenv = strings.ToLower(env)\r\n\tswitch env {\r\n\tcase \"dev\":\r\n\t\tl.SetEnvironment(EnvDevelopment)\r\n\tcase \"qa\":\r\n\t\tl.SetEnvironment(EnvQuality)\r\n\tdefault:\r\n\t\tl.SetEnvironment(EnvProduction)\r\n\t}\r\n}", "func generateRunEnvironment(options entities.ContainerRunlabelOptions) []string {\n\tnewEnv := os.Environ()\n\tif options.Optional1 != \"\" {\n\t\tnewEnv = append(newEnv, fmt.Sprintf(\"OPT1=%s\", options.Optional1))\n\t}\n\tif options.Optional2 != \"\" {\n\t\tnewEnv = append(newEnv, fmt.Sprintf(\"OPT2=%s\", options.Optional2))\n\t}\n\tif options.Optional3 != \"\" {\n\t\tnewEnv = append(newEnv, fmt.Sprintf(\"OPT3=%s\", options.Optional3))\n\t}\n\treturn newEnv\n}", "func (p *Resolver) SetProcessEnvs(pce *model.ProcessCacheEntry) {\n\tif entry, found := p.argsEnvsCache.Get(pce.EnvsID); found {\n\t\tif pce.EnvsTruncated {\n\t\t\tp.envsTruncated.Inc()\n\t\t}\n\n\t\tp.envsSize.Add(int64(len(entry.values)))\n\n\t\tpce.EnvsEntry = &model.EnvsEntry{\n\t\t\tValues: entry.values,\n\t\t\tTruncated: entry.truncated,\n\t\t}\n\n\t\t// no need to keep it in LRU now as attached to a process\n\t\tp.argsEnvsCache.Remove(pce.EnvsID)\n\t}\n}", "func (g *Generator) AddProcessEnv(env string) {\n\tg.initSpec()\n\tg.spec.Process.Env = append(g.spec.Process.Env, env)\n}" ]
[ "0.6530269", "0.6481485", "0.61398983", "0.5656439", "0.5338709", "0.5294525", "0.5229109", "0.51934814", "0.51809675", "0.51685995", "0.5168257", "0.5167598", "0.5120142", "0.5062491", "0.50438", "0.50193334", "0.501236", "0.49830508", "0.49722126", "0.49524188", "0.49515155", "0.4950439", "0.49477676", "0.49474782", "0.49439886", "0.49269816", "0.4899851", "0.48981145", "0.4897032", "0.48845735", "0.48663193", "0.4796618", "0.47849438", "0.47679937", "0.47623354", "0.4753025", "0.47389734", "0.47333276", "0.4722242", "0.47148162", "0.47044727", "0.47035947", "0.46986452", "0.4695053", "0.46825016", "0.4679151", "0.46747288", "0.4674015", "0.4673847", "0.46697274", "0.4668531", "0.46595195", "0.4656276", "0.46474284", "0.46418023", "0.46285382", "0.46166217", "0.45997968", "0.45906052", "0.45906052", "0.4588241", "0.45810404", "0.457207", "0.45669296", "0.45644066", "0.45462957", "0.45346838", "0.45154637", "0.45047653", "0.4502675", "0.45007563", "0.44908077", "0.44850463", "0.4479264", "0.44720575", "0.44699475", "0.4464246", "0.4464128", "0.44619963", "0.44429043", "0.4435439", "0.4418957", "0.4417928", "0.4409393", "0.44067422", "0.44067106", "0.4406488", "0.44046065", "0.44020697", "0.4400343", "0.43931141", "0.43892643", "0.43884337", "0.43865535", "0.43854186", "0.43804285", "0.4378407", "0.4376922", "0.43767083", "0.43766177" ]
0.87559414
0
Mount 2. the component loading html
func (l *LiveComponent) Mount(a *LiveTimeChannel) { l.Component.BeforeMount(l) l.IsMounted = true l.LifeTimeChannel = a l.Component.Mounted(l) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *D) Mount() {\n\tc.Start(js.Global.Get(\"document\").Get(\"body\").Get(\"firstElementChild\"))\n}", "func (c *ZeroContext) Mount(component Componer) {\n\tmarkup.Mount(component, c.ID())\n\tc.root = component\n}", "func defaultMount(ctx context.Context, c *Component, r *http.Request) error {\n\treturn nil\n}", "func Test_Ctx_Render_Mount(t *testing.T) {\n\tt.Parallel()\n\n\tsub := New(Config{\n\t\tViews: html.New(\"./.github/testdata/template\", \".gohtml\"),\n\t})\n\n\tsub.Get(\"/:name\", func(ctx *Ctx) error {\n\t\treturn ctx.Render(\"hello_world\", Map{\n\t\t\t\"Name\": ctx.Params(\"name\"),\n\t\t})\n\t})\n\n\tapp := New()\n\tapp.Mount(\"/hello\", sub)\n\n\tresp, err := app.Test(httptest.NewRequest(MethodGet, \"/hello/a\", http.NoBody))\n\tutils.AssertEqual(t, StatusOK, resp.StatusCode, \"Status code\")\n\tutils.AssertEqual(t, nil, err, \"app.Test(req)\")\n\n\tbody, err := io.ReadAll(resp.Body)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, \"<h1>Hello a!</h1>\", string(body))\n}", "func (h *Browser) Render() vecty.ComponentOrHTML {\n\treturn elem.InlineFrame(\n\t\tvecty.Markup(\n\t\t\tvecty.Class(\"help-browser\"),\n\t\t\tvecty.Property(\"src\", h.getCachedURL()),\n\t\t),\n\t)\n}", "func Render(comp Component, container *js.Object) {\n\tcomp.Reconcile(nil)\n\tcontainer.Call(\"appendChild\", comp.Node())\n}", "func (c *Body) Render() vecty.ComponentOrHTML {\n\treturn elem.Body(\n\t\trouter.NewRoute(\"/go/login\", &Login{}, router.NewRouteOpts{ExactMatch: true}),\n\t\trouter.NewRoute(\"/go/dashboard\", NewDashboard(\"/go/dashboard\"), router.NewRouteOpts{}),\n\t\trouter.NotFoundHandler(&NotFound{}),\n\t)\n}", "func (a *SDK) Render(domain string, dir string) {\n\tfs := http.FileServer(http.Dir(dir))\n\t//http.Handle(\"/preview/\", http.StripPrefix(\"/preview\", fs))\n\thttp.Handle(\"/\", http.StripPrefix(\"/\", fs))\n}", "func (e *Viewer) Mount(r chi.Router) {\n\tr.Get(\"/*\", e.serve)\n\tr.Get(\"/swagger.spec\", e.load)\n}", "func main() {\n\tcomponent := gr.New(new(userGists))\n\tcomponent.Render(\"react\", gr.Props{})\n}", "func (loader *VueLoader) load() []vueComponent {\n\tvar components []vueComponent\n\tfilepath.WalkDir(loader.Config.ComponentPath, func(path string, info fs.DirEntry, err error) error {\n\t\tdefer recover()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif !info.IsDir() && strings.ToLower(filepath.Ext(info.Name())) == \".vue\" {\n\t\t\tc := vueComponent{\n\t\t\t\tFileName: info.Name(),\n\t\t\t\tID: \"\",\n\t\t\t\tHtmlContent: \"\",\n\t\t\t\tScriptContent: \"\",\n\t\t\t\tStyleContent: \"\",\n\t\t\t}\n\t\t\tb, err := ioutil.ReadFile(path)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcontent, err := goquery.NewDocumentFromReader(bytes.NewReader(b))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\ttmpl := content.Find(\"template\").First()\n\t\t\tc.ID = tmpl.AttrOr(\"id\", info.Name())\n\t\t\tc.HtmlContent, _ = goquery.OuterHtml(tmpl)\n\t\t\tc.ScriptContent = content.Find(\"script\").First().Text()\n\t\t\t//there might be multiple style tags\n\t\t\tc.StyleContent = \"\"\n\t\t\tcontent.Find(\"style\").Each(func(i int, s *goquery.Selection) {\n\t\t\t\tstyle := s.Text()\n\t\t\t\t//TODO process scoped styles\n\t\t\t\tif style != \"\" {\n\t\t\t\t\tc.StyleContent += style + \"\\n\"\n\t\t\t\t}\n\t\t\t})\n\t\t\tcomponents = append(components, c)\n\t\t}\n\t\treturn nil\n\t})\n\treturn components\n}", "func (p *Home) Render() vecty.ComponentOrHTML {\n\treturn elem.Body(p.perspectiveList)\n}", "func (c *Context) Render(status int, name string, data interface{}) (err error) {\n\tif c.router.Renderer == nil {\n\t\treturn errors.New(\"renderer not registered\")\n\t}\n\n\tvar buf = new(bytes.Buffer)\n\tif err = c.router.Renderer.Render(buf, name, data, c); err != nil {\n\t\treturn err\n\t}\n\n\tc.HTML(status, buf.Bytes())\n\treturn\n}", "func (s *ServicesWidget) Mount() error {\n\ts.Lock()\n\tdefer s.Unlock()\n\tif s.mounted {\n\t\ts.align()\n\t\treturn nil\n\t}\n\ts.mounted = true\n\tvar rows []*ServiceRow\n\tif services, servicesInfo, err := getServiceInfo(s.swarmClient); err == nil {\n\t\tfor _, service := range services {\n\t\t\trows = append(rows, NewServiceRow(service, servicesInfo[service.ID], s.header))\n\t\t}\n\t}\n\ts.totalRows = rows\n\ts.align()\n\treturn nil\n}", "func RenderHome(response http.ResponseWriter, request *http.Request) {\n\thttp.ServeFile(response, request, \"views/index.html\")\n}", "func (loader *VueLoader) LoadVuePage(w io.Writer, pageTitle string, rootComponent string) {\n\tif loader.Config.CompileEveryRequest {\n\t\tif err := loader.compile(); err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn\n\t\t}\n\t}\n\terr := loader.layoutTemplate.Execute(w, vuePage{\n\t\tTitle: pageTitle,\n\t\tRootElement: template.HTML(rootComponent),\n\t\tScripts: template.HTML(loader.compiledScripts),\n\t\tStyles: template.HTML(loader.compiledStyles),\n\t\tTemplates: template.HTML(loader.compiledHTML),\n\t})\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func mount(e MountableResource, path string, handler MountHandler) {\n\thandler(e.Group(path))\n}", "func (c *Components) Render() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (r RSSWidgetForm) ComponentWillMount() {\n\tvar widget map[string]interface{}\n\n\tif r.Props().Interface(\"widget\") != nil {\n\t\twidgetJson := r.Props().Interface(\"widget\").([]byte)\n\t\tjson.Unmarshal(widgetJson, &widget)\n\t}\n\n\tr.SetState(widget)\n\tr.SetState(gr.State{\"querying\": true})\n\n\t// Get our options for the form\n\tgo func() {\n\t\tendpoint := \"//localhost:8081/api/\" + r.Props().String(\"apiType\") + \"/widgets/options\"\n\t\tresp, err := helpers.GetAPI(endpoint)\n\t\tif !r.IsMounted() {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\tr.SetState(gr.State{\"querying\": false, \"error\": fmt.Sprintf(\"Error while querying endpoint: %s\", endpoint)})\n\t\t\treturn\n\t\t}\n\n\t\tr.SetState(gr.State{\"widgetOptionsResp\": resp, \"querying\": false})\n\t}()\n}", "func (app *App) Render(parent *html.Element, viewport html.Rect) *html.Element {\n\tif len(app.Tag.Id) == 0 {\n\t\tapp.Tag.Id = \"app\"\n\t}\n\n\t// Create content container\n\tcontentEl := &html.Element{\n\t\tTag: \"v-content\",\n\t}\n\n\t// Add children items\n\tif app.Children != nil {\n\t\tcontentEl.Inner = app.Children.Layout(contentEl, viewport)\n\t}\n\n\t// Create application component\n\tappEl := &html.Element{\n\t\tTag: \"v-app\",\n\t\tId: app.Tag.Id + \"-cmp\",\n\t}\n\n\tapp.Appearance.Impose(appEl)\n\n\t// Make application layout\n\tif app.Toolbar.Top == nil && app.Toolbar.Bottom == nil {\n\t\tappEl.Inner = contentEl\n\t} else {\n\t\titems := make([]html.Markuper, 0, 3)\n\n\t\tif app.Toolbar.Top != nil {\n\t\t\ttbEl := app.Toolbar.Top.Render(appEl, viewport)\n\t\t\ttbEl.Attribute.Set(\"app\", true)\n\t\t\titems = append(items, tbEl)\n\t\t}\n\n\t\titems = append(items, contentEl)\n\n\t\tif app.Toolbar.Bottom != nil {\n\t\t\ttbEl := app.Toolbar.Bottom.Render(appEl, viewport)\n\t\t\ttbEl.Attribute.Set(\"app\", true)\n\t\t\titems = append(items, tbEl)\n\t\t}\n\n\t\tappEl.Inner = html.Multiple(items)\n\t}\n\n\t// Create application container element\n\tel := app.Tag.Element()\n\tel.Tag = \"div\"\n\tel.Inner = appEl\n\n\treturn el\n}", "func pageMount(title string) page.MountHandler {\n\treturn func(ctx context.Context, c *page.Component, r *http.Request) error {\n\t\t// Create a new page state.\n\t\tc.State = newPageState(title)\n\t\treturn nil\n\t}\n}", "func Render(c Compo) {\n\tUI(func() { render(c) })\n}", "func render(w http.ResponseWriter, tmpl string, context Context) {\n\ttmplList := []string{\"views/base.html\",\n\t\tfmt.Sprintf(\"views/%s.html\", tmpl)}\n\tt, err := template.ParseFiles(tmplList...)\n\tcheckErr(err)\n\tcheckErr(t.Execute(w, context))\n}", "func Render(bima *bima.Bima) {\n\th := NewHeaderComponent(bima)\n\tbima.UI.Header = h.Render()\n\tgo bima.Sync.Watch()\n\n\t// If never see onboard yet, we should show up onboard screen to enter email and setup password\n\tif bima.Registry.HasOnboard() {\n\t\tc := NewPasswordComponent(bima, EnterPasswordForm)\n\t\tbima.Push(\"unlock\", c)\n\t} else {\n\t\t// No secret key are created yet. We start onboard process so it also give user a chance to save this secret key\n\t\tlog.Debug().Msg(\"Start onboard\")\n\t\tc := NewOnboardComponent(bima)\n\t\tbima.Push(\"onboard\", c)\n\t}\n\n\tbima.UI.Window.Resize(fyne.NewSize(320, 640))\n\tbima.UI.Window.ShowAndRun()\n}", "func Render(c Compo) {\n\tdriver.CallOnUIGoroutine(func() {\n\t\tdriver.Render(c)\n\t})\n}", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func (g userGists) ComponentDidMount() {\n\tprintln(\"ComponentDidMount\")\n\n\tvar gists []gist\n\n\t// Note that ComponentDidMount is assumed to block, so no need to spin up a\n\t// goroutine for this.\n\tresp, err := http.Get(\"https://api.github.com/users/bradfitz/gists\")\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer resp.Body.Close()\n\n\terr = json.NewDecoder(resp.Body).Decode(&gists)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tg.SetState(gr.State{\"gists\": gists})\n}", "func (st *Stemplate) Render(w *http.ResponseWriter, templateName string) {\n\n\tif !st.LiveReload {\n\t\tst.templates[templateName].ExecuteTemplate(*w, \"base\", st.data)\n\t} else {\n\t\tst.loadTemplate(templateName).ExecuteTemplate(*w, \"base\", st.data)\n\t}\n\n}", "func render(w http.ResponseWriter, context PageContext) {\n\tfuncMap := template.FuncMap{\n\t\t\"title\": strings.Title,\n\t\t\"HumanizeBytes\": HumanizeBytes,\n\t\t\"HumanizeBigBytes\": HumanizeBigBytes,\n\t\t\"CommifyFloat\": CommifyFloat,\n\t\t\"Float2Int\": IntFromFloat64,\n\t\t\"OkToBool\": OkToBool,\n\t\t\"tableflip\": func() string { return \"(╯°□°)╯︵ ┻━┻\" },\n\t}\n\tcontext.Static = STATIC_URL\n\ttmpl_list := getTemplateList(context.ViewTemplate)\n\t/*\n\t\tt, err := template.ParseFiles(tmpl_list...)\n\t\tif err != nil {\n\t\t\tlog.Print(\"template parsing error: \", err)\n\t\t}\n\t*/\n\tt := template.Must(template.New(\"base.html\").Funcs(funcMap).ParseFiles(tmpl_list...))\n\terr := t.Execute(w, context)\n\tif err != nil {\n\t\tlog.Print(\"template executing error: \", err)\n\t}\n}", "func render(w http.ResponseWriter, tmpl string, p *page.Page) {\n\tif err := page.Templates.ExecuteTemplate(w, tmpl+\".html\", p); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\tlog.Println(err)\n\t}\n}", "func (a AutoscaleGroupClassForm) ComponentWillMount() {\n\tvar class map[string]interface{}\n\n\tif a.Props().Interface(\"class\") != nil {\n\t\tclassJson := a.Props().Interface(\"class\").([]byte)\n\t\tjson.Unmarshal(classJson, &class)\n\t}\n\n\ta.SetState(class)\n\ta.SetState(gr.State{\"querying\": true})\n\n\t// Get our options for the form\n\tgo func() {\n\t\tendpoint := \"//localhost:8081/api/classes/\" + a.Props().String(\"apiType\") + \"/options\"\n\t\tresp, err := helpers.GetAPI(endpoint)\n\t\tif !a.IsMounted() {\n\t\t\treturn\n\t\t}\n\t\tif err != nil {\n\t\t\ta.SetState(gr.State{\"querying\": false, \"error\": fmt.Sprintf(\"Error while querying endpoint: %s\", endpoint)})\n\t\t\treturn\n\t\t}\n\n\t\ta.SetState(gr.State{\"classOptionsResp\": resp, \"querying\": false})\n\t}()\n}", "func (w *Label) Mount(parent base.Control) (base.Element, error) {\n\t// Forward to the platform-dependant code\n\treturn w.mount(parent)\n}", "func startRenderer(ch <-chan request, configFile string) error {\n\tm, err := govecamole.New(256, 256)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// note: not deferring m.Close() here, as we want ownership passed to\n\t// the goroutine. this probably isn't the best way of doing this, so\n\t// TODO: figure out how to do this in a nicer way, perhaps on the\n\t// goroutine itself?\n\n\terr = m.LoadFile(configFile, true, configFile)\n\tif err != nil {\n\t\tm.Close()\n\t\treturn err\n\t}\n\n\tgo renderLoop(ch, m)\n\n\treturn nil\n}", "func init() {\n\tRegisterEngine(EngineTypeHTML, &htmlEngine{})\n}", "func HTML(opts ...ServerOption) {\n\tsrv, err := initServer(opts...)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\thttp.HandleFunc(\"/\", renderTemplate(srv))\n\n\tlog.Println(\"Listening on :3000...\")\n\terr = http.ListenAndServe(\":3000\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}", "func (m *modules) Render() vdom.Element {\n\tengineUI := dspUI.MakeEngine(&m.dspEngine, 1400-m.state.vDividerPos-4, m.state.hDividerPos, &m.state.dspUIEngineState)\n\tfilePickerUI := dspUI.MakeFilePicker(&m.dspEngine, m.state.vDividerPos, m.state.hDividerPos, &m.state.dspUIFilePickerState)\n\tvSplit := vdomcomp.MakeLayoutVSplit(1200, m.state.hDividerPos, m.state.vDividerPos, 4, &m.state.vDividerMoving,\n\t\tfilePickerUI,\n\t\tengineUI,\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.vDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\thSplit := vdomcomp.MakeLayoutHSplit(1400, 800, m.state.hDividerPos, 4, &m.state.hDividerMoving,\n\t\tvSplit, onscreenkeyboardUI.MakeKeyboard(&m.keyboard),\n\t\tfunc(pos int) {\n\t\t\tif pos > 100 {\n\t\t\t\tm.state.hDividerPos = pos\n\t\t\t}\n\t\t},\n\t)\n\n\telem := vdom.MakeElement(\"svg\",\n\t\t\"id\", \"root\",\n\t\t\"xmlns\", \"http://www.w3.org/2000/svg\",\n\t\t\"style\", \"width:100%;height:100%;position:fixed;top:0;left:0;bottom:0;right:0;\",\n\t\thSplit,\n\t)\n\n\treturn elem\n}", "func (h *htmlRender) Render(w io.Writer) error {\n\tif h.Template == nil {\n\t\treturn errors.New(\"template is nil\")\n\t}\n\n\tif h.Layout == \"\" {\n\t\treturn h.Template.Execute(w, h.ViewArgs)\n\t}\n\n\treturn h.Template.ExecuteTemplate(w, h.Layout, h.ViewArgs)\n}", "func main() {\n\tdomTarget := dom.GetWindow().Document().GetElementByID(\"app\")\n\n\tr.Render(container.Container(), domTarget)\n}", "func (app *application) render(res http.ResponseWriter, req *http.Request, pageName string, tmplData *Templates) {\n\ttmpl, ok := app.templateCache[pageName]\n\tif !ok {\n\t\tapp.serverError(res, fmt.Errorf(\"the page %s is not found\", pageName))\n\t\treturn\n\t}\n\n\tbuf := new(bytes.Buffer)\n\terr := tmpl.Execute(buf, app.addDefault(tmplData, req))\n\tif err != nil {\n\t\tapp.serverError(res, err)\n\t\treturn\n\t}\n\n\tbuf.WriteTo(res)\n}", "func LaunchHTML() {\n\thttp.Handle(\"/\", http.FileServer(http.Dir(\"./\")))\n\thttp.ListenAndServe(\":80\", nil)\n}", "func (r *renderer) Render(w http.ResponseWriter, p ViewModel) {\n\tif r.config.Debug {\n\t\terr := r.initTemplates()\n\t\tif err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n\terr := r.templates.ExecuteTemplate(w, templateName, p)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (t *Template) Render(ctx *gear.Context, w io.Writer, name string, data interface{}) (err error) {\n\tdir, _ := os.Getwd()\n\tname = filepath.Join(dir, \"view\", name+\".html\")\n\ttmpl := template.Must(template.ParseFiles(name))\n\n\terr = tmpl.Execute(w, data)\n\tif err != nil {\n\t\tlogging.Println(err)\n\t}\n\n\treturn\n}", "func (app *App) Mount(mg Moduler, mountbase string) {\n\tapp.Modules = append(app.Modules, mg)\n\tmg.SetMountPath(mountbase)\n\tmg.SetApp(app)\n\tmg.SetDataSrc(app.DataSrc)\n\terr := mg.Init(app)\n\tif err != nil {\n\t\tpanic(\"mount error at: \" + mountbase + \" error message is: \" + err.Error())\n\t}\n\tapp.Router.GET(mountbase+\"/meta\", mg.Meta)\n\n}", "func Widget(args ...interface{}) template.HTML {\n\tok := false\n\tvar s string\n\tif len(args) == 1 {\n\t\ts, ok = args[0].(string)\n\t}\n\tif !ok {\n\t\ts = fmt.Sprint(args...)\n\t}\n\n\ttplPath := GetUri(s, ConfigDir)\n\n\ttpl, _ok := beego.BeeTemplates[tplPath]\n\tif !_ok {\n\t\tbeego.Error(\"cont't found template: \", s)\n\t\treturn \"\"\n\t} else {\n\t\tvar out bytes.Buffer\n\t\ttpl.Execute(&out, nil)\n\t\tLoad(s, ConfigDir, false)\n\t\treturn template.HTML(out.String())\n\t}\n}", "func (h *HTTPHandler) Mount(g *echo.Group) {\n\tg.GET(\"/users\", h.FindAllUser)\n}", "func (ls *LightString) Render() {\n\tlog.Debug(\"Rendering string\")\n}", "func (w *Widget) Render(context *Context, file string) template.HTML {\n\tvar err error\n\tvar result = bytes.NewBufferString(\"\")\n\tif file == \"\" {\n\t\tfile = w.Templates[0]\n\t}\n\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"Get error when render file %v: %v\", file, r)\n\t\t\tutils.ExitWithMsg(err)\n\t\t}\n\t}()\n\n\tif file, err = w.findTemplate(file + \".tmpl\"); err == nil {\n\t\tif tmpl, err := template.New(filepath.Base(file)).ParseFiles(file); err == nil {\n\t\t\tif err = tmpl.Execute(result, context.Options); err == nil {\n\t\t\t\treturn template.HTML(result.String())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn template.HTML(err.Error())\n}", "func (f *Frontend) Render(w io.Writer, name string, data interface{}) error {\n\tfuncMap := template.FuncMap{\n\t\t\"githubUrl\": func(s string) string {\n\t\t\tr := strings.NewReplacer(\"https://\", \"\", \"http://\", \"\")\n\t\t\treturn r.Replace(s)\n\t\t},\n\t}\n\n\t// TODO: implement templates caching\n\ttmpl, err := template.New(name).Funcs(funcMap).ParseFiles(path.Join(f.cfg.TemplateFolder, \"layout.html\"), path.Join(f.cfg.TemplateFolder, name))\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Template reading error. Details: %s\", name, err.Error()))\n\t}\n\n\terr = tmpl.ExecuteTemplate(w, \"layout\", data)\n\tif err != nil {\n\t\treturn echo.NewHTTPError(http.StatusInternalServerError, fmt.Sprintf(\"Template rendering error. Details: %s\", name, err.Error()))\n\t}\n\n\treturn nil\n}", "func templatesLoginHtml() (*asset, error) {\n\tpath := filepath.Join(rootDir, \"templates/login.html\")\n\tname := \"templates/login.html\"\n\tbytes, err := bindataRead(path, name)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfi, err := os.Stat(path)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Error reading asset info %s at %s: %v\", name, path, err)\n\t}\n\n\ta := &asset{bytes: bytes, info: fi}\n\treturn a, err\n}", "func (ns *nodeServer) mount(sourcePath, targetPath string, mountOptions []string, rawBlock bool) error {\n\tnotMnt, err := ns.mounter.IsLikelyNotMountPoint(targetPath)\n\tif err != nil && !os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"failed to determain if '%s' is a valid mount point: %s\", targetPath, err.Error())\n\t}\n\tif !notMnt {\n\t\treturn nil\n\t}\n\n\t// Create target path, using a file for raw block bind mounts\n\t// or a directory for filesystems. Might already exist from a\n\t// previous call or because Kubernetes erroneously created it\n\t// for us.\n\tif rawBlock {\n\t\tf, err := os.OpenFile(targetPath, os.O_CREATE, os.FileMode(0644))\n\t\tif err == nil {\n\t\t\tdefer f.Close()\n\t\t} else if !os.IsExist(err) {\n\t\t\treturn fmt.Errorf(\"create target device file: %w\", err)\n\t\t}\n\t} else {\n\t\tif err := os.Mkdir(targetPath, os.FileMode(0755)); err != nil && !os.IsExist(err) {\n\t\t\treturn fmt.Errorf(\"create target directory: %w\", err)\n\t\t}\n\t}\n\n\t// We supposed to use \"mount\" package - ns.mounter.Mount()\n\t// but it seems not supporting -c \"canonical\" option, so do it with exec()\n\t// added -c makes canonical mount, resulting in mounted path matching what LV thinks is lvpath.\n\targs := []string{\"-c\"}\n\tif len(mountOptions) != 0 {\n\t\targs = append(args, \"-o\", strings.Join(mountOptions, \",\"))\n\t}\n\n\targs = append(args, sourcePath, targetPath)\n\tif _, err := pmemexec.RunCommand(\"mount\", args...); err != nil {\n\t\treturn fmt.Errorf(\"mount filesystem failed: %s\", err.Error())\n\t}\n\n\treturn nil\n}", "func (r *ServerWrapperRender) Render(path string, data *gengokit.Data) (io.Reader, error) {\n\tif path != ServerWrapperPath {\n\t\treturn nil, errors.Errorf(\"cannot render unknown file: %q\", path)\n\t}\n\tif r.prev != nil {\n\t\treturn r.prev, nil\n\t}\n\treturn data.ApplyTemplateFromPath(path)\n}", "func (c *cartridge) Render() {\n\tc.Cls()\n\tc.PrintAt(fmt.Sprintf(\"counter:%d\", c.counter), c.x, c.y)\n}", "func (g userGists) Render() gr.Component {\n\n\telem := el.Div()\n\n\tif s := g.State().Interface(\"gists\"); s != nil {\n\t\t// The nice Gist type is lost once we entered the JavaScript world.\n\t\t//\n\t\t// What we get now is:\n\t\t//\n\t\t// []interface{} with the individual Gists as map[string]interface{}\n\t\t//\n\t\t// Let that serve as a note to self that this may not be the optimal way.\n\t\t// I imagine most of the UI will happen in JavaScript and the business logic\n\t\t// and here in Go \"all\" the orchestration, including injecting data required\n\t\t// by the components.\n\t\tgists := s.([]interface{})\n\n\t\ttable := el.Table(\n\t\t\tgr.CSS(\"table\", \"table-striped\"),\n\t\t\tgr.Style(\"width\", \"50%\"),\n\t\t\tel.TableHead(el.TableRow(\n\t\t\t\tel.TableHeader(gr.Text(\"Description\")),\n\t\t\t\tel.TableHeader(gr.Text(\"URL\")),\n\t\t\t)))\n\n\t\tbody := el.TableBody()\n\n\t\tfor _, g := range gists {\n\t\t\ttr := tableRow(g)\n\t\t\ttr.Modify(body)\n\t\t}\n\n\t\t// TODO(bep) \"body modifies table\" doesn't sound right/good. Rename ...\n\t\tbody.Modify(table)\n\t\ttable.Modify(elem)\n\t}\n\n\treturn examples.Example(\"Ajax (some random Gists)\", elem)\n\n}", "func Mount(router *mux.Router) {\n\n}", "func render(src string, dst string) {\n\tdefer wg.Done()\n\tmd, err := ioutil.ReadFile(src)\n\tif err != nil {\n\t\tprintErr(err)\n\t\treturn\n\t}\n\thtml := renderHtml(md)\n\tif stylefile != \"\" {\n\t\thtml = addStyle(html, stylecont)\n\t} else {\n\t\thtml = addStyle(html, CSS)\n\t}\n\n\terr = ioutil.WriteFile(dst, []byte(html), 0644)\n\tif err != nil {\n\t\tprintErr(err)\n\t}\n}", "func index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tasset, err := Asset(\"static/templates/index.html\")\n\tif err != nil {\n\t\tlog.Panic(\"Unable to read file from bindata: \", err)\n\t}\n\tfmt.Fprint(w, string(asset))\n}", "func renderTemplate(w http.ResponseWriter, p *models.Page) {\n\tlp := path.Join(\"views\", \"log.html\")\n\ttmpl, err := template.ParseFiles(lp)\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\n\ttmpl.ExecuteTemplate(w, \"log.html\", p)\n}", "func (ui *GUI) route() {\n\tui.router = mux.NewRouter()\n\tui.router.Use(csrf.Protect(ui.cfg.CSRFSecret, csrf.Secure(true)))\n\n\tcssDir := http.Dir(filepath.Join(ui.cfg.GUIDir, \"public/css\"))\n\tui.router.PathPrefix(\"/css/\").Handler(http.StripPrefix(\"/css/\",\n\t\thttp.FileServer(cssDir)))\n\n\timagesDir := http.Dir(filepath.Join(ui.cfg.GUIDir, \"public/images\"))\n\tui.router.PathPrefix(\"/images/\").Handler(http.StripPrefix(\"/images/\",\n\t\thttp.FileServer(imagesDir)))\n\n\tui.router.HandleFunc(\"/\", ui.GetIndex).Methods(\"GET\")\n\tui.router.HandleFunc(\"/admin\", ui.GetAdmin).Methods(\"GET\")\n\tui.router.HandleFunc(\"/admin\", ui.PostAdmin).Methods(\"POST\")\n\tui.router.HandleFunc(\"/backup\", ui.PostBackup).Methods(\"POST\")\n\tui.router.HandleFunc(\"/logout\", ui.PostLogout).Methods(\"POST\")\n}", "func (t Tmpl) RenderWidget(req *http.Request, name string, args map[string]interface{}) (*bytes.Buffer, error) {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Create new template\n\t\tt = NewTemplate(\"widget\")\n\n\t\t// Set template FuncMap\n\t\tt.Tmpl.Funcs(FuncMap)\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"widgets/\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Reload extension templates\n\t\tif err := t.LoadExtensionTemplates(\"widgets\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Get csrf token\n\ttkn, ok := req.Context().Value(\"csrf-token\").(*models.CsrfToken)\n\tif !ok {\n\t\treturn nil, errors.New(\"Cannot get CSRF token\")\n\t}\n\n\t// Get nonce value\n\tnonce, ok := req.Context().Value(\"nonce\").(string)\n\n\tif !ok {\n\t\treturn nil, errors.New(\"Cannot get nonce value\")\n\t}\n\n\t// Get session map\n\tsession, ok := req.Context().Value(\"session\").(map[string]interface{})\n\n\tif !ok {\n\t\treturn nil, errors.New(\"Cannot get session value\")\n\t}\n\n\t// Set session value\n\targs[\"session\"] = session\n\n\t// Set nonce value\n\targs[\"nonce\"] = nonce\n\n\t// Set token value\n\targs[\"csrfToken\"] = tkn.Token\n\n\t// Data holder\n\tbuff := &bytes.Buffer{}\n\n\t// Render template to buffer\n\tif err := t.Tmpl.ExecuteTemplate(buff, name, args); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buff, nil\n}", "func Load() *template.Template {\n\treturn template.Must(\n\t\ttemplate.New(\n\t\t\t\"index.html\",\n\t\t).Parse(\n\t\t\tstring(MustAsset(\"index.html\")),\n\t\t),\n\t)\n}", "func UI(build string, shutdown chan os.Signal, log *log.Logger, dgraph data.Dgraph, browserEndpoint string, mapsKey string) (*web.App, error) {\n\tapp := web.NewApp(shutdown, mid.Logger(log), mid.Errors(log), mid.Metrics(), mid.Panics(log))\n\n\t// Register the index page for the website.\n\tindex, err := newIndex(dgraph, browserEndpoint, cities, mapsKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"loading index template\")\n\t}\n\tapp.Handle(\"GET\", \"/\", index.handler)\n\n\t// Register the assets.\n\tfs := http.FileServer(http.Dir(\"assets\"))\n\tfs = http.StripPrefix(\"/assets/\", fs)\n\tf := func(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\t\tfs.ServeHTTP(w, r)\n\t\treturn nil\n\t}\n\tapp.Handle(\"GET\", \"/assets/*\", f)\n\n\t// Register health check endpoint.\n\tcheck := check{\n\t\tbuild: build,\n\t\tdgraph: dgraph,\n\t}\n\tapp.Handle(http.MethodGet, \"/health\", check.health)\n\n\t// Register data load endpoint.\n\tfetch := fetch{\n\t\tdgraph: dgraph,\n\t}\n\tapp.Handle(\"GET\", \"/data/:city\", fetch.data)\n\n\treturn app, nil\n}", "func (w *ServiceWrapperRender) Render(path string, data *gengokit.Data) (io.Reader, error) {\n\tif path != ServiceWrapperPath {\n\t\treturn nil, errors.Errorf(\"cannot render unknown file: %q\", path)\n\t}\n\tif w.prev != nil {\n\t\treturn w.prev, nil\n\t}\n\treturn data.ApplyTemplateFromPath(path)\n}", "func (c *Context) Render(content string) {\n\t// Write response\n\tc.Response.Write([]byte(content))\n}", "func (hr *GinRendererS) Instance(name string, data interface{}) render.Render {\n\tif simplateViewPathTemplates[name] == nil {\n\t\tsugar.Warnf(\"no template of name: %s\", name)\n\t}\n\n\tlayoutFile := defaultLayoutFile\n\n\t// body\n\tvar buf bytes.Buffer\n\tExecuteViewPathTemplate(&buf, name, data)\n\tdataT := make(gin.H)\n\tdataMap, ok := data.(gin.H)\n\tif ok {\n\t\tdataMap[\"LayoutContent\"] = template.HTML(buf.String())\n\t\tdataT = dataMap\n\t\t// custom layout\n\t\tif layout, ok := dataMap[\"layout\"]; ok {\n\t\t\tlayoutFile = layout.(string)\n\t\t}\n\t} else {\n\t\tdataT[\"LayoutContent\"] = template.HTML(buf.String())\n\t}\n\treturn render.HTML{\n\t\tTemplate: simplateViewPathTemplates[layoutFile],\n\t\tData: dataT,\n\t}\n}", "func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n p, _ := loadPage(\"/src/github.com/mrgirlyman/watcher/frontman/build/index.html\")\n\n fmt.Fprintf(w, string(p.Body))\n // log.Fatal(err)\n\n // if (err != nil) {\n // fmt.Fprintf(w, string(p.Body))\n // } else {\n // fmt.Fprintf(w, \"Error reading index.html\")\n // }\n}", "func (w *Window) Start() error {\n\tnewui, err := lorca.New(\"data:text/html,\"+url.PathEscape(fmt.Sprintf(\"%s\", w)), w.ProfileDir, w.Width, w.Height, w.Args...)\n\tif err != nil {\n\t\treturn err\n\t}\n\tw.ui = newui\n\n\tw.BindChildren(nil)\n\n\t//Apply Bindings\n\tfor _, bound := range w.Bindings {\n\t\terr = newui.Bind(bound.FunctionName, bound.BoundFunction)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (rd *FileDirsResponse) Render(w http.ResponseWriter, r *http.Request) error {\n\t// Pre-processing before a response is marshalled and sent across the wire\n\treturn nil\n}", "func render(ctx Config, com Component, gfx *dot.Graph) *dot.Node {\n\n\timg := iconPath(ctx, com)\n\n\tif fc := strings.TrimSpace(com.FontColor); len(fc) == 0 {\n\t\tcom.FontColor = \"#000000ff\"\n\t}\n\n\tif imp := strings.TrimSpace(com.Impl); len(imp) == 0 {\n\t\tcom.Impl = \"&nbsp;\"\n\t}\n\n\tvar sb strings.Builder\n\tsb.WriteString(`<table border=\"0\" cellborder=\"0\">`)\n\tif ctx.showImpl {\n\t\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"8\">%s</font></td></tr>`, com.Impl)\n\t}\n\n\tsb.WriteString(\"<tr>\")\n\tfmt.Fprintf(&sb, `<td fixedsize=\"true\" width=\"50\" height=\"50\"><img src=\"%s\" /></td>`, img)\n\tsb.WriteString(\"</tr>\")\n\n\tlabel := \"&nbsp;\"\n\tif s := strings.TrimSpace(com.Label); len(s) > 0 {\n\t\tlabel = s\n\t}\n\tfmt.Fprintf(&sb, `<tr><td><font point-size=\"7\">%s</font></td></tr>`, label)\n\tsb.WriteString(\"</table>\")\n\n\treturn node.New(gfx, com.ID,\n\t\tnode.Label(sb.String(), true),\n\t\tnode.FillColor(\"transparent\"),\n\t\tnode.Shape(\"plain\"),\n\t)\n}", "func (service *LoanSrvc) Mount(ctx context.Context, mux goahttp.Muxer) goahttp.Server {\n\tendpoints := loan.NewEndpoints(service)\n\tsrv := server.New(endpoints, mux, goahttp.RequestDecoder, goahttp.ResponseEncoder, api.ErrorHandler, nil)\n\tserver.Mount(mux, srv)\n\n\tfor _, m := range srv.Mounts {\n\t\tlog.WithContext(ctx).Infof(\"%q mounted on %s %s\", m.Method, m.Verb, m.Pattern)\n\t}\n\treturn srv\n}", "func Start(data, port string, wg *sync.WaitGroup) error {\n\tdefer wg.Done()\n\tstatikFS, err := fs.New()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstrHTML, err := getHTMLContent(statikFS, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\thttp.Handle(\"/_nuxt/\", http.FileServer(statikFS))\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\tfmt.Fprintf(w, strHTML)\n\t})\n\tif err := printHelpMsg(port); err != nil {\n\t\treturn err\n\t}\n\tif err := http.ListenAndServe(\":\"+port, nil); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n\n}", "func Home(w http.ResponseWriter, r *http.Request) { // Grab the span from the gorilla context. We do this so that we can grab\n\t// the span.Trace ID and link directly to the trace on the web-page itself!\n\tspan := context.Get(r, CtxSpanID).(appdash.SpanID)\n\n\t// We're going to make some API requests, so we create a HTTP client using\n\t// a appdash/httptrace transport here. The transport will inform Appdash of\n\t// the HTTP events occuring.\n\thttpClient := &http.Client{\n\t\tTransport: &httptrace.Transport{\n\t\t\tRecorder: appdash.NewRecorder(span, collector),\n\t\t\tSetName: true,\n\t\t},\n\t}\n\n\t// Make three API requests using our HTTP client.\n\tfor i := 0; i < 3; i++ {\n\t\tresp, err := httpClient.Get(\"/endpoint\")\n\t\tif err != nil {\n\t\t\tlog.Println(\"/endpoint:\", err)\n\t\t\tcontinue\n\t\t}\n\t\tresp.Body.Close()\n\t}\n\n\t// Render the page.\n\tfmt.Fprintf(w, `<!DOCTYPE html>\n\t\t\t\t\t\t\t\t\t\t<html>\n\t\t\t\t\t\t\t\t\t\t<head>\n\n\t\t\t\t\t\t\t\t\t\t <!-- Basic Page Needs\n\t\t\t\t\t\t\t\t\t\t –––––––––––––––––––––––––––––––––––––––––––––––––– -->\n\t\t\t\t\t\t\t\t\t\t <meta charset=\"utf-8\">\n\t\t\t\t\t\t\t\t\t\t <title>Test load</title>\n\t\t\t\t\t\t\t\t\t\t <meta name=\"description\" content=\"\">\n\t\t\t\t\t\t\t\t\t\t <meta name=\"author\" content=\"\">\n\n\t\t\t\t\t\t\t\t\t\t <!-- Mobile Specific Metas\n\t\t\t\t\t\t\t\t\t\t –––––––––––––––––––––––––––––––––––––––––––––––––– -->\n\t\t\t\t\t\t\t\t\t\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t\t\t\t\t\t\t\t\t\t<link href=\"https://bedbathandbeyond.qa.nrdecor.com/js/lib/jqwidgets/styles/jqx.base.css\" rel=\"stylesheet\" type=\"text/css\" id=\"jqw-styles\">\n\t\t\t\t\t\t\t\t\t\t<link href=\"https://bedbathandbeyond.qa.nrdecor.com/js/lib/jqwidgets/styles/jqx.office.css\" rel=\"stylesheet\" type=\"text/css\" id=\"jqw-styles\">\n\t\t\t\t\t\t\t\t\t\t<link href=\"https://bedbathandbeyond.qa.nrdecor.com/js/lib/justified-gallery/styles/justifiedGallery.css\" type=\"text/css\" rel=\"stylesheet\" >\n\n\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/enterprise/default/css/styles.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/enterprise/default/css/widgets.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/bbb2/common/css/common.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/bbb2/common/css/jquery-ui-1.9.2.custom.min.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/bbb2/web/css/web.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/bbb2/web/css/fonts.css\" media=\"all\" />\n\t\t\t\t\t\t\t\t\t\t<link rel=\"stylesheet\" type=\"text/css\" href=\"https://bedbathandbeyond.qa.nrdecor.com/skin/frontend/enterprise/default/css/print.css\" media=\"print\" />\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/prototype/prototype.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/lib/ccard.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/prototype/validation.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/scriptaculous/builder.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/scriptaculous/effects.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/scriptaculous/dragdrop.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/scriptaculous/controls.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/scriptaculous/slider.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/varien/js.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/varien/form.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/varien/menu.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\" src=\"https://bedbathandbeyond.qa.nrdecor.com/js/mage/translate.js\"></script>\n\t\t\t\t\t\t\t\t\t\t<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js\"></script>\n\n\t\t\t\t\t\t\t\t\t\t <!-- Scripts\n\t\t\t\t\t\t\t\t\t\t –––––––––––––––––––––––––––––––––––––––––––––––––– -->\n\n\t\t\t\t\t\t\t\t\t\t<script type=\"text/javascript\">\n\t\t\t\t\t\t\t\t\t\t $(document).ready(function () {\n\t\t\t\t\t\t\t\t\t\t console.log(window.performance)//.getEntries())\n\t\t\t\t\t\t\t\t\t\t var arr = window.performance.getEntriesByType(\"resource\")\n\t\t\t\t\t\t\t\t\t\t jsonObj = [];\n\t\t\t\t\t\t\t\t\t\t console.log(jsonObj);\n\t\t\t\t\t\t\t\t\t\t $.each( arr, function( i, val ) {\n\t\t\t\t\t\t\t\t\t\t var name = val.name;\n\t\t\t\t\t\t\t\t\t\t var entryType = val.entryType;\n\t\t\t\t\t\t\t\t\t\t var startTime = val.fetchStart;\n\t\t\t\t\t\t\t\t\t\t var endTime = val.duration;\n\t\t\t\t\t\t\t\t\t\t var initiatorType = val.initiatorType;\n\n\t\t\t\t\t\t\t\t\t\t item = {}\n\t\t\t\t\t\t\t\t\t\t item [\"name\"] = name;\n\t\t\t\t\t\t\t\t\t\t item [\"entryType\"] = entryType;\n\t\t\t\t\t\t\t\t\t\t item [\"startTime\"] = startTime;\n\t\t\t\t\t\t\t\t\t\t item [\"endTime\"] = endTime;\n\t\t\t\t\t\t\t\t\t\t item [\"initiatorType\"] = initiatorType;\n\n\t\t\t\t\t\t\t\t\t\t jsonObj.push(item);\n\t\t\t\t\t\t\t\t\t\t });\n\t\t\t\t\t\t\t\t\t\t jsonString = JSON.stringify(jsonObj);\n\t\t\t\t\t\t\t\t\t\t console.log(jsonString);\n\t\t\t\t\t\t\t\t\t\t $.ajax({\n\t\t\t\t\t\t\t\t\t\t type: \"POST\",\n\t\t\t\t\t\t\t\t\t\t url: \"http://192.168.70.1:8699/endpoint\",\n\t\t\t\t\t\t\t\t\t\t data: jsonString\n\t\t\t\t\t\t\t\t\t\t // success: success,\n\t\t\t\t\t\t\t\t\t\t // dataType: dataType\n\t\t\t\t\t\t\t\t\t\t });\n\t\t\t\t\t\t\t\t\t\t });\n\t\t\t\t\t\t\t\t\t\t </script>\n\t\t\t\t\t\t\t\t\t\t</head>\n\t\t\t\t\t\t\t\t\t\t<body>\n\t\t\t\t\t\t\t\t\t\t<!-- Primary Page Layout\n\t\t\t\t\t\t\t\t\t\t –––––––––––––––––––––––––––––––––––––––––––––––––– -->\n\t\t\t\t\t\t\t\t\t\t <img id=\"image0\" src=\"http://flex.madebymufffin.com/images/inacup_donut.jpg\" alt=\"Smiley face\" height=\"42\" width=\"42\">\n\t\t\t\t\t\t\t\t\t\t<!-- End Document\n\t\t\t\t\t\t\t\t\t\t –––––––––––––––––––––––––––––––––––––––––––––––––– -->\n\t\t\t\t\t\t\t\t\t\t</body>\n\t\t\t\t\t\t\t\t\t\t</html>\n\t\t\t\t\t\t\t\t\t`)\n\tfmt.Fprintf(w, `<p><a href=\"http://localhost:8700/traces\" target=\"_\">View all traces</a></p>`)\n}", "func loveMountains(w http.ResponseWriter, r *http.Request) {\n\t// Build path to template\n\ttmplPath := filepath.Join(templatesDir, \"love-mountains.html\")\n\t// Load template from disk\n\ttmpl := template.Must(template.ParseFiles(tmplPath))\n\t// Inject data into template\n\tdata := \"Cadallac Mountain\"\n\ttmpl.Execute(w, data)\n}", "func (win *winInfo) displayLoading() {\n\ttexture, _ := win.renderText(\"Loading...\")\n\tww, wh := win.window.GetSize()\n\twin.renderer.Copy(texture, nil, &sdl.Rect{X: int32(ww/2 - 50), Y: int32(wh/2 - 1), W: 65, H: 20})\n\ttexture.Destroy()\n\twin.renderer.Present()\n}", "func (m *Markdown) Render() vecty.ComponentOrHTML {\n\t// Render the markdown input into HTML using Goldmark.\n\tvar buf bytes.Buffer\n\tif err := goldmark.Convert([]byte(m.Input), &buf); err != nil {\n\t\tpanic(err)\n\t}\n\t// The goldmark README says:\n\t// \"By default, goldmark does not render raw HTML or potentially dangerous links. \"\n\t// So, it should be ok without sanitizing.\n\n\t// Return the HTML.\n\treturn elem.Div(\n\t\tvecty.Markup(\n\t\t\tvecty.UnsafeHTML(buf.String()),\n\t\t),\n\t)\n}", "func init_html(srvaddr string) {\n\n\tsrvaddr = strings.ToLower(srvaddr)\n\n\tif !strings.HasPrefix(srvaddr, \"http://\") {\n\t\tsrvaddr = \"http://\" + srvaddr\n\t}\n\n\tif !strings.HasSuffix(srvaddr, \"/\") {\n\t\tsrvaddr = srvaddr + \"/\"\n\t}\n\n\tDOCHTML = bytes.ReplaceAll(DOCHTML, []byte(\"$$srvaddr$$\"), []byte(srvaddr))\n\tDOCHTML = bytes.ReplaceAll(DOCHTML, []byte(\"$$version$$\"), []byte(VERSION))\n}", "func loadTemplate() {\n\tif _, err := os.Stat(indexPath); err == nil {\n\t\tif homeTemplate, err = template.New(\"index.html\").ParseFiles(indexPath); err != nil {\n\t\t\tlog.Errorf(\"Unable to parse template %s: %+v\", indexPath, err)\n\t\t}\n\t\tlog.Infof(\"Running with production template...\")\n\t\treturn\n\t}\n\tlog.Infof(\"Running in dev mode...\")\n\tdevMode = true\n}", "func (h *todoHTTPHandler) Mount(group *echo.Group) {\n group.POST(\"\", h.CreateTodo)\n group.GET(\"\", h.GetAllTodo)\n group.GET(\"/:id\", h.GetTodo)\n group.PUT(\"/:id\", h.UpdateTodo)\n group.DELETE(\"/:id\", h.DeleteTodo)\n group.PUT(\"/status/:id\", h.UpdateStatusTodo)\n}", "func (m *Mosaic) Render() error {\n\tif err := m.target.Load(); err != nil {\n\t\treturn err\n\t}\n\tif err := m.tiles.Load(); err != nil {\n\t\treturn err\n\t}\n\tm.out = m.generate()\n\treturn nil\n}", "func (d *DeploymentComponent) Render(is *v1alpha2.InstallSpec) (string, error) {\n\td.waitDeps()\n\tglobalValues, err := getHelmValues(d.helmChartBaseDirPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsubchartDirPath := filepath.Join(d.helmChartBaseDirPath, d.relativeChartPath, d.componentName)\n\tchart, err := chartutil.Load(subchartDirPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalues := globalValues\n\tif filepath.Clean(d.helmChartBaseDirPath) != filepath.Clean(subchartDirPath) {\n\t\tvar err error\n\t\tvalues, err = getHelmValues(subchartDirPath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvalues, err = patchValues(bytes.Join([][]byte{globalValues, values}, nil), is)\n\t}\n\t//\tlog.Infof(\"values: \\n%s\\n\", values)\n\n\tlog.Infof(\"Rendering %s\", subchartDirPath)\n\tbaseYAML, err := helm.renderChart(d.namespace, string(values), chart)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn baseYAML, err\n}", "func (s *Server) render(w http.ResponseWriter, r *http.Request, templateName string, ctx pongo2.Context) {\n\tt, err := pongo2.FromFile(path.Join(s.templateDir, templateName))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tctx[\"request\"] = r\n\tctx[\"alerts\"] = s.getAlerts(w, r)\n\tctx[\"current_user\"] = context.Get(r, contextCurrentUser).(*db.User)\n\tctx[\"site_title\"] = s.config.GetString(configSiteTitle)\n\tb, err := t.ExecuteBytes(ctx)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(b)\n}", "func (t *Text) Render() vecty.ComponentOrHTML {\n\treturn elem.Heading1(\n\t\tvecty.Text(\"scnace's Homepage - With The GEEKER Heart Forever.\"),\n\t)\n}", "func (t Tmpl) RenderWidget(req *http.Request, name string, args map[string]interface{}) (*bytes.Buffer, error) {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Create new template\n\t\tt = NewTemplate(\"widget\")\n\n\t\t// Set template FuncMap\n\t\tt.Tmpl.Funcs(FuncMap)\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"widgets/\"); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Get csrf token\n\ttkn, ok := req.Context().Value(\"csrf-token\").(*models.CsrfToken)\n\tif !ok {\n\t\treturn nil, errors.New(\"Cannot get CSRF token\")\n\t}\n\n\t// Get nonce value\n\tnonce, ok := req.Context().Value(\"nonce\").(string)\n\n\tif !ok {\n\t\treturn nil, errors.New(\"Cannot get nonce value\")\n\t}\n\n\t// Set nonce value\n\targs[\"nonce\"] = nonce\n\n\t// Set token value\n\targs[\"csrfToken\"] = tkn.Token\n\n\t// Data holder\n\tbuff := &bytes.Buffer{}\n\n\t// Render template to buffer\n\tif err := t.Tmpl.ExecuteTemplate(buff, name, args); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buff, nil\n}", "func (p *PageView) Render() vecty.ComponentOrHTML {\n\treturn elem.Body(\n\t\telem.Header(\n\t\t\tvecty.Property(\"class\", \"header\"),\n\t\t\tvecty.Text(\"json2struct playground\"),\n\t\t),\n\t\telem.Div(\n\t\t\tvecty.Property(\"class\", \"wrapper\"),\n\t\t\telem.Div(\n\t\t\t\tvecty.Property(\"class\", \"col input\"),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"input json\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.TextArea(\n\t\t\t\t\t\tvecty.Property(\"class\", \"u-full-width\"),\n\t\t\t\t\t\tvecty.Text(p.Input),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Input = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.StructName),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.StructName = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct prefix name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.Prefix),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Prefix = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct suffix name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.Suffix),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Suffix = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"omitempty mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseOmitempty),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseOmitempty = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"short mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseShortStruct),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseShortStruct = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"local mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseLocal),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseLocal = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"example tag mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseExampleTag),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseExampleTag = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t\telem.Div(\n\t\t\t\tvecty.Property(\"class\", \"col output\"),\n\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\tvecty.Text(\"output struct\"),\n\t\t\t\t),\n\n\t\t\t\tvecty.Tag(\"pre\",\n\t\t\t\t\telem.Code(\n\t\t\t\t\t\t&StructObject{\n\t\t\t\t\t\t\tInput: p.Input,\n\t\t\t\t\t\t\tOption: json2struct.Options{\n\t\t\t\t\t\t\t\tName: p.StructName,\n\t\t\t\t\t\t\t\tPrefix: p.Prefix,\n\t\t\t\t\t\t\t\tSuffix: p.Suffix,\n\t\t\t\t\t\t\t\tUseShortStruct: p.UseShortStruct,\n\t\t\t\t\t\t\t\tUseLocal: p.UseLocal,\n\t\t\t\t\t\t\t\tUseOmitempty: p.UseOmitempty,\n\t\t\t\t\t\t\t\tUseExample: p.UseExampleTag,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\telem.Footer(\n\t\t\tvecty.Property(\"class\", \"footer\"),\n\t\t\tvecty.Text(\"Used by \"),\n\t\t\telem.Anchor(\n\t\t\t\tprop.Href(\"https://github.com/yudppp/json2struct\"),\n\t\t\t\tvecty.Text(\"yudppp/json2struct\"),\n\t\t\t),\n\t\t),\n\t)\n\n}", "func render(c *gin.Context) {\n\t// fill up the list with the current store listing\n\tfmt.Println(\"RENDER ATTACHED\")\n\t// render_active = true\n\tc.Stream(func(w io.Writer) bool {\n\t\tselect {\n\t\tcase msg := <-render_chan:\n\t\t\tdata, _ := json.Marshal(msg)\n\t\t\tc.SSEvent(\"render\", string(data))\n\t\t}\n\t\treturn true\n\t})\n\t// render_active = false\n\tfmt.Println(\"RENDERER DETACHED\")\n}", "func (c *Component) String() string {\n\tvar buf bytes.Buffer\n\tif err := c.Render(&buf, c); err != nil {\n\t\treturn fmt.Sprintf(\"template rendering failed: %s\", err)\n\t}\n\treturn buf.String()\n}", "func ServeHTML(w http.ResponseWriter, layout string, content string, data map[string]interface{}) {\n\tvar buf bytes.Buffer\n\tbodyTmplErr := tmpl.ExecuteTemplate(&buf, content, data)\n\tif bodyTmplErr != nil {\n\t\tlog.Printf(\"|ERROR|ServeHTML bodyTmplErr ERROR %v\", bodyTmplErr)\n\t}\n\tbodyHTML := template.HTML(buf.String())\n\tif len(data) == 0 {\n\t\tdata = map[string]interface{}{}\n\t}\n\tdata[\"LayoutContent\"] = bodyHTML\n\ttmplErr := tmpl.ExecuteTemplate(w,\n\t\tlayout,\n\t\tdata)\n\n\tif tmplErr != nil {\n\t\tlog.Printf(\"|ERROR|ServeHTML LayoutTmplErr ERROR %v\", tmplErr)\n\t}\n}", "func init() {\n\tpackr.PackJSONBytes(\"./static\", \"index.html\", \"\\\"PCFET0NUWVBFIGh0bWw+CjxodG1sPgogIDxoZWFkPgogICAgPHN0eWxlPgogICAgICBib2R5IHsKICAgICAgICBoZWlnaHQ6IDEwMCU7CiAgICAgICAgbWFyZ2luOiAwOwogICAgICAgIHdpZHRoOiAxMDAlOwogICAgICAgIG92ZXJmbG93OiBoaWRkZW47CiAgICAgIH0KICAgICAgI2dyYXBoaXFsIHsKICAgICAgICBoZWlnaHQ6IDEwMHZoOwogICAgICB9CiAgICA8L3N0eWxlPgoKICAgIDxzY3JpcHQgc3JjPSIvL2Nkbi5qc2RlbGl2ci5uZXQvZXM2LXByb21pc2UvNC4wLjUvZXM2LXByb21pc2UuYXV0by5taW4uanMiPjwvc2NyaXB0PgogICAgPHNjcmlwdCBzcmM9Ii8vY2RuLmpzZGVsaXZyLm5ldC9mZXRjaC8wLjkuMC9mZXRjaC5taW4uanMiPjwvc2NyaXB0PgogICAgPHNjcmlwdCBzcmM9Ii8vY2RuLmpzZGVsaXZyLm5ldC9yZWFjdC8xNS40LjIvcmVhY3QubWluLmpzIj48L3NjcmlwdD4KICAgIDxzY3JpcHQgc3JjPSIvL2Nkbi5qc2RlbGl2ci5uZXQvcmVhY3QvMTUuNC4yL3JlYWN0LWRvbS5taW4uanMiPjwvc2NyaXB0PgoKICAgIDxsaW5rIHJlbD0ic3R5bGVzaGVldCIgaHJlZj0iaHR0cHM6Ly9jZG5qcy5jbG91ZGZsYXJlLmNvbS9hamF4L2xpYnMvZ3JhcGhpcWwvMC4xMi4wL2dyYXBoaXFsLmNzcyIgLz4KICAgIDxzY3JpcHQgc3JjPSJodHRwczovL2NkbmpzLmNsb3VkZmxhcmUuY29tL2FqYXgvbGlicy9ncmFwaGlxbC8wLjEyLjAvZ3JhcGhpcWwuanMiIGNoYXJzZXQ9InV0Zi04Ij48L3NjcmlwdD4KCiAgPC9oZWFkPgogIDxib2R5PgogICAgPGRpdiBpZD0iZ3JhcGhpcWwiPkxvYWRpbmcuLi48L2Rpdj4KICAgIDxzY3JpcHQ+CiAgICAgIC8vIFBhcnNlIHRoZSBzZWFyY2ggc3RyaW5nIHRvIGdldCB1cmwgcGFyYW1ldGVycy4KICAgICAgdmFyIHNlYXJjaCA9IHdpbmRvdy5sb2NhdGlvbi5zZWFyY2g7CiAgICAgIHZhciBob3N0bmFtZSA9IHdpbmRvdy5sb2NhdGlvbi5ob3N0bmFtZTsKICAgICAgdmFyIHBhcmFtZXRlcnMgPSB7fTsKCiAgICAgIHNlYXJjaC5zdWJzdHIoMSkuc3BsaXQoJyYnKS5mb3JFYWNoKGZ1bmN0aW9uIChlbnRyeSkgewogICAgICAgIHZhciBlcSA9IGVudHJ5LmluZGV4T2YoJz0nKTsKICAgICAgICBpZiAoZXEgPj0gMCkgewogICAgICAgICAgcGFyYW1ldGVyc1tkZWNvZGVVUklDb21wb25lbnQoZW50cnkuc2xpY2UoMCwgZXEpKV0gPQogICAgICAgICAgICBkZWNvZGVVUklDb21wb25lbnQoZW50cnkuc2xpY2UoZXEgKyAxKSk7CiAgICAgICAgfQogICAgICB9KTsKCiAgICAgIC8vIGlmIHZhcmlhYmxlcyB3YXMgcHJvdmlkZWQsIHRyeSB0byBmb3JtYXQgaXQuCiAgICAgIGlmIChwYXJhbWV0ZXJzLnZhcmlhYmxlcykgewogICAgICAgIHRyeSB7CiAgICAgICAgICBwYXJhbWV0ZXJzLnZhcmlhYmxlcyA9CiAgICAgICAgICAgIEpTT04uc3RyaW5naWZ5KEpTT04ucGFyc2UocGFyYW1ldGVycy52YXJpYWJsZXMpLCBudWxsLCAyKTsKICAgICAgICB9IGNhdGNoIChlKSB7CiAgICAgICAgICAvLyBEbyBub3RoaW5nLCB3ZSB3YW50IHRvIGRpc3BsYXkgdGhlIGludmFsaWQgSlNPTiBhcyBhIHN0cmluZywgcmF0aGVyCiAgICAgICAgICAvLyB0aGFuIHByZXNlbnQgYW4gZXJyb3IuCiAgICAgICAgfQogICAgICB9CgogICAgICAvLyBXaGVuIHRoZSBxdWVyeSBhbmQgdmFyaWFibGVzIHN0cmluZyBpcyBlZGl0ZWQsIHVwZGF0ZSB0aGUgVVJMIGJhciBzbwogICAgICAvLyB0aGF0IGl0IGNhbiBiZSBlYXNpbHkgc2hhcmVkCiAgICAgIGZ1bmN0aW9uIG9uRWRpdFF1ZXJ5KG5ld1F1ZXJ5KSB7CiAgICAgICAgcGFyYW1ldGVycy5xdWVyeSA9IG5ld1F1ZXJ5OwogICAgICAgIHVwZGF0ZVVSTCgpOwogICAgICB9CgogICAgICBmdW5jdGlvbiBvbkVkaXRWYXJpYWJsZXMobmV3VmFyaWFibGVzKSB7CiAgICAgICAgcGFyYW1ldGVycy52YXJpYWJsZXMgPSBuZXdWYXJpYWJsZXM7CiAgICAgICAgdXBkYXRlVVJMKCk7CiAgICAgIH0KCiAgICAgIGZ1bmN0aW9uIG9uRWRpdE9wZXJhdGlvbk5hbWUobmV3T3BlcmF0aW9uTmFtZSkgewogICAgICAgIHBhcmFtZXRlcnMub3BlcmF0aW9uTmFtZSA9IG5ld09wZXJhdGlvbk5hbWU7CiAgICAgICAgdXBkYXRlVVJMKCk7CiAgICAgIH0KCiAgICAgIGZ1bmN0aW9uIHVwZGF0ZVVSTCgpIHsKICAgICAgICB2YXIgbmV3U2VhcmNoID0gJz8nICsgT2JqZWN0LmtleXMocGFyYW1ldGVycykuZmlsdGVyKGZ1bmN0aW9uIChrZXkpIHsKICAgICAgICAgIHJldHVybiBCb29sZWFuKHBhcmFtZXRlcnNba2V5XSk7CiAgICAgICAgfSkubWFwKGZ1bmN0aW9uIChrZXkpIHsKICAgICAgICAgIHJldHVybiBlbmNvZGVVUklDb21wb25lbnQoa2V5KSArICc9JyArCiAgICAgICAgICAgIGVuY29kZVVSSUNvbXBvbmVudChwYXJhbWV0ZXJzW2tleV0pOwogICAgICAgIH0pLmpvaW4oJyYnKTsKICAgICAgICBoaXN0b3J5LnJlcGxhY2VTdGF0ZShudWxsLCBudWxsLCBuZXdTZWFyY2gpOwogICAgICB9CgogICAgICAvLyBEZWZpbmVzIGEgR3JhcGhRTCBmZXRjaGVyIHVzaW5nIHRoZSBmZXRjaCBBUEkuIFlvdSdyZSBub3QgcmVxdWlyZWQgdG8KICAgICAgLy8gdXNlIGZldGNoLCBhbmQgY291bGQgaW5zdGVhZCBpbXBsZW1lbnQgZ3JhcGhRTEZldGNoZXIgaG93ZXZlciB5b3UgbGlrZSwKICAgICAgLy8gYXMgbG9uZyBhcyBpdCByZXR1cm5zIGEgUHJvbWlzZSBvciBPYnNlcnZhYmxlLgogICAgICBmdW5jdGlvbiBncmFwaFFMRmV0Y2hlcihncmFwaFFMUGFyYW1zKSB7CiAgICAgICAgLy8gVGhpcyBleGFtcGxlIGV4cGVjdHMgYSBHcmFwaFFMIHNlcnZlciBhdCB0aGUgcGF0aCAvZ3JhcGhxbC4KICAgICAgICAvLyBDaGFuZ2UgdGhpcyB0byBwb2ludCB3aGVyZXZlciB5b3UgaG9zdCB5b3VyIEdyYXBoUUwgc2VydmVyLgogICAgICAgIC8vIHJldHVybiBmZXRjaCgnL2dyYXBocWwnLCB7CiAgICAgICAgcmV0dXJuIGZldGNoKCdodHRwOi8vJyArIGhvc3RuYW1lICsgJzo3MzUwL3YyL3JwYy9ncmFwaHFsP2h0dHBfa2V5PWRlZmF1bHRrZXknLCB7CiAgICAgICAgICBtZXRob2Q6ICdwb3N0JywKICAgICAgICAgIGhlYWRlcnM6IHsKICAgICAgICAgICAgJ0FjY2VwdCc6ICdhcHBsaWNhdGlvbi9qc29uJywKICAgICAgICAgICAgJ0NvbnRlbnQtVHlwZSc6ICdhcHBsaWNhdGlvbi9qc29uJywKICAgICAgICAgIH0sCiAgICAgICAgICBib2R5OiBKU09OLnN0cmluZ2lmeShKU09OLnN0cmluZ2lmeShncmFwaFFMUGFyYW1zKSksCiAgICAgICAgICAvLyBjcmVkZW50aWFsczogJ2luY2x1ZGUnLAogICAgICAgIH0pLnRoZW4oZnVuY3Rpb24gKHJlc3BvbnNlKSB7CiAgICAgICAgICByZXR1cm4gcmVzcG9uc2UudGV4dCgpOwogICAgICAgIH0pLnRoZW4oZnVuY3Rpb24gKHJlc3BvbnNlQm9keSkgewogICAgICAgICAgdHJ5IHsKICAgICAgICAgICAgcmV0dXJuIEpTT04ucGFyc2UoSlNPTi5wYXJzZShyZXNwb25zZUJvZHkpLnBheWxvYWQpOwogICAgICAgICAgfSBjYXRjaCAoZXJyb3IpIHsKICAgICAgICAgICAgcmV0dXJuIHJlc3BvbnNlQm9keTsKICAgICAgICAgIH0KICAgICAgICB9KTsKICAgICAgfQoKICAgICAgLy8gUmVuZGVyIDxHcmFwaGlRTCAvPiBpbnRvIHRoZSBib2R5LgogICAgICAvLyBTZWUgdGhlIFJFQURNRSBpbiB0aGUgdG9wIGxldmVsIG9mIHRoaXMgbW9kdWxlIHRvIGxlYXJuIG1vcmUgYWJvdXQKICAgICAgLy8gaG93IHlvdSBjYW4gY3VzdG9taXplIEdyYXBoaVFMIGJ5IHByb3ZpZGluZyBkaWZmZXJlbnQgdmFsdWVzIG9yCiAgICAgIC8vIGFkZGl0aW9uYWwgY2hpbGQgZWxlbWVudHMuCiAgICAgIFJlYWN0RE9NLnJlbmRlcigKICAgICAgICBSZWFjdC5jcmVhdGVFbGVtZW50KEdyYXBoaVFMLCB7CiAgICAgICAgICBmZXRjaGVyOiBncmFwaFFMRmV0Y2hlciwKICAgICAgICAgIHF1ZXJ5OiBwYXJhbWV0ZXJzLnF1ZXJ5LAogICAgICAgICAgdmFyaWFibGVzOiBwYXJhbWV0ZXJzLnZhcmlhYmxlcywKICAgICAgICAgIG9wZXJhdGlvbk5hbWU6IHBhcmFtZXRlcnMub3BlcmF0aW9uTmFtZSwKICAgICAgICAgIG9uRWRpdFF1ZXJ5OiBvbkVkaXRRdWVyeSwKICAgICAgICAgIG9uRWRpdFZhcmlhYmxlczogb25FZGl0VmFyaWFibGVzLAogICAgICAgICAgb25FZGl0T3BlcmF0aW9uTmFtZTogb25FZGl0T3BlcmF0aW9uTmFtZQogICAgICAgIH0pLAogICAgICAgIGRvY3VtZW50LmdldEVsZW1lbnRCeUlkKCdncmFwaGlxbCcpCiAgICAgICk7CiAgICA8L3NjcmlwdD4KICA8L2JvZHk+CjwvaHRtbD4K\\\"\")\n}", "func (h *eventServiceHTTPHandler) Mount(group *echo.Group) {\n\tgroup.POST(\"/create\", h.CreateEvent)\n\tgroup.POST(\"/ticket/create\", h.CreateTicket)\n\tgroup.GET(\"/get_info\", h.GetEventInfo)\n}", "func Test_Ctx_Render_Mount_ParentOrSubHasViews(t *testing.T) {\n\tt.Parallel()\n\n\tengine := &testTemplateEngine{}\n\terr := engine.Load()\n\tutils.AssertEqual(t, nil, err)\n\n\tengine2 := &testTemplateEngine{path: \"testdata2\"}\n\terr = engine2.Load()\n\tutils.AssertEqual(t, nil, err)\n\n\tsub := New(Config{\n\t\tViews: html.New(\"./.github/testdata/template\", \".gohtml\"),\n\t})\n\n\tsub2 := New(Config{\n\t\tViews: engine2,\n\t})\n\n\tapp := New(Config{\n\t\tViews: engine,\n\t})\n\n\tapp.Get(\"/test\", func(c *Ctx) error {\n\t\treturn c.Render(\"index.tmpl\", Map{\n\t\t\t\"Title\": \"Hello, World!\",\n\t\t})\n\t})\n\n\tsub.Get(\"/world/:name\", func(c *Ctx) error {\n\t\treturn c.Render(\"hello_world\", Map{\n\t\t\t\"Name\": c.Params(\"name\"),\n\t\t})\n\t})\n\n\tsub2.Get(\"/moment\", func(c *Ctx) error {\n\t\treturn c.Render(\"bruh.tmpl\", Map{})\n\t})\n\n\tsub.Mount(\"/bruh\", sub2)\n\tapp.Mount(\"/hello\", sub)\n\n\tresp, err := app.Test(httptest.NewRequest(MethodGet, \"/hello/world/a\", http.NoBody))\n\tutils.AssertEqual(t, StatusOK, resp.StatusCode, \"Status code\")\n\tutils.AssertEqual(t, nil, err, \"app.Test(req)\")\n\n\tbody, err := io.ReadAll(resp.Body)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, \"<h1>Hello a!</h1>\", string(body))\n\n\tresp, err = app.Test(httptest.NewRequest(MethodGet, \"/test\", http.NoBody))\n\tutils.AssertEqual(t, StatusOK, resp.StatusCode, \"Status code\")\n\tutils.AssertEqual(t, nil, err, \"app.Test(req)\")\n\n\tbody, err = io.ReadAll(resp.Body)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, \"<h1>Hello, World!</h1>\", string(body))\n\n\tresp, err = app.Test(httptest.NewRequest(MethodGet, \"/hello/bruh/moment\", http.NoBody))\n\tutils.AssertEqual(t, StatusOK, resp.StatusCode, \"Status code\")\n\tutils.AssertEqual(t, nil, err, \"app.Test(req)\")\n\n\tbody, err = io.ReadAll(resp.Body)\n\tutils.AssertEqual(t, nil, err)\n\tutils.AssertEqual(t, \"<h1>I'm Bruh</h1>\", string(body))\n}", "func (mm *massivemonster) render() {\n\n\trenderOutput(\"Massive Monster\", \"h1\", \"red\")\n\trenderOutput(mm.mmType, \"\", \"clear\")\n\trenderOutput(\"Class: \"+strconv.Itoa(mm.class), \"\", \"clear\")\n\trenderOutput(\"Motivation: \"+mm.motivation, \"\", \"clear\")\n\n\trenderOutput(\"Abilities\", \"h2\", \"clear\")\n\tif len(mm.abilities) > 0 {\n\t\tfor i := 0; i < len(mm.abilities); i++ {\n\t\t\trenderOutput(mm.abilities[i], \"listitem\", \"blue\")\n\t\t}\n\t}\n\n\trenderOutput(\"Natures\", \"h2\", \"clear\")\n\tif len(mm.natures) > 0 {\n\t\tfor i := 0; i < len(mm.natures); i++ {\n\t\t\trenderOutput(mm.natures[i], \"listitem\", \"green\")\n\t\t}\n\t}\n\trenderOutput(\"Weak Spot: \"+mm.weakSpot, \"\", \"yellow\")\n\trenderOutput(\"Incursion Zone Effect\", \"h2\", \"purple\")\n\trenderOutput(mm.zEffect, \"listitem\", \"clear\")\n\n}", "func startService() {\n\n box := packr.NewBox(\"./templates\")\n\n http.Handle(\"/\", http.FileServer(box))\n http.HandleFunc(\"/upload/\", ReceiveFile)\n\n log.Println(\"starting http service...\")\n if err := http.ListenAndServe(\":80\", nil); err != nil {\n log.Fatal(err)\n }\n}", "func Open() {\n\t// router.RegisterByHandleFunc(\"/\", func(res http.ResponseWriter, req *http.Request) {\n\t// \tvar tpl = template.Must(template.ParseGlob(\"resources/*.gohtml\"))\n\t// \terr := tpl.ExecuteTemplate(res, \"home.gohtml\", nil)\n\t// \tif !recoder.Write(err) {\n\t// \t\tio.WriteString(res, err.Error())\n\t// \t}\n\t// })\n\trouter.RegisterByString(\"/\", \"HomeController\", \"Index\")\n\trouter.RegisterByString(\"/login\", \"LoginController\", \"Index\")\n\trouter.RegisterByString(\"/logincheck\", \"LoginController\", \"LoginCheck\")\n\trouter.RegisterByString(\"/logout\", \"LoginController\", \"Logout\")\n\trouter.RegisterByString(\"/register\", \"RegisterController\", \"Index\")\n\trouter.RegisterByString(\"/registercheck\", \"RegisterController\", \"Register\")\n\trouter.RegisterByString(\"/activity\", \"ActivityController\", \"Index\")\n\trouter.RegisterByString(\"/activity/create\", \"ActivityController\", \"Create\")\n\trouter.RegisterByString(\"/activity/store\", \"ActivityController\", \"Store\")\n\trouter.RegisterByString(\"/activity/delete\", \"ActivityController\", \"Delete\")\n\trouter.RegisterByString(\"/activity/join\", \"ActivityController\", \"Join\")\n\trouter.Start()\n}", "func renderPage(ctx *Context, path, tpl string, data interface{}) error {\n\tif err := filesystem.CreateDir(path, true); err != nil {\n\t\treturn err\n\t}\n\n\thandle, err := filesystem.CreateFile(filepath.Join(path, indexFile))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttplPath := filepath.Join(ctx.TemplateDir, tpl)\n\treturn template.Render(tplPath, data, handle)\n}", "func NewPage(ID string, h *live.Handler, s *live.Socket, title string) (*page.Component, error) {\n\treturn page.NewComponent(ID, h, s,\n\t\tpage.WithRegister(pageRegister),\n\t\tpage.WithMount(pageMount(title)),\n\t\tpage.WithRender(pageRender),\n\t)\n}", "func (tp *Template) Component(filename ...string) *Template {\n\ttp.components = append(tp.components, filename...)\n\treturn tp\n}", "func (w *Window) Render(compo app.Component) error {\n\tsyncs, err := w.markup.Update(compo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, sync := range syncs {\n\t\tif sync.Replace {\n\t\t\terr = w.render(sync)\n\t\t} else {\n\t\t\terr = w.renderAttributes(sync)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func addUIRoutes(router *mux.Router, fsc *frontendServerConfig, handlers *web.Handlers) {\n\t// Serve static assets (JS and CSS Webpack bundles, images, etc.).\n\t//\n\t// Note that this includes the raw HTML templates (e.g. /dist/byblame.html) with unpopulated\n\t// placeholders such as {{.Title}}. These aren't used directly by client code. We should probably\n\t// unexpose them and only serve the JS/CSS Webpack bundles from this route (and any other static\n\t// assets such as the favicon).\n\trouter.PathPrefix(\"/dist/\").Handler(http.StripPrefix(\"/dist/\", http.HandlerFunc(web.MakeResourceHandler(fsc.ResourcesPath))))\n\n\tvar templates *template.Template\n\n\tloadTemplates := func() {\n\t\ttemplates = template.Must(template.New(\"\").ParseGlob(filepath.Join(fsc.ResourcesPath, \"*.html\")))\n\t}\n\n\tloadTemplates()\n\n\tfsc.FrontendConfig.BaseRepoURL = fsc.GitRepoURL\n\tfsc.FrontendConfig.IsPublic = fsc.IsPublicView\n\n\ttemplateHandler := func(name string) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tw.Header().Set(\"Content-Type\", \"text/html\")\n\n\t\t\t// Reload the template if we are running locally.\n\t\t\tif fsc.Local {\n\t\t\t\tloadTemplates()\n\t\t\t}\n\t\t\tif err := templates.ExecuteTemplate(w, name, fsc.FrontendConfig); err != nil {\n\t\t\t\tsklog.Errorf(\"Failed to expand template %s : %s\", name, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\t// These routes serve the web UI.\n\trouter.HandleFunc(\"/\", templateHandler(\"byblame.html\"))\n\trouter.HandleFunc(\"/changelists\", templateHandler(\"changelists.html\"))\n\trouter.HandleFunc(\"/cluster\", templateHandler(\"cluster.html\"))\n\trouter.HandleFunc(\"/triagelog\", templateHandler(\"triagelog.html\"))\n\trouter.HandleFunc(\"/ignores\", templateHandler(\"ignorelist.html\"))\n\trouter.HandleFunc(\"/diff\", templateHandler(\"diff.html\"))\n\trouter.HandleFunc(\"/detail\", templateHandler(\"details.html\"))\n\trouter.HandleFunc(\"/details\", templateHandler(\"details.html\"))\n\trouter.HandleFunc(\"/list\", templateHandler(\"by_test_list.html\"))\n\trouter.HandleFunc(\"/help\", templateHandler(\"help.html\"))\n\trouter.HandleFunc(\"/search\", templateHandler(\"search.html\"))\n\trouter.HandleFunc(\"/cl/{system}/{id}\", handlers.ChangelistSearchRedirect)\n}", "func renderRawComponent(elem types.AddonElementFile) (*common2.ApplicationComponent, error) {\n\tbaseRawComponent := common2.ApplicationComponent{\n\t\tType: \"raw\",\n\t\tName: strings.Join(append(elem.Path, elem.Name), \"-\"),\n\t}\n\tobj, err := renderObject(elem)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbaseRawComponent.Properties = util.Object2RawExtension(obj)\n\treturn &baseRawComponent, nil\n}", "func loadEngine(t *template.Template) template.Engine {\n\tvar e template.Engine\n\tvar err error\n\tswitch format {\n\tcase \"yaml\":\n\t\te, err = yaml.New(&yaml.Config{\n\t\t\tLogger: logrus.StandardLogger(),\n\t\t\tOptional: optional,\n\t\t\tTemplate: t,\n\t\t})\n\t\tif err != nil {\n\t\t\tlogrus.WithError(err).Fatalln(\"error creating renderer\")\n\t\t}\n\tdefault:\n\t\tlogrus.Fatalf(\"unsupported renderer format: %s\", format)\n\t}\n\treturn e\n}" ]
[ "0.61620396", "0.59130037", "0.5405633", "0.52657056", "0.52206516", "0.5196817", "0.51771003", "0.51350504", "0.51303655", "0.512185", "0.50885075", "0.5082273", "0.4991742", "0.49844354", "0.49831536", "0.498048", "0.49544212", "0.49427688", "0.4928292", "0.49256727", "0.49189642", "0.49168488", "0.49019894", "0.4898215", "0.4887526", "0.48717147", "0.48717147", "0.48594242", "0.4857845", "0.48507592", "0.48285216", "0.48202056", "0.47819877", "0.4777286", "0.47750834", "0.4759377", "0.4751693", "0.4728134", "0.472274", "0.47178724", "0.47164553", "0.4708143", "0.4693464", "0.4667918", "0.46654728", "0.46444666", "0.46428058", "0.46406087", "0.46381643", "0.46259725", "0.461751", "0.4603474", "0.4592499", "0.45831308", "0.4576938", "0.4572956", "0.45627823", "0.45595625", "0.45532507", "0.45531827", "0.45445758", "0.45422077", "0.45411533", "0.4531978", "0.45306864", "0.45291945", "0.45214552", "0.4519452", "0.45167485", "0.45148584", "0.45146605", "0.44982803", "0.4497931", "0.4496132", "0.4492465", "0.44913384", "0.4491317", "0.4489675", "0.44864577", "0.44763324", "0.44759947", "0.44725704", "0.4459052", "0.44555455", "0.44477114", "0.44451937", "0.44444335", "0.44371304", "0.44254023", "0.44250962", "0.44221112", "0.4419697", "0.44181845", "0.44163898", "0.441373", "0.4405245", "0.44043738", "0.44022596", "0.44019964", "0.4399256" ]
0.4971512
16
LiveRender render the last version of the component, and detect differences from the last render and sets the new version of render
func (l *LiveComponent) LiveRender() (string, []OutMessage) { newRender := l.GetComponentRender() oms := make([]OutMessage, 0) if len(l.Rendered) > 0 { changeInstructions, err := GetDiffFromRawHTML(l.Rendered, newRender) if err != nil { panic("There is a error in diff") } for _, instruction := range changeInstructions { oms = append(oms, OutMessage{ Name: EventLiveDom, Type: instruction.Type, Attr: instruction.Attr, ScopeID: instruction.ScopeID, Content: instruction.Content, Element: instruction.Element, }) } } l.Rendered = newRender return l.Rendered, oms }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Window) Render(compo app.Component) error {\n\tsyncs, err := w.markup.Update(compo)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, sync := range syncs {\n\t\tif sync.Replace {\n\t\t\terr = w.render(sync)\n\t\t} else {\n\t\t\terr = w.renderAttributes(sync)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *PureComponent) HasUpdated() bool { return false }", "func (p *PageView) Rerender() {\n\ttimeKey := time.Now().UnixNano()\n\tp.lastTimeKey = timeKey\n\tgo func() {\n\t\ttime.Sleep(800 * time.Millisecond)\n\t\tif timeKey == p.lastTimeKey {\n\t\t\tvecty.Rerender(p)\n\t\t}\n\t}()\n}", "func (o *RenderTemplate) Version() int {\n\n\treturn 1\n}", "func (d *DeploymentComponent) Render(is *v1alpha2.InstallSpec) (string, error) {\n\td.waitDeps()\n\tglobalValues, err := getHelmValues(d.helmChartBaseDirPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tsubchartDirPath := filepath.Join(d.helmChartBaseDirPath, d.relativeChartPath, d.componentName)\n\tchart, err := chartutil.Load(subchartDirPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tvalues := globalValues\n\tif filepath.Clean(d.helmChartBaseDirPath) != filepath.Clean(subchartDirPath) {\n\t\tvar err error\n\t\tvalues, err = getHelmValues(subchartDirPath)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tvalues, err = patchValues(bytes.Join([][]byte{globalValues, values}, nil), is)\n\t}\n\t//\tlog.Infof(\"values: \\n%s\\n\", values)\n\n\tlog.Infof(\"Rendering %s\", subchartDirPath)\n\tbaseYAML, err := helm.renderChart(d.namespace, string(values), chart)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn baseYAML, err\n}", "func Render(comp Component, container *js.Object) {\n\tcomp.Reconcile(nil)\n\tcontainer.Call(\"appendChild\", comp.Node())\n}", "func (o *SparseRenderTemplate) Version() int {\n\n\treturn 1\n}", "func (vd *videoDriver) Render(frameData []uint8) error {\n\tif !vd.readyForNewFrame {\n\t\treturn nil\n\t}\n\n\tvd.readyForNewFrame = false\n\n\tdoOnMainThread(func() {\n\t\tsurface, err := sdl.CreateRGBSurfaceFrom(\n\t\t\tunsafe.Pointer(&frameData[0]),\n\t\t\tgameboy.ScreenWidth,\n\t\t\tgameboy.ScreenHeight,\n\t\t\t32, // Bits per pixel\n\t\t\t4*gameboy.ScreenWidth, // Bytes per row\n\t\t\t0x000000FF, // Bitmask for R value\n\t\t\t0x0000FF00, // Bitmask for G value\n\t\t\t0x00FF0000, // Bitmask for B value\n\t\t\t0xFF000000, // Bitmask for alpha value\n\t\t)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"creating surface: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer surface.Free()\n\n\t\ttexture, err := vd.renderer.CreateTextureFromSurface(surface)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"converting surface to a texture: %w\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer texture.Destroy()\n\n\t\terr = vd.renderer.Copy(texture, nil, nil)\n\t\tif err != nil {\n\t\t\terr = xerrors.Errorf(\"copying frame to screen: %w\", err)\n\t\t\treturn\n\t\t}\n\n\t\tvd.renderer.Present()\n\n\t\tif !vd.unlimitedFPS {\n\t\t\tif time.Since(vd.lastFrameTime) < time.Second/targetFPS {\n\t\t\t\ttime.Sleep((time.Second / targetFPS) - time.Since(vd.lastFrameTime))\n\t\t\t}\n\t\t\tvd.lastFrameTime = time.Now()\n\t\t}\n\n\t\tvd.readyForNewFrame = true\n\t}, true)\n\n\treturn nil\n}", "func (r *renderer) Update(_ tea.Msg, _ *list.Model) tea.Cmd { return nil }", "func (st *Stemplate) Render(w *http.ResponseWriter, templateName string) {\n\n\tif !st.LiveReload {\n\t\tst.templates[templateName].ExecuteTemplate(*w, \"base\", st.data)\n\t} else {\n\t\tst.loadTemplate(templateName).ExecuteTemplate(*w, \"base\", st.data)\n\t}\n\n}", "func updateVisibleMesh(compRenderable *meshRenderable) {\n\t// push all settings from the component to the renderable\n\tcompRenderable.Renderable.Location = compRenderable.ComponentMesh.Offset\n\tcompRenderable.Renderable.Scale = compRenderable.ComponentMesh.Scale\n\tcompRenderable.Renderable.Material.DiffuseColor = compRenderable.ComponentMesh.Material.Diffuse\n\tif compRenderable.ComponentMesh.RotationDegrees != 0.0 {\n\t\tcompRenderable.Renderable.LocalRotation = mgl.QuatRotate(\n\t\t\tmgl.DegToRad(compRenderable.ComponentMesh.RotationDegrees),\n\t\t\tcompRenderable.ComponentMesh.RotationAxis)\n\t}\n\n\tcompRenderable.Renderable.Material.SpecularColor = compRenderable.ComponentMesh.Material.Specular\n\tcompRenderable.Renderable.Material.Shininess = compRenderable.ComponentMesh.Material.Shininess\n\n\t// try to find a shader\n\tshader, shaderFound := shaders[compRenderable.ComponentMesh.Material.ShaderName]\n\tif shaderFound {\n\t\tcompRenderable.Renderable.Material.Shader = shader\n\t}\n\n\t// assign textures\n\ttextures := compRenderable.ComponentMesh.Material.Textures\n\tfor i := 0; i < len(textures); i++ {\n\t\tglTex, texFound := textureMan.GetTexture(textures[i])\n\t\tif texFound && i < fizzle.MaxCustomTextures {\n\t\t\tcompRenderable.Renderable.Material.CustomTex[i] = glTex\n\t\t}\n\t}\n\tif len(compRenderable.ComponentMesh.Material.DiffuseTexture) > 0 {\n\t\tglTex, texFound := textureMan.GetTexture(compRenderable.ComponentMesh.Material.DiffuseTexture)\n\t\tif texFound {\n\t\t\tcompRenderable.Renderable.Material.DiffuseTex = glTex\n\t\t}\n\t}\n\tif len(compRenderable.ComponentMesh.Material.NormalsTexture) > 0 {\n\t\tglTex, texFound := textureMan.GetTexture(compRenderable.ComponentMesh.Material.NormalsTexture)\n\t\tif texFound {\n\t\t\tcompRenderable.Renderable.Material.NormalsTex = glTex\n\t\t}\n\t}\n\tif len(compRenderable.ComponentMesh.Material.SpecularTexture) > 0 {\n\t\tglTex, texFound := textureMan.GetTexture(compRenderable.ComponentMesh.Material.SpecularTexture)\n\t\tif texFound {\n\t\t\tcompRenderable.Renderable.Material.SpecularTex = glTex\n\t\t}\n\t}\n\n}", "func (h *Browser) Render() vecty.ComponentOrHTML {\n\treturn elem.InlineFrame(\n\t\tvecty.Markup(\n\t\t\tvecty.Class(\"help-browser\"),\n\t\t\tvecty.Property(\"src\", h.getCachedURL()),\n\t\t),\n\t)\n}", "func (v *Component) ComponentDidUpdate(prevProps *Map, prevState *Map) {}", "func (o RenderTemplatesList) Version() int {\n\n\treturn 1\n}", "func (r *Renderer) Render(ctx context.Context, input *RenderInput) (*RenderOutput, error) {\n\tif input == nil {\n\t\tinput = &RenderInput{}\n\t}\n\n\t// policyEnforcedClient cannot be global because policy is calculated from global policy, action policy and worklfow step policies\n\tpolicyEnforcedClient := hubclient.NewPolicyEnforcedClient(r.hubClient)\n\n\t// 0. Populate render options\n\tdedicatedRenderer := newDedicatedRenderer(r.maxDepth, policyEnforcedClient, r.typeInstanceHandler, input.Options...)\n\n\tctxWithTimeout, cancel := context.WithTimeout(ctx, r.renderTimeout)\n\tdefer cancel()\n\n\t// 1. Find the root manifests\n\tinterfaceRef := interfaceRefToHub(input.InterfaceRef)\n\n\t// 1.1 Get Interface\n\tiface, err := policyEnforcedClient.FindInterfaceRevision(ctx, interfaceRef)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 1.2 Get all ImplementationRevisions for a given Interface\n\timplementations, rule, err := policyEnforcedClient.ListImplementationRevisionForInterface(ctxWithTimeout, interfaceRef)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, `while listing ImplementationRevisions for Interface \"%s:%s\"`,\n\t\t\tinterfaceRef.Path, interfaceRef.Revision,\n\t\t)\n\t}\n\n\t// 1.3 Pick one of the Implementations\n\timplementation, err := dedicatedRenderer.PickImplementationRevision(implementations)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, `while picking ImplementationRevision for Interface \"%s:%s\"`,\n\t\t\tinterfaceRef.Path, interfaceRef.Revision)\n\t}\n\n\t// 2. Ensure that the runner was defined in imports section\n\t// TODO: we should check whether imported revision is valid for this render algorithm\n\trunnerInterface, err := dedicatedRenderer.ResolveRunnerInterface(implementation)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while resolving runner Interface\")\n\t}\n\n\t// 3. Extract workflow from the root Implementation\n\trootWorkflow, _, err := dedicatedRenderer.UnmarshalWorkflowFromImplementation(\"\", &implementation)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while creating root workflow\")\n\t}\n\n\t// 3.1 Add our own root step and replace entrypoint\n\trootWorkflow, entrypointStep := dedicatedRenderer.WrapEntrypointWithRootStep(rootWorkflow)\n\n\t// 4. Add user input\n\tdedicatedRenderer.AddUserInputSecretRefIfProvided(rootWorkflow)\n\n\t// 5. List data based on policy and inject them if provided\n\t// 5.1 TypeInstances\n\ttypeInstancesToInject := policyEnforcedClient.ListTypeInstancesToInjectBasedOnPolicy(rule, implementation)\n\terr = dedicatedRenderer.InjectDownloadStepForTypeInstancesIfProvided(rootWorkflow, typeInstancesToInject)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while injecting step for downloading TypeInstances based on policy\")\n\t}\n\t// 5.2 Additional Input\n\tadditionalInput := policyEnforcedClient.ListAdditionalInputToInjectBasedOnPolicy(rule, implementation)\n\terr = dedicatedRenderer.InjectAdditionalInput(entrypointStep, additionalInput)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"while injecting additional input based on policy\")\n\t}\n\n\t// 6. Add runner context\n\tif err := dedicatedRenderer.AddRunnerContext(rootWorkflow, input.RunnerContextSecretRef); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// 7. Add steps to populate rootWorkflow with input TypeInstances\n\tif err := dedicatedRenderer.AddInputTypeInstances(rootWorkflow); err != nil {\n\t\treturn nil, err\n\t}\n\n\tavailableArtifacts := dedicatedRenderer.tplInputArguments[dedicatedRenderer.entrypointStep.Template]\n\n\t// 8 Register output TypeInstances\n\tif err := dedicatedRenderer.addOutputTypeInstancesToGraph(nil, \"\", iface, &implementation, availableArtifacts); err != nil {\n\t\treturn nil, errors.Wrap(err, \"while noting output artifacts\")\n\t}\n\n\t// 9. Render rootWorkflow templates\n\t_, err = dedicatedRenderer.RenderTemplateSteps(ctxWithTimeout, rootWorkflow, implementation.Spec.Imports, dedicatedRenderer.inputTypeInstances, \"\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trootWorkflow.Templates = dedicatedRenderer.GetRootTemplates()\n\n\tif err := dedicatedRenderer.AddOutputTypeInstancesStep(rootWorkflow); err != nil {\n\t\treturn nil, err\n\t}\n\n\tout, err := r.toMapStringInterface(rootWorkflow)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &RenderOutput{\n\t\tAction: &types.Action{\n\t\t\tArgs: out,\n\t\t\tRunnerInterface: runnerInterface,\n\t\t},\n\t\tTypeInstancesToLock: dedicatedRenderer.GetTypeInstancesToLock(),\n\t}, nil\n}", "func (o SparseRenderTemplatesList) Version() int {\n\n\treturn 1\n}", "func postrender(c *gin.Context) {\n\tvar r Render\n\terr := c.ShouldBind(&r)\n\tfmt.Println(r, err)\n\tb, _ := json.Marshal(r)\n\tview.Save(r.Name, b)\n\t//if render_active {\n\trender_chan <- r\n\trender_update <- r\n\t//}\n}", "func Render(c Compo) {\n\tdriver.CallOnUIGoroutine(func() {\n\t\tdriver.Render(c)\n\t})\n}", "func defaultRender(w io.Writer, c *Component) error {\n\t_, err := w.Write([]byte(fmt.Sprintf(\"%+v\", c.State)))\n\treturn err\n}", "func (p *PageView) Render() vecty.ComponentOrHTML {\n\treturn elem.Body(\n\t\telem.Header(\n\t\t\tvecty.Property(\"class\", \"header\"),\n\t\t\tvecty.Text(\"json2struct playground\"),\n\t\t),\n\t\telem.Div(\n\t\t\tvecty.Property(\"class\", \"wrapper\"),\n\t\t\telem.Div(\n\t\t\t\tvecty.Property(\"class\", \"col input\"),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"input json\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.TextArea(\n\t\t\t\t\t\tvecty.Property(\"class\", \"u-full-width\"),\n\t\t\t\t\t\tvecty.Text(p.Input),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Input = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.StructName),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.StructName = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct prefix name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.Prefix),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Prefix = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"struct suffix name\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tprop.Value(p.Suffix),\n\t\t\t\t\t\tprop.Type(prop.TypeText),\n\t\t\t\t\t\tevent.Input(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.Suffix = e.Target.Get(\"value\").String()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"omitempty mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseOmitempty),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseOmitempty = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"short mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseShortStruct),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseShortStruct = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"local mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseLocal),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseLocal = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t\telem.Div(\n\t\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\t\tvecty.Text(\"example tag mode\"),\n\t\t\t\t\t),\n\t\t\t\t\telem.Input(\n\t\t\t\t\t\tvecty.Property(\"class\", \"toggle\"),\n\t\t\t\t\t\tprop.Type(prop.TypeCheckbox),\n\t\t\t\t\t\tprop.Checked(p.UseExampleTag),\n\t\t\t\t\t\tevent.Change(func(e *vecty.Event) {\n\t\t\t\t\t\t\tp.UseExampleTag = e.Target.Get(\"checked\").Bool()\n\t\t\t\t\t\t\tp.Rerender()\n\t\t\t\t\t\t}),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t\telem.Div(\n\t\t\t\tvecty.Property(\"class\", \"col output\"),\n\t\t\t\tvecty.Tag(\"label\",\n\t\t\t\t\tvecty.Text(\"output struct\"),\n\t\t\t\t),\n\n\t\t\t\tvecty.Tag(\"pre\",\n\t\t\t\t\telem.Code(\n\t\t\t\t\t\t&StructObject{\n\t\t\t\t\t\t\tInput: p.Input,\n\t\t\t\t\t\t\tOption: json2struct.Options{\n\t\t\t\t\t\t\t\tName: p.StructName,\n\t\t\t\t\t\t\t\tPrefix: p.Prefix,\n\t\t\t\t\t\t\t\tSuffix: p.Suffix,\n\t\t\t\t\t\t\t\tUseShortStruct: p.UseShortStruct,\n\t\t\t\t\t\t\t\tUseLocal: p.UseLocal,\n\t\t\t\t\t\t\t\tUseOmitempty: p.UseOmitempty,\n\t\t\t\t\t\t\t\tUseExample: p.UseExampleTag,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t),\n\t\telem.Footer(\n\t\t\tvecty.Property(\"class\", \"footer\"),\n\t\t\tvecty.Text(\"Used by \"),\n\t\t\telem.Anchor(\n\t\t\t\tprop.Href(\"https://github.com/yudppp/json2struct\"),\n\t\t\t\tvecty.Text(\"yudppp/json2struct\"),\n\t\t\t),\n\t\t),\n\t)\n\n}", "func (v *Component) redraw() {\n\tv.Render()\n}", "func (c *Component) OnRender() {\n\t// Logger.Trace().Str(\"component\", c.GetName()).Msg(\"OnRender\")\n}", "func (vtx *uniqueVertex) shallowRefresh() {\n\tif vtx.v == nil {\n\t\tvtx.v = &vertexState{}\n\t}\n\tif vtx.v.latest {\n\t\treturn\n\t}\n\n\tlatest := vtx.serializer.state.UniqueVertex(vtx)\n\tprevVtx := vtx.v.vtx\n\tif latest == vtx {\n\t\tvtx.v.status = vtx.serializer.state.Status(vtx.ID())\n\t\tvtx.v.latest = true\n\t} else {\n\t\t// If someone is in the cache, they must be up-to-date\n\t\t*vtx = *latest\n\t}\n\n\tif vtx.v.vtx == nil {\n\t\tvtx.v.vtx = prevVtx\n\t}\n}", "func (srv *Server) Render() {\n\tsrv.mu.Lock()\n\tdefer srv.mu.Unlock()\n\tif srv.debounce {\n\t\treturn\n\t}\n\tsrv.debounce = true\n\tgo func() {\n\t\t<-time.After(1 * time.Millisecond)\n\t\tsrv.doRender(false)\n\t}()\n}", "func pageRender(w io.Writer, cmp *page.Component) error {\n\tstate, ok := cmp.State.(*PageState)\n\tif !ok {\n\t\treturn fmt.Errorf(\"could not get state\")\n\t}\n\n\t// Here we use the gomponents library to do typed rendering.\n\t// https://github.com/maragudk/gomponents\n\treturn c.HTML5(c.HTML5Props{\n\t\tTitle: state.Title,\n\t\tLanguage: \"en\",\n\t\tHead: []g.Node{\n\t\t\tStyleEl(Type(\"text/css\"),\n\t\t\t\tg.Raw(`body {font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, Helvetica, Arial, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\"; }`),\n\t\t\t),\n\t\t},\n\t\tBody: []g.Node{\n\t\t\tH1(g.Text(\"World Clocks\")),\n\t\t\tFormEl(\n\t\t\t\tID(\"tz-form\"),\n\t\t\t\tg.Attr(\"live-change\", cmp.Event(validateTZ)), // c.Event scopes the events to this component.\n\t\t\t\tg.Attr(\"live-submit\", cmp.Event(addTime)),\n\t\t\t\tDiv(\n\t\t\t\t\tP(g.Text(\"Try Europe/London or America/New_York\")),\n\t\t\t\t\tInput(Name(\"tz\")),\n\t\t\t\t\tg.If(state.ValidationError != \"\", Span(g.Text(state.ValidationError))),\n\t\t\t\t),\n\t\t\t\tInput(Type(\"submit\"), g.If(state.ValidationError != \"\", Disabled())),\n\t\t\t),\n\t\t\tDiv(\n\t\t\t\tg.Group(g.Map(len(state.Timezones), func(idx int) g.Node {\n\t\t\t\t\treturn page.Render(state.Timezones[idx])\n\t\t\t\t})),\n\t\t\t),\n\t\t\tScript(Src(\"/live.js\")),\n\t\t},\n\t}).Render(w)\n}", "func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {\n\treturn defaultCtrl.Render(w, r, v)\n}", "func (gm *GraphicsManager) Render(compsToSend *common.Vector) {\n\thandlerIndex := 0\n\tdefer gm.handleClosedGraphicsHandler(handlerIndex)\n\n\t//common.LogInfo.Println(compsToSend)\n\tfor handlerIndex = range gm.graphicsHandlersLink {\n\t\tif gm.graphicsHandlersLink[handlerIndex] == nil {\n\t\t\tcontinue\n\t\t}\n\t\tgm.graphicsHandlersLink[handlerIndex] <- compsToSend\n\t}\n}", "func (gm *GraphicsManager) ForceRender(compsToSend *common.Vector) {\n\thandlerIndex := 0\n\tdefer gm.handleClosedGraphicsHandler(handlerIndex)\n\n\tgm.Render(compsToSend)\n\tfor handlerIndex = range gm.resizelink {\n\t\tif gm.resizelink[handlerIndex] == nil {\n\t\t\tcontinue\n\t\t}\n\t\tgm.resizelink[handlerIndex] <- true\n\t}\n\n\tgm.justForcedARender = true\n\n}", "func (r *syncResponse) Render(w http.ResponseWriter) error {\n\t// Set an appropriate ETag header\n\tif r.eTag != nil {\n\t\tif eTag, err := etag.Hash(r.eTag); err == nil {\n\t\t\tw.Header().Set(\"ETag\", eTag)\n\t\t}\n\t}\n\n\tstatus := http.StatusOK\n\tif !r.success {\n\t\tstatus = http.StatusBadRequest\n\t}\n\n\tif r.headers != nil {\n\t\tfor h, v := range r.headers {\n\t\t\tw.Header().Set(h, v)\n\t\t}\n\t}\n\n\tif r.location != \"\" {\n\t\tw.Header().Set(\"Location\", r.location)\n\t\tif r.code == 0 {\n\t\t\tw.WriteHeader(201)\n\t\t} else {\n\t\t\tw.WriteHeader(r.code)\n\t\t}\n\t}\n\n\treturn json.Write(w, client.ResponseRaw{\n\t\tType: client.SyncResponse,\n\t\tStatus: http.StatusText(status),\n\t\tStatusCode: status,\n\t\tMetadata: r.metadata,\n\t}, false, r.logger)\n}", "func render(c *gin.Context) {\n\t// fill up the list with the current store listing\n\tfmt.Println(\"RENDER ATTACHED\")\n\t// render_active = true\n\tc.Stream(func(w io.Writer) bool {\n\t\tselect {\n\t\tcase msg := <-render_chan:\n\t\t\tdata, _ := json.Marshal(msg)\n\t\t\tc.SSEvent(\"render\", string(data))\n\t\t}\n\t\treturn true\n\t})\n\t// render_active = false\n\tfmt.Println(\"RENDERER DETACHED\")\n}", "func (b *renderSystem) Render(dt float64) {\n\n\tb.renderer.Clear()\n\n\tfor i := 0; i < 100; i++ {\n\t\tl := b.layers[i]\n\t\tif l != nil {\n\t\t\tfor _, renderable := range *l {\n\t\t\t\trenderable.Paint(b.renderer)\n\t\t\t}\n\t\t}\n\t}\n\n\tb.renderer.Present()\n}", "func (ed *Editor) Render() *vecty.HTML {\n\ted.updateStateFromRanges()\n\ted.updateStateFromWarnings()\n\ted.updateStateFromErrors()\n\tutil.Schedule(ed.afterRender)\n\treturn elem.Div(\n\t\tvecty.ClassMap{\"scroller\": true},\n\t\telem.TextArea(\n\t\t\tvecty.ClassMap{\"editor\": true},\n\t\t\tvecty.Property(\"autocapitalize\", \"off\"),\n\t\t\tvecty.Attribute(\"autocomplete\", \"off\"),\n\t\t\tvecty.Attribute(\"autocorrect\", \"off\"),\n\t\t\tvecty.Property(\"autofocus\", true),\n\t\t\tvecty.Property(\"spellcheck\", false),\n\t\t\t//vecty.Text(ed.InitialValue), // only sets the value initially!\n\n\t\t\tevent.KeyDown(ed.handleKeyDown),\n\t\t\tevent.Select(ed.updateSelectionInfo),\n\t\t\tevent.Input(ed.onChange),\n\t\t),\n\t\telem.Div(\n\t\t\tvecty.ClassMap{\"shadow\": true},\n\t\t\tvecty.UnsafeHTML(ed.highlighted),\n\t\t\tevent.ContextMenu(ed.cancelEvent),\n\t\t),\n\t\telem.Style(\n\t\t\tvecty.UnsafeHTML(ed.selLinesCSS),\n\t\t),\n\t\telem.Style(\n\t\t\tvecty.UnsafeHTML(ed.warningsCSS),\n\t\t),\n\t\telem.Style(\n\t\t\tvecty.UnsafeHTML(ed.errorsCSS),\n\t\t),\n\t\tevent.MouseDown(ed.handleScrollerClick),\n\t)\n}", "func (g *Game) Update(display chan<- Frame) {\n\t// apply animations\n\tif g.animator.Step() {\n\t\tg.needsRender = true\n\t}\n\t// render if needed\n\tif g.needsRender {\n\t\tdisplay <- g.Render()\n\t\tg.needsRender = false\n\t}\n}", "func (r *templateRenderer) Render(parameters *internalParameters, chartPath string, valueRenderer ValueRenderer) (testrunner.RunList, error) {\n\tif chartPath == \"\" {\n\t\treturn make(testrunner.RunList, 0), nil\n\t}\n\n\tstate := &renderState{\n\t\ttemplateRenderer: *r,\n\t\tchartPath: chartPath,\n\t\tvalues: valueRenderer,\n\t\tparameters: parameters,\n\t}\n\n\tc, err := chartutil.Load(chartPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// split all found templates into separate charts\n\ttemplates, files := splitTemplates(c.GetTemplates())\n\truns := make(testrunner.RunList, 0)\n\tfor _, tmpl := range files {\n\t\tvalues, metadata, info, err := valueRenderer.Render(r.defaultValues)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tc.Templates = append(templates, tmpl)\n\t\tfiles, err := r.RenderChart(c, parameters.Namespace, values)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttestruns := parseTestrunsFromChart(r.log, files)\n\n\t\tfor _, tr := range testruns {\n\t\t\tmeta := metadata.DeepCopy()\n\t\t\t// Add all repositories defined in the component descriptor to the testrun locations.\n\t\t\t// This gives us all dependent repositories as well as there deployed version.\n\t\t\tif err := testrun_renderer.AddLocationsToTestrun(tr, \"default\", parameters.ComponentDescriptor, true, parameters.AdditionalLocations); err != nil {\n\t\t\t\tr.log.Info(fmt.Sprintf(\"cannot add bom locations: %s\", err.Error()))\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Add runtime annotations to the testrun\n\t\t\taddAnnotationsToTestrun(tr, meta.CreateAnnotations())\n\n\t\t\t// add collect annotation\n\t\t\tmetav1.SetMetaDataAnnotation(&tr.ObjectMeta, common.AnnotationCollectTestrun, \"true\")\n\n\t\t\truns = append(runs, &testrunner.Run{\n\t\t\t\tInfo: info,\n\t\t\t\tTestrun: tr,\n\t\t\t\tMetadata: meta,\n\t\t\t\tRerenderer: state,\n\t\t\t})\n\t\t}\n\n\t}\n\n\treturn runs, nil\n}", "func (r *renderer) Render(w http.ResponseWriter, p ViewModel) {\n\tif r.config.Debug {\n\t\terr := r.initTemplates()\n\t\tif err != nil {\n\t\t\tlog.Printf(err.Error())\n\t\t}\n\t}\n\terr := r.templates.ExecuteTemplate(w, templateName, p)\n\tif err != nil {\n\t\tlog.Fatalln(err.Error())\n\t}\n}", "func (view *View) Render() {\n\tif view.model.restoreFocus {\n\t\timgui.SetNextWindowFocus()\n\t\tview.model.restoreFocus = false\n\t\tview.model.windowOpen = true\n\t}\n\tif view.model.windowOpen {\n\t\timgui.SetNextWindowSizeV(imgui.Vec2{X: 400 * view.guiScale, Y: 300 * view.guiScale}, imgui.ConditionFirstUseEver)\n\t\tif imgui.BeginV(\"Texts\", view.WindowOpen(), imgui.WindowFlagsNoCollapse) {\n\t\t\tview.renderContent()\n\t\t}\n\t\timgui.End()\n\t}\n}", "func (r *ServerWrapperRender) Render(path string, data *gengokit.Data) (io.Reader, error) {\n\tif path != ServerWrapperPath {\n\t\treturn nil, errors.Errorf(\"cannot render unknown file: %q\", path)\n\t}\n\tif r.prev != nil {\n\t\treturn r.prev, nil\n\t}\n\treturn data.ApplyTemplateFromPath(path)\n}", "func ListeningChangeSetRenderer(streamer StackSubscriber, stackName, description string, changes []Renderer, opts RenderOptions) DynamicRenderer {\n\treturn &dynamicTreeComponent{\n\t\tRoot: ListeningResourceRenderer(streamer, stackName, description, ResourceRendererOpts{\n\t\t\tRenderOpts: opts,\n\t\t}),\n\t\tChildren: changes,\n\t}\n}", "func UpdateWidget(res http.ResponseWriter, req *http.Request) {\n\tresp := response.New()\n\n\tresp.Render(res, req)\n}", "func Version(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Cache-Control\", \"must-revalidate\")\n\tw.Header().Set(\"Content-Type\", \"text/plain\")\n\tw.Write([]byte(\"1\"))\n}", "func (r *Renderer) RenderFrame() RenderFrame {\n\tif targetA {return frameB}\n\treturn frameA\n}", "func Render(w http.ResponseWriter, r *http.Request, v Renderer) error {\n\tif err := renderer(w, r, v); err != nil {\n\t\treturn err\n\t}\n\tRespond(w, r, v)\n\treturn nil\n}", "func (tr *Tracker) SetLastConfigRendered(t time.Time) {\n\ttr.status.LastUpdated.LastConfigRendered = t\n}", "func (b *Baa) Render() Renderer {\n\treturn b.GetDI(\"render\").(Renderer)\n}", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func (t Tmpl) Render(wr io.Writer, name string, args interface{}) error {\n\t// Check if app is running on dev mode\n\tif Config.Configuration.IsDev() {\n\n\t\t// Lock mutex\n\t\tt.rw.Lock()\n\t\tdefer t.rw.Unlock()\n\n\t\t// Reload all templates\n\t\tif err := t.LoadTemplates(\"views/\"); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Execute template and return error\n\treturn t.Tmpl.ExecuteTemplate(wr, name, args)\n}", "func Render(c Compo) {\n\tUI(func() { render(c) })\n}", "func (rs *RenderSystem) Update(frameDelta float32) {\n\t// clear the screen\n\twidth, height := rs.Renderer.GetResolution()\n\trs.gfx.Viewport(0, 0, int32(width), int32(height))\n\trs.gfx.ClearColor(0.25, 0.25, 0.25, 1.0)\n\trs.gfx.Clear(graphics.COLOR_BUFFER_BIT | graphics.DEPTH_BUFFER_BIT)\n\n\t// make the projection and view matrixes\n\tprojection := mgl.Perspective(mgl.DegToRad(60.0), float32(width)/float32(height), 1.0, 100.0)\n\tvar view mgl.Mat4\n\tif rs.Camera != nil {\n\t\tview = rs.Camera.GetViewMatrix()\n\t} else {\n\t\tview = mgl.Ident4()\n\t}\n\n\t// draw stuff the visible entities\n\tfor _, e := range rs.visibleEntities {\n\t\tvisibleEntity, okay := e.(RenderableEntity)\n\t\tif okay {\n\t\t\tr := visibleEntity.GetRenderable()\n\t\t\trs.Renderer.DrawRenderable(r, nil, projection, view, rs.Camera)\n\t\t}\n\t}\n\n\t// draw the screen\n\trs.MainWindow.SwapBuffers()\n}", "func (d Dispatcher) Version() (string, error) {\n\theight, err := d.GetBC().GetLatestHeight()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\thashes, err := d.GetBC().GetBlockHashesHex()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tversionBytes, err := helpers.Serialize(NewVersion(GizoVersion, height, hashes))\n\treturn string(versionBytes), nil\n}", "func (c *Components) Render() ([]byte, error) {\n\treturn yaml.Marshal(c)\n}", "func (p *Home) Render() vecty.ComponentOrHTML {\n\treturn elem.Body(p.perspectiveList)\n}", "func (sp *ServiceProcessor) renderService(svc *Service, oldContivSvc *renderer.ContivService,\n\toldBackends []podmodel.ID) error {\n\n\tvar err error\n\tnewContivSvc := svc.GetContivService()\n\tnewBackends := svc.GetLocalBackends()\n\totherContiveServices := sp.otherContivServices(svc)\n\n\t// Render service.\n\tif newContivSvc != nil {\n\t\tif oldContivSvc == nil {\n\t\t\tfor _, renderer := range sp.renderers {\n\t\t\t\tif err = renderer.AddService(newContivSvc); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, renderer := range sp.renderers {\n\t\t\t\tif err = renderer.UpdateService(oldContivSvc, newContivSvc, otherContiveServices); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif oldContivSvc != nil {\n\t\t\tfor _, renderer := range sp.renderers {\n\t\t\t\tif err = renderer.DeleteService(oldContivSvc, otherContiveServices); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Render local Backends.\n\tnewBackendIfs := sp.backendIfs.Copy()\n\tupdateBackends := false\n\t// -> handle new backend interfaces\n\tfor _, newBackend := range newBackends {\n\t\tnew := true\n\t\tfor _, oldBackend := range oldBackends {\n\t\t\tif newBackend == oldBackend {\n\t\t\t\tnew = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif new {\n\t\t\tlocalEp := sp.getLocalEndpoint(newBackend)\n\t\t\tlocalEp.svcCount++\n\t\t\tif localEp.ifName != \"\" && localEp.svcCount == 1 {\n\t\t\t\tnewBackendIfs.Add(localEp.ifName)\n\t\t\t\tupdateBackends = true\n\t\t\t}\n\t\t}\n\t}\n\t// -> handle removed backend interfaces\n\tfor _, oldBackend := range oldBackends {\n\t\tremoved := true\n\t\tfor _, newBackend := range newBackends {\n\t\t\tif newBackend == oldBackend {\n\t\t\t\tremoved = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif removed {\n\t\t\tlocalEp := sp.getLocalEndpoint(oldBackend)\n\t\t\tlocalEp.svcCount--\n\t\t\tif localEp.ifName != \"\" && localEp.svcCount == 0 {\n\t\t\t\tnewBackendIfs.Del(localEp.ifName)\n\t\t\t\tupdateBackends = true\n\t\t\t}\n\t\t}\n\t}\n\t// -> update local backends\n\tif updateBackends {\n\t\tfor _, renderer := range sp.renderers {\n\t\t\terr = renderer.UpdateLocalBackendIfs(sp.backendIfs, newBackendIfs)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tsp.backendIfs = newBackendIfs\n\t}\n\n\treturn err\n}", "func (v *Layer) Render() error {\n\tlogrus.Tracef(\"view.Render() %s\", v.Name())\n\n\t// indicate when selected\n\ttitle := \"Layers\"\n\tisSelected := v.gui.CurrentView() == v.view\n\n\tv.gui.Update(func(g *gocui.Gui) error {\n\t\t// update header\n\t\tv.header.Clear()\n\t\twidth, _ := g.Size()\n\t\theaderStr := format.RenderHeader(title, width, isSelected)\n\t\theaderStr += fmt.Sprintf(\"Cmp\"+image.LayerFormat, \"Size\", \"Command\")\n\t\t_, err := fmt.Fprintln(v.header, headerStr)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// update contents\n\t\tv.view.Clear()\n\t\tfor idx, layer := range v.Layers {\n\n\t\t\tlayerStr := layer.String()\n\t\t\tcompareBar := v.renderCompareBar(idx)\n\n\t\t\tif idx == v.LayerIndex {\n\t\t\t\t_, err = fmt.Fprintln(v.view, compareBar+\" \"+format.Selected(layerStr))\n\t\t\t} else {\n\t\t\t\t_, err = fmt.Fprintln(v.view, compareBar+\" \"+layerStr)\n\t\t\t}\n\n\t\t\tif err != nil {\n\t\t\t\tlogrus.Debug(\"unable to write to buffer: \", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t}\n\t\treturn nil\n\t})\n\treturn nil\n}", "func (vhs *VHS) Render() error {\n\t// Apply Loop Offset by modifying frame sequence\n\tif err := vhs.ApplyLoopOffset(); err != nil {\n\t\treturn err\n\t}\n\n\t// Generate the video(s) with the frames.\n\tvar cmds []*exec.Cmd\n\tcmds = append(cmds, MakeGIF(vhs.Options.Video))\n\tcmds = append(cmds, MakeMP4(vhs.Options.Video))\n\tcmds = append(cmds, MakeWebM(vhs.Options.Video))\n\tcmds = append(cmds, MakeScreenshots(vhs.Options.Screenshot)...)\n\n\tfor _, cmd := range cmds {\n\t\tif cmd == nil {\n\t\t\tcontinue\n\t\t}\n\t\tout, err := cmd.CombinedOutput()\n\t\tif err != nil {\n\t\t\tlog.Println(string(out))\n\t\t}\n\t}\n\n\treturn nil\n}", "func (rs *RenderSystem) Update(dt float64) {\n\tthread.Call(func() {\n\t\trs.prepare()\n\t\tstartShader(rs.Shader)\n\t\trs.Shader.Setup(*rs.Camera)\n\t\tfor _, e := range rs.BaseSystem.Entities() {\n\t\t\trc := e.Component(RenderComponentName).(*RenderComponent)\n\t\t\trs.Shader.Render(*rc)\n\t\t\trender(*rc)\n\t\t}\n\t\tstopShader()\n\n\t\t//as last, render our skybox\n\t\trs.renderSkybox()\n\t})\n}", "func (v *View) Renderer(matcher func(instance.Description) bool) (func(w io.Writer, v interface{}) error, error) {\n\ttagsView, err := template.NewTemplate(template.ValidURL(v.tagsTemplate), v.options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpropertiesView, err := template.NewTemplate(template.ValidURL(v.propertiesTemplate), v.options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn func(w io.Writer, result interface{}) error {\n\n\t\tinstances, is := result.([]instance.Description)\n\t\tif !is {\n\t\t\treturn fmt.Errorf(\"not []instance.Description\")\n\t\t}\n\n\t\tif !v.quiet {\n\t\t\tif v.viewTemplate != \"\" {\n\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\n\", \"ID\", \"VIEW\")\n\t\t\t} else if v.properties {\n\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\t%-30s\\t%-s\\n\", \"ID\", \"LOGICAL\", \"TAGS\", \"PROPERTIES\")\n\n\t\t\t} else {\n\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\t%-s\\n\", \"ID\", \"LOGICAL\", \"TAGS\")\n\t\t\t}\n\t\t}\n\t\tfor _, d := range instances {\n\n\t\t\t// TODO - filter on the client side by tags\n\t\t\tif len(v.TagFilter()) > 0 {\n\t\t\t\tif hasDifferentTag(v.TagFilter(), d.Tags) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\tif matcher != nil {\n\t\t\t\tif !matcher(d) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlogical := \" - \"\n\t\t\tif d.LogicalID != nil {\n\t\t\t\tlogical = string(*d.LogicalID)\n\t\t\t}\n\n\t\t\tif v.viewTemplate != \"\" {\n\n\t\t\t\tcolumn := \"-\"\n\t\t\t\tif view, err := d.View(v.viewTemplate); err == nil {\n\t\t\t\t\tcolumn = view\n\t\t\t\t} else {\n\t\t\t\t\tcolumn = err.Error()\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\n\", d.ID, column)\n\n\t\t\t} else {\n\n\t\t\t\ttagViewBuff := \"\"\n\t\t\t\tif v.tagsTemplate == \"*\" {\n\t\t\t\t\t// default -- this is a hack\n\t\t\t\t\tprintTags := []string{}\n\t\t\t\t\tfor k, v := range d.Tags {\n\t\t\t\t\t\tprintTags = append(printTags, fmt.Sprintf(\"%s=%s\", k, v))\n\t\t\t\t\t}\n\t\t\t\t\tsort.Strings(printTags)\n\t\t\t\t\ttagViewBuff = strings.Join(printTags, \",\")\n\t\t\t\t} else {\n\t\t\t\t\ttagViewBuff = renderTags(d.Tags, tagsView)\n\t\t\t\t}\n\n\t\t\t\tif v.properties {\n\n\t\t\t\t\tif v.quiet {\n\t\t\t\t\t\t// special render only the properties\n\t\t\t\t\t\tfmt.Printf(\"%s\", renderProperties(d.Properties, propertiesView))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\t%-30s\\t%-s\\n\", d.ID, logical, tagViewBuff,\n\t\t\t\t\t\t\trenderProperties(d.Properties, propertiesView))\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"%-30s\\t%-30s\\t%-s\\n\", d.ID, logical, tagViewBuff)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}, nil\n}", "func (s *State) Update() {\n\t// fmt.Println(\"update\")\n\ts.render()\n}", "func (rf RendererFunc) Render(w io.Writer, v interface{}) error { return rf(w, v) }", "func (sh *ShaderStd) PostRender() error { return nil }", "func (v *Status) Render() error {\n\tlogrus.Tracef(\"view.Render() %s\", v.Name())\n\n\tv.gui.Update(func(g *gocui.Gui) error {\n\t\tv.view.Clear()\n\n\t\tvar selectedHelp string\n\t\tif v.selectedView != nil {\n\t\t\tselectedHelp = v.selectedView.KeyHelp()\n\t\t}\n\n\t\t_, err := fmt.Fprintln(v.view, v.KeyHelp()+selectedHelp+format.StatusNormal(\"▏\"+strings.Repeat(\" \", 1000)))\n\t\tif err != nil {\n\t\t\tlogrus.Debug(\"unable to write to buffer: \", err)\n\t\t}\n\n\t\treturn err\n\t})\n\treturn nil\n}", "func (rc *RenderCore) updateElement(_parent interface{}, parent *Element, new, old interface{}, index int, inReplaced bool) error {\n\t// if element has created\n\tif old == nil {\n\t\trc.Add(&RenderTask{\n\t\t\tType: CreateType,\n\t\t\tNew: new,\n\t\t\tParent: parent,\n\t\t\tNodeParent: _parent,\n\t\t\tIgnoreHooks: inReplaced,\n\t\t})\n\n\t\treturn nil\n\t}\n\n\t_childes := rc.BE.ChildNodes(_parent)\n\n\tvar _el interface{}\n\tif len(_childes) > index {\n\t\t_el = _childes[index]\n\t} else {\n\t\tif IsElement(old) {\n\t\t\t_el = I2E(old).BEElement()\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\t// if element was deleted\n\tif new == nil {\n\t\trc.Add(&RenderTask{\n\t\t\tType: DeleteType,\n\t\t\tNodeParent: _parent,\n\t\t\tParent: parent,\n\t\t\tNodeOld: _el,\n\t\t\tOld: old,\n\t\t\tIgnoreHooks: inReplaced,\n\t\t})\n\n\t\treturn nil\n\t}\n\n\t// if element has Changed\n\tisChanged, canGoDeeper, err := Changed(new, old)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isChanged {\n\t\trc.Add(&RenderTask{\n\t\t\tType: ReplaceType,\n\t\t\tNodeParent: _parent,\n\t\t\tNodeOld: _el,\n\t\t\tParent: parent,\n\t\t\tNew: new,\n\t\t\tOld: old,\n\t\t\tReplaceCanGoDeeper: canGoDeeper,\n\t\t\tIgnoreHooks: inReplaced,\n\t\t})\n\t}\n\tif !canGoDeeper {\n\t\treturn nil\n\t}\n\n\tnewE := new.(*Element)\n\toldE := old.(*Element)\n\tif newE.UUID != oldE.UUID {\n\t\tnewE.UUID = oldE.UUID // little hack\n\t}\n\n\t// if old and new is equals and they have html directives => they are two commons elements\n\tif oldE.HTML.Render != nil && newE.HTML.Render != nil {\n\t\treturn nil\n\t}\n\n\tvar oldChildes []interface{}\n\tif newE.IsPointer {\n\t\toldChildes = newE.OldChildes\n\t} else {\n\t\toldChildes = oldE.Childes\n\t}\n\n\terr = rc.UpdateElementChildes(_el, newE, newE.Childes, oldChildes, isChanged)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif isChanged && !inReplaced {\n\t\trc.Add(&RenderTask{\n\t\t\tType: ReplaceHooks,\n\t\t\tNodeParent: _parent,\n\t\t\tNodeOld: _el,\n\t\t\tParent: parent,\n\t\t\tNew: new,\n\t\t\tOld: old,\n\t\t})\n\t}\n\n\treturn nil\n}", "func (o AppIngressTrafficWeightOutput) LatestRevision() pulumi.BoolPtrOutput {\n\treturn o.ApplyT(func(v AppIngressTrafficWeight) *bool { return v.LatestRevision }).(pulumi.BoolPtrOutput)\n}", "func (trd *trxDispatcher) updateLastSeenBlock() {\n\t// get the current value\n\tlsb := trd.blkObserver.Load()\n\tlog.Noticef(\"last seen block is #%d\", lsb)\n\n\t// make the change in the database so the progress persists\n\terr := repo.UpdateLastKnownBlock((*hexutil.Uint64)(&lsb))\n\tif err != nil {\n\t\tlog.Errorf(\"could not update last seen block; %s\", err.Error())\n\t}\n}", "func (c *HBComp) logVersion() {\n\tnow := time.Now()\n\tif now.Sub(c.lastVersionLogTime) >= c.app.VersionLogPeriod {\n\t\tc.Log.Info(c.app.InvocationArgs)\n\t\tc.lastVersionLogTime = now\n\t}\n}", "func (e *Element) Reconcile(oldComp Component) {\n\tfor _, l := range e.EventListeners {\n\t\tl.wrapper = func(jsEvent *js.Object) {\n\t\t\tif l.callPreventDefault {\n\t\t\t\tjsEvent.Call(\"preventDefault\")\n\t\t\t}\n\t\t\tif l.callStopPropagation {\n\t\t\t\tjsEvent.Call(\"stopPropagation\")\n\t\t\t}\n\t\t\tl.Listener(&Event{Target: jsEvent.Get(\"target\")})\n\t\t}\n\t}\n\n\tif oldElement, ok := oldComp.(*Element); ok && oldElement.TagName == e.TagName {\n\t\te.node = oldElement.node\n\t\tfor name, value := range e.Properties {\n\t\t\tvar oldValue interface{}\n\t\t\tswitch name {\n\t\t\tcase \"value\":\n\t\t\t\toldValue = e.node.Get(\"value\").String()\n\t\t\tcase \"checked\":\n\t\t\t\toldValue = e.node.Get(\"checked\").Bool()\n\t\t\tdefault:\n\t\t\t\toldValue = oldElement.Properties[name]\n\t\t\t}\n\t\t\tif value != oldValue {\n\t\t\t\te.node.Set(name, value)\n\t\t\t}\n\t\t}\n\t\tfor name := range oldElement.Properties {\n\t\t\tif _, ok := e.Properties[name]; !ok {\n\t\t\t\te.node.Set(name, nil)\n\t\t\t}\n\t\t}\n\n\t\tstyle := e.node.Get(\"style\")\n\t\tfor name, value := range e.Style {\n\t\t\tstyle.Call(\"setProperty\", name, value)\n\t\t}\n\t\tfor name := range oldElement.Style {\n\t\t\tif _, ok := e.Style[name]; !ok {\n\t\t\t\tstyle.Call(\"removeProperty\", name)\n\t\t\t}\n\t\t}\n\n\t\tfor _, l := range oldElement.EventListeners {\n\t\t\te.node.Call(\"removeEventListener\", l.Name, l.wrapper)\n\t\t}\n\t\tfor _, l := range e.EventListeners {\n\t\t\te.node.Call(\"addEventListener\", l.Name, l.wrapper)\n\t\t}\n\n\t\t// TODO better list element reuse\n\t\tfor i, newChild := range e.Children {\n\t\t\tif i >= len(oldElement.Children) {\n\t\t\t\tnewChild.Reconcile(nil)\n\t\t\t\te.node.Call(\"appendChild\", newChild.Node())\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\toldChild := oldElement.Children[i]\n\t\t\tnewChild.Reconcile(oldChild)\n\t\t\treplaceNode(newChild.Node(), oldChild.Node())\n\t\t}\n\t\tfor i := len(e.Children); i < len(oldElement.Children); i++ {\n\t\t\tremoveNode(oldElement.Children[i].Node())\n\t\t}\n\t\treturn\n\t}\n\n\te.node = js.Global.Get(\"document\").Call(\"createElement\", e.TagName)\n\tfor name, value := range e.Properties {\n\t\te.node.Set(name, value)\n\t}\n\tfor name, value := range e.Dataset {\n\t\te.node.Get(\"dataset\").Set(name, value)\n\t}\n\tstyle := e.node.Get(\"style\")\n\tfor name, value := range e.Style {\n\t\tstyle.Call(\"setProperty\", name, value)\n\t}\n\tfor _, l := range e.EventListeners {\n\t\te.node.Call(\"addEventListener\", l.Name, l.wrapper)\n\t}\n\tfor _, c := range e.Children {\n\t\tc.Reconcile(nil)\n\t\te.node.Call(\"appendChild\", c.Node())\n\t}\n}", "func (r *Reflector) rewatchResourceVersion() string {\n\tr.lastSyncResourceVersionMutex.RLock()\n\tdefer r.lastSyncResourceVersionMutex.RUnlock()\n\tif r.isLastSyncResourceVersionUnavailable {\n\t\t// initial stream should return data at the most recent resource version.\n\t\t// the returned data must be consistent i.e. as if served from etcd via a quorum read\n\t\treturn \"\"\n\t}\n\treturn r.lastSyncResourceVersion\n}", "func updateChildComponentRenderable(childRenderable *fizzle.Renderable, childComp *component.ChildRef) {\n\t// push all settings from the child component to the renderable\n\tchildRenderable.Location = childComp.Location\n\tchildRenderable.Scale = childComp.Scale\n\tif childComp.RotationDegrees != 0.0 {\n\t\tchildRenderable.LocalRotation = mgl.QuatRotate(mgl.DegToRad(childComp.RotationDegrees), childComp.RotationAxis)\n\t}\n}", "func (g userGists) Render() gr.Component {\n\n\telem := el.Div()\n\n\tif s := g.State().Interface(\"gists\"); s != nil {\n\t\t// The nice Gist type is lost once we entered the JavaScript world.\n\t\t//\n\t\t// What we get now is:\n\t\t//\n\t\t// []interface{} with the individual Gists as map[string]interface{}\n\t\t//\n\t\t// Let that serve as a note to self that this may not be the optimal way.\n\t\t// I imagine most of the UI will happen in JavaScript and the business logic\n\t\t// and here in Go \"all\" the orchestration, including injecting data required\n\t\t// by the components.\n\t\tgists := s.([]interface{})\n\n\t\ttable := el.Table(\n\t\t\tgr.CSS(\"table\", \"table-striped\"),\n\t\t\tgr.Style(\"width\", \"50%\"),\n\t\t\tel.TableHead(el.TableRow(\n\t\t\t\tel.TableHeader(gr.Text(\"Description\")),\n\t\t\t\tel.TableHeader(gr.Text(\"URL\")),\n\t\t\t)))\n\n\t\tbody := el.TableBody()\n\n\t\tfor _, g := range gists {\n\t\t\ttr := tableRow(g)\n\t\t\ttr.Modify(body)\n\t\t}\n\n\t\t// TODO(bep) \"body modifies table\" doesn't sound right/good. Rename ...\n\t\tbody.Modify(table)\n\t\ttable.Modify(elem)\n\t}\n\n\treturn examples.Example(\"Ajax (some random Gists)\", elem)\n\n}", "func (t *TemplateRenderable) Render(_ ...string) string {\n\treturn string(t.cache.Bytes())\n}", "func (e *EndComponent) Version() string {\n\treturn \"alpha\"\n}", "func (obj *material) Render(\n\tdelta time.Duration,\n\tpos Position,\n\torientation Orientation,\n\tactiveScene Scene,\n\tprogram uint32,\n) error {\n\t// use the program:\n\tgl.UseProgram(program)\n\n\t// loop the layers:\n\tfor _, oneLayer := range obj.layers {\n\t\terr := oneLayer.Render(delta, pos, orientation, activeScene, program)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// fetch the unform variable on the alpha, and update it:\n\talphaValue := obj.alpha.Value()\n\talphaVar := obj.alpha.Variable()\n\talphaVarName := fmt.Sprintf(glStrPattern, alphaVar)\n\talphaVarUniform := gl.GetUniformLocation(program, gl.Str(alphaVarName))\n\tgl.Uniform1f(alphaVarUniform, alphaValue)\n\n\t// update the viewport:\n\trect := obj.viewport.Rectangle()\n\trectPos := rect.Position()\n\trectDim := rect.Dimension()\n\tviewportVar := obj.viewport.Variable()\n\tviewportVarname := fmt.Sprintf(glStrPattern, viewportVar)\n\tviewportUiform := gl.GetUniformLocation(program, gl.Str(viewportVarname))\n\tgl.Uniform4i(viewportUiform, int32(rectPos.X()), int32(rectPos.Y()), int32(rectDim.X()), int32(rectDim.Y()))\n\n\treturn nil\n}", "func (info *componentInfo) updateComponent(step float32, runtime *Runtime, context *Context) {\n\tif info.Active == 0 && info.Start != nil {\n\t\truntime.workers.Run(func() {\n\t\t\tinfo.Start.Start(context)\n\t\t\tinfo.Active += 1\n\t\t})\n\t} else if info.Update != nil {\n\t\truntime.workers.Run(func() {\n\t\t\tinfo.Update.Update(context)\n\t\t\tinfo.Active += 1\n\t\t})\n\t}\n}", "func (m *MockInterface) Render(client.RenderOptions) ([]byte, error) {\n\treturn nil, nil\n}", "func (l Layout) DebugRender(win *pixelgl.Window) {\n\tfor key := range l.Panels {\n\t\tpanel := l.CreatePanel(key)\n\t\tpanel.Draw(win)\n\t}\n\n\t//temp camera matrix\n\t//cam := pixel.IM.Scaled(l.centerPos, 1.0).Moved(l.centerPos)\n\t//win.SetMatrix(cam)\n}", "func (v *Component) ComponentWillUpdate(nextProps *Map, nextState *Map) {}", "func (o EnvironmentDaprComponentOutput) Version() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *EnvironmentDaprComponent) pulumi.StringOutput { return v.Version }).(pulumi.StringOutput)\n}", "func (c *stackComponent) Render(out io.Writer) (numLines int, err error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\n\treturn renderComponents(out, c.resources)\n}", "func (c *SceneController) OnRender() {\n}", "func (mrt *MockRendererTxn) Render(pod podmodel.ID, podIP *net.IPNet, ingress []*renderer.ContivRule, egress []*renderer.ContivRule, removed bool) renderer.Txn {\n\tmrt.Log.WithFields(logging.Fields{\n\t\t\"renderer\": mrt.renderer.name,\n\t\t\"pod\": pod,\n\t\t\"IP\": podIP,\n\t\t\"ingress\": ingress,\n\t\t\"egress\": egress,\n\t\t\"removed\": removed,\n\t}).Debug(\"Mock RendererTxn Render()\")\n\tif removed {\n\t\tif _, hasPod := mrt.config[pod]; hasPod {\n\t\t\tdelete(mrt.config, pod)\n\t\t}\n\t} else {\n\t\tmrt.config[pod] = &PodConfig{ip: podIP, ingress: ingress, egress: egress}\n\t}\n\treturn mrt\n}", "func (c *ZeroContext) Render(s markup.Sync) {\n\tlog.Infof(\"%v rendering: %v\", s.Scope, s.Node.Markup())\n}", "func (h *History) Newer(buf *Buffer) (new *Buffer, changed bool) {\n\tif h.selected >= len(h.tmp)-1 {\n\t\treturn buf, false\n\t}\n\th.tmp[h.selected] = buf.Text()\n\n\th.selected++\n\tnew = NewBuffer()\n\tnew.InsertText(h.tmp[h.selected], false, true)\n\treturn new, true\n}", "func (o GetAppIngressTrafficWeightOutput) LatestRevision() pulumi.BoolOutput {\n\treturn o.ApplyT(func(v GetAppIngressTrafficWeight) bool { return v.LatestRevision }).(pulumi.BoolOutput)\n}", "func (l *LiveComponent) Mount(a *LiveTimeChannel) {\n\tl.Component.BeforeMount(l)\n\tl.IsMounted = true\n\tl.LifeTimeChannel = a\n\tl.Component.Mounted(l)\n}", "func (o ApplicationStatusOperationStateSyncResultOutput) Revision() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateSyncResult) string { return v.Revision }).(pulumi.StringOutput)\n}", "func TestDiffSame(t *testing.T) {\n\tloadTemplates()\n\tfmt.Println(\"TestDiffSame...\")\n\tdom1 := &element.DOM{View: element.View{Children: make([]*element.View, 0), Template: \"base.html\", Provides: \"html\", Model: &element.Model{MAP: make(map[string]interface{})}}, Id: \"1\"}\n\tdom1.IdMap = make(map[string]*element.View)\n\tdom1.IdMap[dom1.View.Provides] = &dom1.View\n\tdom2 := CopyDom(*dom1)\n\tpatches := Diff(&dom1.View, &dom2.View)\n\tif len(patches) != 0 {\n\t\tt.Error(\"Patches generated for same DOM\")\n\t\tt.Fail()\n\t}\n\t// fmt.Printf(\"\\ndom1: %+v\\n\", dom1.IdTree)\n\t// fmt.Printf(\"\\ndom2: %+v\\n\", dom1.IdTree)\n}", "func update(vs *ViewServer, primary string, backup string){\n\tvs.currentView.Viewnum += 1\n\tvs.currentView.Primary = primary\n\tvs.currentView.Backup = backup\n\tvs.idleServer = \"\"\n\tvs.primaryACK = false\n\tvs.backupACK = false\n}", "func Render(files [][]byte, maxIt uint, debug bool) (\n\t[]byte, error,\n) {\n\tinfl, debugParse, err := parseFiles(files)\n\tif err != nil {\n\t\tif debug {\n\t\t\twriteDebug(\"parsing\", debugParse)\n\t\t}\n\t\treturn []byte{}, err\n\t}\n\tres, debugRender, err := renderTmpl(infl, maxIt)\n\tif err != nil {\n\t\tif debug {\n\t\t\twriteDebug(\"render\", debugRender)\n\t\t}\n\t\treturn []byte{}, err\n\t}\n\treturn res, nil\n}", "func (e *Element) Render() string {\n\treturn strings.Join(e.renderConnections(), \"\\n\")\n}", "func newRender() *Render {\n\tr := new(Render)\n\treturn r\n}", "func (chs *ChartChangeSync) updateObservedGeneration(hr helmfluxv1.HelmRelease) error {\n\thrClient := chs.ifClient.HelmV1().HelmReleases(hr.Namespace)\n\n\treturn status.SetObservedGeneration(hrClient, hr, hr.Generation)\n}", "func (pb *PBServer) tick() {\n\n newview, err := pb.vs.Ping(pb.view.Viewnum)\n if err != nil {\n fmt.Printf(\"view serivice unreachable!, error %s\\n\", err)\n return;\n }\n\n if pb.view.Viewnum != newview.Viewnum {\n fmt.Printf(\"view changed from \\n%s ==>\\n%s\\n\",pb.view, newview)\n if (pb.view.Primary == pb.me &&\n newview.Primary == pb.me &&\n pb.view.Backup != newview.Backup &&\n newview.Backup != \"\") {\n // backup changes and I'm still primary \n pb.view = newview\n fmt.Printf(\"new backup is %s\\n\", newview.Backup)\n pb.syncWithBackup()\n }\n }\n // only when pb is in the view, proceed to new view\n if pb.me == newview.Primary || pb.me == newview.Backup {\n pb.view = newview\n } else {\n fmt.Printf(\"I'm not in the view, keep trying\\n\")\n }\n}", "func (r *Renderer) Update(t int64) {\n\tdefer r.SwitchBuffer()\n\n\t// any world logic can go in here\n\tframe := r.TargetFrame()\n\tframe.Clear(0) // shouldn't be needed when rendering complete scenes\n\n\tbuf := frame.bmp\n\n\t// Update scene\n\tr.scene.Advance(t)\n\tr.scene.Camera.Position = Vec3{\n\t //math.Cos(r.scene.Time/3)*10, 0, -math.Sin(r.scene.Time/3)*5 + 8,\n\t\t//math.Cos(r.scene.Time/3)*4, 0, -math.Sin(r.scene.Time/3)*4,\n\n\t\t//-5,(math.Sin(r.scene.Time/3)+1.0) * 2.5,-5,\n\t\tmath.Cos(r.scene.Time/3)*4, (math.Sin(r.scene.Time/6)+1.0) * 2.5, -math.Sin(r.scene.Time/3)*4,\n\t}\n\tr.scene.Camera.Yaw = math.Pi + (math.Sin(r.scene.Time)*0.2) // 0 is facing +Z, pi is facing -Z\n\tr.scene.Camera.Pitch = math.Sin(r.scene.Time/6)*0.1\n\n\tr.scene.Camera.Target = Vec3{\n\t\t0,0,0,\n\t\t//0,math.Cos(r.scene.Time), 0,\n\t\t//math.Cos(r.scene.Time/6)*3,1,0,\n\t}\n\n\t// Do the transforms (scene & perspective)\n\tpoints := r.scene.ProjectPoints(float64(frame.Width), float64(frame.Height))\n\n\t// Sort geometry far to near\n\tgeom := r.scene.Geometry\n\ttriangles := make([]*RefTriangle, len(geom))\n\tfor i := 0; i < len(geom); i++ {\n\t\ttriangles[i] = &geom[i]\n\t}\n\tsort.Slice(triangles, func(i, j int) bool {\n\t\ta := triangles[i]; b := triangles[j]\n\n\t\taveA := points[a.A].Z+points[a.B].Z+points[a.C].Z\n\t\taveB := points[b.A].Z+points[b.B].Z+points[b.C].Z\n\t\treturn aveA < aveB\n\t})\n\n\t// Render geometry\n\tend := len(triangles)\n\tfor i := 0; i < end; i++ {\n\t\ttri := triangles[i]\n\n\t\ttex := r.scene.Textures[tri.Tex]\n\t\ta := points[tri.A]\n\t\tb := points[tri.B]\n\t\tc := points[tri.C]\n\n\t\tif a.Z > 0 || b.Z > 0 || c.Z > 0 {\n\t\t\t// Should check if any are in front and do clipping. But not yet\n\t\t\tbreak // we should be drawing in order, so reject anything behind the camera\n\t\t}\n\n\t\tTextureTriangle(a,b,c, tex, &buf, frame.Width, frame.Height)\n\t}\n}", "func (self *StraightLineTrack) Render(render chan Object) {\n\tfor _, val := range self.Childs() {\n\t\trender <- val\n\t}\n}", "func (g *Graph) Render() *ebiten.Image {\n\tif g.simulation.IsPaused() {\n\t\treturn g.graphImage\n\t}\n\n\tvar img *ebiten.Image\n\tif g.shouldRefresh() {\n\t\timg = g.renderAll()\n\t} else if g.shouldAddBar() {\n\t\timg = g.renderNewBar()\n\t} else {\n\t\treturn g.graphImage\n\t}\n\n\tg.graphImage = ebiten.NewImage(realGraphWidth, realGraphHeight)\n\tg.graphImage.DrawImage(img, nil)\n\n\treturn img\n}", "func (c *ZtunnelComponent) RenderManifest() (string, error) {\n\treturn renderManifest(c, c.CommonComponentFields)\n}", "func (mock *TemplateRendererMock) SetReturnRender(r0 string, r1 error) *TemplateRendererMock {\n\tmock.impl.Render = func(string, interface{}) (string, error) {\n\t\treturn r0, r1\n\t}\n\treturn mock\n}", "func (svc *Compiler) Version() string {\n\tval, err := svc.ctx.RunScript(\"svelte.VERSION\", \"version_call\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn val.String()\n}", "func (o ApplicationStatusOperationStateOperationSyncOutput) Revision() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusOperationStateOperationSync) *string { return v.Revision }).(pulumi.StringPtrOutput)\n}", "func (r *Document) LatestVersion() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"latestVersion\"])\n}", "func (o ApplicationStatusSyncComparedToSourceKustomizeOutput) Version() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ApplicationStatusSyncComparedToSourceKustomize) *string { return v.Version }).(pulumi.StringPtrOutput)\n}" ]
[ "0.59645724", "0.56659704", "0.5490005", "0.53410953", "0.53156286", "0.51906294", "0.50233555", "0.5009566", "0.4963389", "0.49517462", "0.4896993", "0.48948595", "0.48684895", "0.4863019", "0.48010954", "0.47940645", "0.47808796", "0.4780281", "0.4766615", "0.47607514", "0.47581813", "0.47332183", "0.4698787", "0.46850193", "0.46604463", "0.46532935", "0.46380526", "0.46373448", "0.46102166", "0.4606862", "0.46037272", "0.45970982", "0.4596949", "0.45776832", "0.4573423", "0.4568027", "0.45678893", "0.45560762", "0.4554898", "0.4550867", "0.45352265", "0.4531408", "0.45304865", "0.45204324", "0.45075384", "0.45075384", "0.4505951", "0.45045695", "0.44989404", "0.4494914", "0.44935918", "0.44901544", "0.4478492", "0.44658336", "0.44549045", "0.44435263", "0.443418", "0.44257295", "0.44193926", "0.44179738", "0.44066456", "0.44051114", "0.44028172", "0.44011748", "0.43816337", "0.43807977", "0.4373518", "0.43704948", "0.43610814", "0.4360723", "0.435662", "0.43508047", "0.43460378", "0.4331974", "0.43313992", "0.4325485", "0.4325449", "0.43232659", "0.4320313", "0.43197656", "0.43145025", "0.4312503", "0.42963216", "0.42826188", "0.42799062", "0.42703265", "0.42639005", "0.42633402", "0.42621684", "0.42593232", "0.42559174", "0.42549118", "0.42546263", "0.4247336", "0.42433807", "0.4236867", "0.42367432", "0.4232071", "0.42287117", "0.42284033" ]
0.7247001
0
create new user from json file name
func NewUsers(filename string) (Users, error) { file, err := os.Open(filename) if err != nil { return nil, errors.Wrap(err, "Unable to open Json File.") } defer file.Close() // Todo use streams/pipe dataInBytes, err := io.ReadAll(file) if err != nil { return nil, errors.Wrap(err, "Error occurred in reading bytes from file.") } var users Users err = json.Unmarshal(dataInBytes, &users) if err != nil { return nil, errors.Wrap(err, "Error occurred in unmarshing json.") } return users, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (t *OpetCode) createUser(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 2 {\n return shim.Error(\"Incorrect number of arguments. Expecting 2\")\n }\n\n uid := args[0]\n json_props := args[1]\n user_key, _ := APIstub.CreateCompositeKey(uid, []string{USER_KEY})\n\n if _, err := t.loadUser(APIstub, user_key); err == nil {\n return shim.Error(\"Account already exists\")\n }\n new_user := new(User)\n new_user.Uid = uid\n new_user.Data = make(map[string]string)\n err := json.Unmarshal([]byte(json_props), &new_user.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_user_json, _ := json.Marshal(new_user)\n APIstub.PutState(user_key, new_user_json)\n\n return shim.Success(nil)\n}", "func createJSONFile() {\n\tusers := []User{\n\t\t{Username: \"Thao Ho\", Password: \"change me\", Email: \"[email protected]\"},\n\t\t{Username: \"Thao Nhi\", Password: \"change me\", Email: \"[email protected]\"},\n\t}\n\n\tdb := UserDb{Users: users, Type: \"Simple\"}\n\n\t//fmt.Println(users)\n\tvar buf = new(bytes.Buffer)\n\n\tenc := json.NewEncoder(buf)\n\tenc.Encode(db)\n\tf, err := os.Create(\"user.db.json\")\n\tif nil != err {\n\t\tlog.Fatalln(err)\n\t}\n\tdefer f.Close()\n\tio.Copy(f, buf) // can use the command jq '.' user.db.json in terminal commands to format the json file\n}", "func createNewUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tvar userInfo UserBody\n\t//decode the json object and store the values in userInfo\n\terr := json.NewDecoder(r.Body).Decode(&userInfo)\n\tif err != nil {\n\t\tfmt.Println(\"ERROR DECODING JSON OBJ FROM CREATE NEW USER\")\n\t}\n\tresult := post.CreateUser(params[\"id\"], userInfo.FirstName, userInfo.LastName, userInfo.Email)\n\tjson.NewEncoder(w).Encode(map[string]bool{\n\t\t\"result\": result,\n\t})\n}", "func db_register(user User) {\n fmt.Println(\"JSON DATA:\")\n newUserBytes := db_user_to_JSON(user)\n fmt.Println(string(newUserBytes)[:])\n \n file_path := path.Join(\"db/users\", strings.ToLower(user.Username)+\".json\")\n\n if _, err := os.Stat(file_path); !os.IsNotExist(err) {\n return\n }\n writeerr := ioutil.WriteFile(file_path, newUserBytes, 0644)\n\n if writeerr != nil {\n panic(writeerr)\n }\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar user User\n\tif err := json.NewDecoder(r.Body).Decode(&user); err != nil {\n\t\tpanic(err)\n\t}\n\t//Todo (Farouk): Mock ID - not safe\n\tuser.ID = strconv.Itoa(rand.Intn(1000000))\n\tusers = append(users, user)\n}", "func createUser(name, password, passwordUpdateRequest string) string {\n\treturn fmt.Sprintf(`{\n \"type\": \"User\",\n \"name\": \"%s\",\n \"credential\": {\n \"type\": \"PasswordCredential\",\n\t\t\"password\": \"%s\",\n\t\t\"passwordUpdateRequest\": \"%s\"\n }\n}`, name, password, passwordUpdateRequest)\n}", "func CreateUser(user *User, userID string) error {\n\tnewUserVal := decodeUser(user)\n\tnewUser := map[string]interface{}{userID: newUserVal}\n\tfileError := file.WriteUsersFile(newUser)\n\tif fileError != nil {\n\t\treturn nil\n\t} else {\n\t\treturn fileError\n\t}\n}", "func CreateNewUser(username, password string) (userID string, err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var checkIfTheUserAlreadyExists = func(username string, userData map[string]interface{}) (err error) {\n var salt = userData[\"_salt\"].(string)\n var loginUsername = userData[\"_username\"].(string)\n\n if SHA256(username, salt) == loginUsername {\n err = createError(020)\n }\n\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n for _, userData := range users {\n err = checkIfTheUserAlreadyExists(username, userData.(map[string]interface{}))\n if err != nil {\n return\n }\n }\n\n var defaults = defaultsForNewUser(username, password)\n userID = defaults[\"_id\"].(string)\n users[userID] = defaults\n\n saveDatabase(data)\n\n return\n}", "func CreateUser(w http.ResponseWriter, r *http.Request){\n\n\t\tu := User{}\n\n\t\terr:= json.NewDecoder(r.Body).Decode(&u)\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\treturn\n\t\t}\n\n\t\t// Checks if name is Empty\n\t\tfmt.Printf(\"name: [%+v]\\n\", u.Name)\n\t\tif u.Name == \"\" {\n\t\t\tfmt.Println(\"Empty string\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\n\t\t//start validation for username\n\t\tvar isStringAlphabetic = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`).MatchString\n\t\tif !isStringAlphabetic(u.Name){\n\t\t\tfmt.Println(\"is not alphanumeric\")\n\t\t\tw.Write([]byte(`{\"status\":\"Invalid Name\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//make the Name Uppercase\n\t\tu.Name = strings.ToUpper(u.Name)\n\n\t\t// check if username already exists\n\t\tuser := userExist(u.Name)\n\t\tif user != (User{}) {\n\t\t\tfmt.Println(\"Name already exists\")\n\t\t\tw.Write([]byte(`{\"status\":\"Name Exists\"}`))\n\t\t\treturn\n\t\t}\n\n\t\t//if it does exist create the user with a random ID and score = 0\n\t\tuuid, err := uuid.NewV4()\n\t\tu.ID = uuid.String()\n\t\tu.Score = 0\n\n\t\tquery := \"INSERT INTO users (id, name, score) VALUES ($1, $2, $3);\"\n\t\t_, err = db.Exec(query, u.ID, u.Name, u.Score);\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t\tw.WriteHeader(201)\n\t\tjson.NewEncoder(w).Encode(u)\n\n}", "func db_JSON_to_user(username string) User {\n file_path := path.Join(\"db/users\", strings.ToLower(username)+\".json\")\n \n dat, err := ioutil.ReadFile(file_path)\n \n if err != nil {\n panic(err.Error())\n }\n \n var user User\n if err := json.Unmarshal(dat, &user); err != nil {\n panic(err)\n }\n return user\n}", "func CreateUser(c *gin.Context) {\n\t//intialize\n\tvar user users.User\n\t//fetch the json request and unmarshal the json file into struct\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := errors.NewBadRequestError(\"invalid json request while creating a user\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\t//send the user struct to the services\n\tresult, err := services.UsersService.CreateUser(user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\tc.JSON(http.StatusCreated, result.Marshall(c.GetHeader(\"X-Public\") == \"true\"))\n}", "func (server Server) CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User // make a user\n\tvar res models.APIResponse // make a response\n\n\terr := json.NewDecoder(r.Body).Decode(&user) //decode the user\n\tif err != nil {\n\t\tlog.Printf(\"Unable to decode the request body. %v\", err)\n\t\tres = models.BuildAPIResponseFail(\"Unable to decode the request body\", nil)\n\t}\n\tif user.Name == \"\" || user.Email == \"\" || user.Password == \"\" {\n\t\tres = models.BuildAPIResponseFail(\"Blank users cannot be created\", nil)\n\t} else {\n\t\tinsertID := insertUser(user, server.db) // call insert user function and pass the note\n\t\tres = models.BuildAPIResponseSuccess(fmt.Sprintf(\"User Created with %d id\", insertID), nil) // format a response object\n\t}\n\tjson.NewEncoder(w).Encode(res)\n\n}", "func CreateUser(c *gin.Context) {}", "func Create(jsonIn []byte) ([]byte, error) {\n\tvar s create\n\tif err := json.Unmarshal(jsonIn, &s); err != nil {\n\t\treturn jsonStatusError(err)\n\t}\n\n\tif passvault.NumRecords() != 0 {\n\t\treturn jsonStatusError(errors.New(\"Vault is already created\"))\n\t}\n\n\t// Validate the Name and Password as valid\n\tif err := validateUser(s.Name, s.Password); err != nil {\n\t\treturn jsonStatusError(err)\n\t}\n\n\tif _, err := passvault.AddNewRecord(s.Name, s.Password, true); err != nil {\n\t\tlog.Printf(\"Error adding record for %s: %s\\n\", s.Name, err)\n\t\treturn jsonStatusError(err)\n\t}\n\n\treturn jsonStatusOk()\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user User\n\tvar b []byte\n\tr.Body.Read(b)\n\terr := json.Unmarshal(b, &user)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(err)\n\t}\n}", "func UserCreate(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := auth.GetUserFromJSON(body)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"User\")\n\t\trespondErr(w, err)\n\t\tlog.Error(string(body[:]))\n\t\treturn\n\t}\n\n\tuuid := uuid.NewV4().String() // generate a new uuid to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\t// Get Result Object\n\tres, err := auth.CreateUser(uuid, urlUser, postBody.FirstName, postBody.LastName, postBody.Organization, postBody.Description,\n\t\tpostBody.Projects, token, postBody.Email, postBody.ServiceRoles, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"duplicate\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"invalid\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func createUser(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tvar user schema.User\n\n\t// we decode our body request params in JSON\n\t_ = json.NewDecoder(r.Body).Decode(&user)\n\n\tresult, err := users.InsertOne(context.TODO(), user)\n\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// we decode the recieved params in JSON\n\tjson.NewEncoder(w).Encode(result)\n}", "func CreateNewUserProfile(path string) error {\n\tnewProfile := &Profile{\n\t\tROOT: struct {\n\t\t\tId string `json:\"id\"`\n\t\t\tDir bool `json:\"dir\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tLevel int `json:\"level\"`\n\t\t\tChildren []string `json:\"children\"`\n\t\t\tParent string `json:\"parent\"`\n\t\t}(struct {\n\t\t\tId string\n\t\t\tDir bool\n\t\t\tName string\n\t\t\tLevel int\n\t\t\tChildren []string\n\t\t\tParent string\n\t\t}{Id: \"ROOT\", Dir: true, Name: \"ROOT\", Level: 0, Children: make([]string, 0), Parent: \"NONE\"}),\n\t}\n\tbyteVal, err := json.Marshal(newProfile)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = ioutil.WriteFile(path, byteVal, 0644)\n\treturn err\n}", "func Create(newuser User) error {\n\t// Check if the new user exists\n\tif stt := Find(newuser.UserID); stt == \"Unavailable\" {\n\t\treturn errors.New(\"Exists\")\n\t}\n\n\tif newuser.CallerID == \"\" {\n\t\tnewuser.CallerID = newuser.UserID\n\t}\n\n\tif newuser.Context == \"\" {\n\t\tnewuser.Context = defaultContext\n\t}\n\n\ttmpl, err := template.ParseFiles(userConfTempl)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tuserconf := userConfPath + newuser.UserID + \".conf\"\n\tf, err := os.OpenFile(userconf, os.O_CREATE|os.O_RDWR, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\n\terr = tmpl.Execute(f, newuser)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = writeToDB(newuser); err != nil {\n\t\treturn err\n\t}\n\n\t// Check if the new user is created\n\tif stt := Find(newuser.UserID); stt == \"Unavailable\" {\n\t\treturn nil\n\t}\n\n\tif err = PjsipReload(); err != nil {\n\t\treturn err\n\t}\n\n\treturn errors.New(\"Failed\")\n}", "func (us *UserStorage) ImportJSON(data []byte) error {\n\tud := []userData{}\n\tif err := json.Unmarshal(data, &ud); err != nil {\n\t\treturn err\n\t}\n\tfor _, u := range ud {\n\t\tpswd := u.Pswd\n\t\tu.Pswd = \"\"\n\t\t_, err := us.AddNewUser(&User{userData: u}, pswd)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func CreateUser(w http.ResponseWriter, req *http.Request) {\n\tbody, err := ioutil.ReadAll(io.LimitReader(req.Body, 1048576))\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := req.Body.Close(); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tvar user User\n\terr = json.Unmarshal(body, &user)\n\tif err != nil {\n\t\tw.WriteHeader(422)\n\t\tlog.Println(err.Error())\n\t}\n\n\tInsertUser(user)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n\tif err := json.NewEncoder(w).Encode(user); err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (h *userHandler) createUser(ctx context.Context, rw http.ResponseWriter, r *http.Request) {\n\n\tvar user = &model.User{}\n\n\terr := json.NewDecoder(r.Body).Decode(user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\n\t}\n\n\tif user.Login == \"\" || user.Password == \"\" {\n\n\t\th.serv.writeResponse(ctx, rw, \"Login or password are empty\", http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\terr = h.registerUser(ctx, user)\n\tif err != nil {\n\n\t\th.serv.writeResponse(ctx, rw, err.Error(), http.StatusBadRequest, nil)\n\n\t\treturn\n\t}\n\n\th.serv.writeResponse(ctx, rw, \"user was created: \"+user.Login, http.StatusCreated, user)\n\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n\tuser := new(User)\n\tuser.Token = validateToken(r.FormValue(\"token\"))\n\tuser.PasswordHash = validatePassHash(r.FormValue(\"passHash\"))\n\tuser.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n\tuser.PublicHash = computePublicHash(user.PublicKey)\n\tuser.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n\tlog.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n\tif !SaveUser(user) {\n\t\thttp.Error(w, \"That username is taken\", http.StatusBadRequest)\n\t}\n}", "func (us *UserStorage) ImportJSON(data []byte) error {\n\tud := []userData{}\n\tif err := json.Unmarshal(data, &ud); err != nil {\n\t\treturn err\n\t}\n\tfor _, u := range ud {\n\t\tpswd := u.Pswd\n\t\tu.Pswd = \"\"\n\t\tif _, err := us.AddNewUser(&User{userData: u}, pswd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func CreateDefaultUser(username, password string) (err error) {\n\n err = checkInit()\n if err != nil {\n return\n }\n\n var users = data[\"users\"].(map[string]interface{})\n // Check if the default user exists\n if len(users) > 0 {\n err = createError(001)\n return\n }\n\n var defaults = defaultsForNewUser(username, password)\n users[defaults[\"_id\"].(string)] = defaults\n saveDatabase(data)\n\n return\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tu := User{}\n\terr := json.NewDecoder(r.Body).Decode(&u)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\n\terr = SaveUser(u.FullName, u.NickName, u.Email, u.Balance)\n\n\tif err != nil {\n\t\thttp.Error(w, http.StatusText(500), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusCreated)\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\tjson.NewDecoder(req.Body).Decode(&u)\n\n\tu.ID = \"007\"\n\n\tuj, err := json.Marshal(u)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tw.Header().Set(\"Contenty-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // STATYS 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func CreateUser(body []byte) error {\n\tkeyVal := make(map[string]string)\n\tjson.Unmarshal(body, &keyVal)\n\n\tuser := models.User{\n\t\tName: keyVal[\"name\"],\n\t\tEmail: keyVal[\"email\"],\n\t\tPassword: keyVal[\"password\"],\n\t}\n\n\terr := repositories.CreateUser(user)\n\n\tif err != nil {\n\t\treturn errors.New(\"EMAIL_ALREADY_IN_USE\")\n\t}\n\n\treturn err\n}", "func (rc *ResourceCommand) createUser(ctx context.Context, client auth.ClientI, raw services.UnknownResource) error {\n\tuser, err := services.UnmarshalUser(raw.Raw)\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\tuserName := user.GetName()\n\texistingUser, err := client.GetUser(userName, false)\n\tif err != nil && !trace.IsNotFound(err) {\n\t\treturn trace.Wrap(err)\n\t}\n\texists := (err == nil)\n\n\tif exists {\n\t\tif !rc.force {\n\t\t\treturn trace.AlreadyExists(\"user %q already exists\", userName)\n\t\t}\n\n\t\t// Unmarshalling user sets createdBy to zero values which will overwrite existing data.\n\t\t// This field should not be allowed to be overwritten.\n\t\tuser.SetCreatedBy(existingUser.GetCreatedBy())\n\n\t\tif err := client.UpdateUser(ctx, user); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tfmt.Printf(\"user %q has been updated\\n\", userName)\n\n\t} else {\n\t\tif err := client.CreateUser(ctx, user); err != nil {\n\t\t\treturn trace.Wrap(err)\n\t\t}\n\t\tfmt.Printf(\"user %q has been created\\n\", userName)\n\t}\n\n\treturn nil\n}", "func init() {\n\tCreateUser(UserObject{\n\t\tFname: \"Debapriya\",\n\t\tLname: \"Das\",\n\t\tAge: 24,\n\t})\n\tCreateUser(UserObject{\n\t\tFname: \"Anuja\",\n\t\tLname: \"Saha\",\n\t\tAge: 21,\n\t})\n}", "func CreateUser(response http.ResponseWriter, request *http.Request) {\n\n\t\n\t\trequest.ParseForm()\n\t\tdecoder := json.NewDecoder(request.Body)\n\t\tvar newUser User\n\t\t\n\t\terr := decoder.Decode(&newUser)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\t\n newUser.Password=hashAndSalt([]byte(newUser.Password))\n\t\t\n\t\tinsertUser(newUser)\n\t\n}", "func Create(c *gin.Context) {\n\tvar user users.User\n\n\t// ShouldBindJSON - read request body and unmarshals the []bytes to user\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\tbdErr := errors.NewBadRequestError(fmt.Sprintf(\"invalid json body: %s\", err.Error()))\n\t\tc.JSON(bdErr.Status, bdErr)\n\t\treturn\n\t}\n\n\tresult, err := services.UserServ.CreateUser(user)\n\tif err != nil {\n\t\tc.JSON(err.Status, err)\n\t\treturn\n\t}\n\n\tisPublic := c.GetHeader(\"X-Public\") == \"true\"\n\tc.JSON(http.StatusCreated, result.Marshall(isPublic))\n}", "func createUser(c *gin.Context) {\n password,_ := HashPassword(c.PostForm(\"password\"))\n\tuser := user{Login: c.PostForm(\"login\"), Password: password}\n\tdb.Save(&user)\n\tc.JSON(http.StatusCreated, gin.H{\"status\": http.StatusCreated, \"message\": \"User item created successfully!\"})\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tenableCors(&w)\n\tvars := mux.Vars(r)\n\tuid := vars[\"uid\"]\n\t//uuid := uuid.New().String()\n\t//ip := strings.Split(r.RemoteAddr, \":\")[0]\n\tfilesFirstore := StructToJSON(userFiles)\n\t_, err := db.Collection(\"users\").Doc(uid).Update(context.Background(), []firestore.Update{{Path: \"rudi\", Value:filesFirstore }})\n\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (us UserService) AddNew(name string, age int) {\n\tu1 := User{Name: name, Age: age}\n\t// Read data from file\n\tallUsers := us.Store.Read()\n\tif len(allUsers) == 0 {\n\t\tallUsers = []byte(\"[]\")\n\t}\n\t// JSON message to Struct\n\tout := jsontoStruct(allUsers)\n\t// Add new user\n\tout = append(out, u1)\n\t// Struct to JSON message\n\tcontent, _ := json.Marshal(out)\n\t// Save data to file\n\tus.Store.Write(content)\n}", "func Create(c *gin.Context) {\n\tvar user models.User\n\tif err := c.ShouldBindJSON(&user); err != nil {\n\t\trestErr := rest_errors.NewBadRequestError(\"invalid json body\")\n\t\tc.JSON(restErr.Status, restErr)\n\t\treturn\n\t}\n\n\tresult, saveErr := services.UsersService.CreateUser(user)\n\tif saveErr != nil {\n\t\tc.JSON(saveErr.Status, saveErr)\n\t\treturn\n\t}\n\n\tc.JSON(http.StatusCreated, result.Marshal(c.GetHeader(\"X-Public\") == \"false\"))\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\trequestBody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tvar user models.User\n\tif err = json.Unmarshal(requestBody, &user); err != nil {\n\t\tlog.Fatal(\"Error\")\n\t}\n\n\tdb, err := database.OpenDbConnection()\n\tif err != nil {\n\t\tlog.Fatal(\"error\")\n\t}\n\n\trepository := repositories.UserRepository(db)\n\trepository.Create(user)\n}", "func CreateUserHandler(w http.ResponseWriter, r *http.Request) {\n\n\tuser := &models.User{}\n\terr := json.NewDecoder(r.Body).Decode(user) //decode the request body into struct and fail if any error occur\n\tif err != nil {\n\t\tfmt.Println(\"Debug user CreateUserHandler:\", err)\n\t\tutils.Respond(w, utils.Message(false, \"Invalid request\"))\n\t\treturn\n\t}\n\n\tresp := user.Create() //Create user\n\tutils.Respond(w, resp)\n}", "func createJSONFile (outputDir string, fileName string) *os.File {\n\n file, err := os.Create(filepath.Join(outputDir, fileName+jsonExt)) \n check(err) \n\n return file\n}", "func (d *DecodeService) New(w http.ResponseWriter, r *http.Request) {\n\tvar req request.UserName\n\terr := json.NewDecoder(r.Body).Decode(&req)\n\tif err != nil {\n\t\tservice.ProcessBadFormat(w, service.ErrWrongFormat)\n\t\treturn\n\t}\n\n\tdb, err := d.adb.Create(req.Username)\n\tif err != nil {\n\t\tservice.ProcessServerError(w, service.ErrCreateUser)\n\t\treturn\n\t}\n\n\tas, err := storage.NewAudioPostgres(db)\n\tif err != nil {\n\t\tservice.ProcessServerError(w, service.ErrCreateUser)\n\t\treturn\n\t}\n\n\tas.Migrate()\n\n\tos.MkdirAll(getBaseDir(req.Username), 0777)\n}", "func NewJSONPasswordKeeper(filename string) (basicauth.UserAccountStorage, error) {\n\tif filename == \"\" {\n\t\treturn nil, fmt.Errorf(\"empty filename provided. will do nothing\")\n\t}\n\tif _, err := os.Stat(filename); err == nil {\n\t\treturn nil, fmt.Errorf(\"error: file %v already exists\", filename)\n\t}\n\tvar pk JSONPasswordKeeper\n\tpk.userInfo = make(map[string]basicauth.Account)\n\tpk.filename = filename\n\treturn &pk, pk.flushToDisk()\n}", "func (app *App) createUser(w http.ResponseWriter, r *http.Request) {\n\tvar user users.User\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&user); err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tif (user.Email == \"\") || (user.FName == \"\") || (user.LName == \"\") || (user.Role == \"\") || (user.Password == \"\") {\n\t\trespondWithError(w, http.StatusBadRequest, \"Missing fields\")\n\t\treturn\n\t}\n\n\tif !inArray(user.Role, []string{\"base\", \"admin\"}) {\n\t\trespondWithError(w, http.StatusBadRequest, \"The 'Role' field must be one of: base, admin\")\n\t\treturn\n\t}\n\n\terr := user.CreateUser(app.Db)\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\trespondWithJSON(w, http.StatusOK, user)\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\t// create an empty user of type models.User\n\tvar user models.User\n\n\t// decode the json request to user\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to decode the request body. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !user.Valid() {\n\t\thttp.Error(w, \"Invalid User\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// set the header to content type x-www-form-urlencoded\n\t// Allow all origin to handle cors issue\n\tw.Header().Set(\"Context-Type\", \"application/x-www-form-urlencoded\")\n\tw.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tw.Header().Set(\"Access-Control-Allow-Methods\", \"POST\")\n\tw.Header().Set(\"Access-Control-Allow-Headers\", \"Content-Type\")\n\t//set the hash\n\thashedPass, err := user.HashPassword()\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create hash of the given password. %v\", err)\n\t\thttp.Error(w, \"Bad Request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t// call insert user function and pass the user\n\terr = database.InsertUser(user.Email, hashedPass, user.FirstName, user.LastName)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to insert user. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusBadRequest)\n\t\treturn\n\t}\n\ttkn, err := models.CreateToken(user.Email)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Unable to create token. %v\", err)\n\t\thttp.Error(w, \"\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// format a response object\n\tres := models.TokenResponse{\n\t\tToken: tkn,\n\t}\n\t// send the response\n\terr = json.NewEncoder(w).Encode(res)\n\tif err != nil {\n\t\tlogrus.Errorf(err.Error())\n\t\treturn\n\t}\n}", "func CreateUser(name, email, password string) {\n\n\tm := make(map[string]interface{})\n\tm[\"Github\"] = \"\"\n\tm[\"Linkedin\"] = \"\"\n\tm[\"Twitter\"] = \"\"\n\n\tv, err := json.Marshal(m)\n\tif err != nil {\n\t\tlog.Println(\"Marshal error: \", err)\n\t\treturn\n\t}\n\n\tuser := &User{Name: name, Email: email, Password: password, Meta: string(v)}\n\n\tDb.Debug().Create(&user)\n}", "func (h *User) Create(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tuser, err := validator.UserCreate(body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON400(w)\n\t\treturn\n\t}\n\n\terr = h.Storage.CreateUser(user)\n\t// @todo this might be also 400 response since email can be a duplicate\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tR.JSON500(w)\n\t\treturn\n\t}\n\n\tR.JSON200OK(w)\n}", "func (s *UserStoreFile) Create(user *app.User) error {\r\n\treturn nil\r\n}", "func CreatePerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"content-type\", \"application/json\")\n\n\tperson := r.Context().Value(security.KeyUser{}).(data.Person)\n\n\t//create the user\n\tcreatedPerson := data.DB.Create(&person)\n\terr := createdPerson.Error\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tjson.NewEncoder(w).Encode(&person)\n}", "func Register_user(user *User) {\n\tif(user.Username == \"\" || user.Password == \"\" || user.Email == \"\" || user.Phone == \"\"){\n\t\tfmt.Println(\"you need to input user message to create an account, the arguments include usernam, password, email, telephone.For example:\\n./agenda register -u=zhangzemian -p=12345678 [email protected] -t=15018377821\\n\")\n\t\treturn\n\t}\n\tAllUserInfo := Get_all_user_info()\n\tflog, err := os.OpenFile(\"data/input_output.log\", os.O_APPEND|os.O_WRONLY, 0600)\n\tdefer flog.Close()\n\tcheck_err(err)\n\tlogger := log.New(flog, \"\", log.LstdFlags)\n\n\tif _, ok := AllUserInfo[user.Username]; !ok {\n\t\tAllUserInfo[user.Username] = *user\n\t\tos.Stdout.WriteString(\"[agenda][info] \"+ user.Username + \" registed succeed!\\n\")\n\t\tlogger.Printf(\"[agenda][info] \"+user.Username+\" registed succeed\\n\")\n\t} else {\n\t\tos.Stdout.WriteString(\"[agenda][warning]The userName \" + user.Username + \" have been registered\\n\")\n\t\treturn\n\t}\n\n\tfout, _ := os.Create(\"data/User.json\")\n\tdefer fout.Close()\n\tb, _ := json.Marshal(AllUserInfo)\n\tfout.Write(b)\n}", "func makeUser(t *testing.T, groups []authn.Group, name, secret string) *authn.UserInfo {\n\ttkn := jwt.New(jwt.SigningMethodHS256)\n\tclaims := tkn.Claims.(jwt.MapClaims)\n\tclaims[\"oid\"] = \"42\"\n\tclaims[\"name\"] = name\n\tsecretKey, _ := hex.DecodeString(secret)\n\n\tvalidToken, err := tkn.SignedString(secretKey)\n\tif err != nil {\n\t\tt.Fatalf(\"signing string %v\", err)\n\t}\n\n\treturn &authn.UserInfo{\n\t\tUserID: \"fake\" + name,\n\t\tUserName: name,\n\t\tGroups: groups,\n\t\tToken: validToken,\n\t\tExpiry: time.Time{},\n\t}\n}", "func UserCreate(w http.ResponseWriter, r *http.Request) {\n\terr := json.NewDecoder(r.Body).Decode(&user)\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al leer el usuario a registrarse: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tif user.Password != user.ConfirmPassword {\n\t\tm.Message = \"Las contraseña no coinciden\"\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tuser.Password = password\n\tavatarmd5 := md5.Sum([]byte(user.Password))\n\tavatarstr := fmt.Sprintf(\"%x\", avatarmd5)\n\tuser.Avatar = \"https://gravatar.com/avatar/\" + avatarstr + \"?s=100\"\n\tdatabase := configuration.GetConnection()\n\tdefer database.Close()\n\terr = database.Create(&user).Error\n\tif err != nil {\n\t\tm.Message = fmt.Sprintf(\"Error al crear el registro: %s\", err)\n\t\tm.Code = http.StatusBadRequest\n\t\tcommons.DisplayMessage(w, m)\n\t\treturn\n\t}\n\tm.Message = \"Usuario creado con éxito\"\n\tm.Code = http.StatusCreated\n\tcommons.DisplayMessage(w, m)\n}", "func (context Context) CreateUser(id, password, name string) (string, error) {\n\n\tif id == \"\" {\n\t\tpanic(\"id argument cannot be empty\")\n\t}\n\tif password == \"\" {\n\t\tpanic(\"password argument cannot be empty\")\n\t}\n\tif nameRegex.MatchString(name) == false {\n\t\treturn \"\", errors.New(\"invalid user name\")\n\t}\n\n\thasher := sha256.New()\n\thasher.Write([]byte(password))\n\tpasswordHash := hex.EncodeToString(hasher.Sum(nil))\n\n\tuser := types.User{\n\t\tID: id,\n\t\tName: name,\n\t\tPasswordHash: passwordHash,\n\t}\n\n\tuserBytes, err := json.Marshal(&user)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tresp, err := context.sendAPIPostRequest(\"users\", bytes.NewReader(userBytes), \"application/json\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer resp.Body.Close()\n\n\treturn id, nil\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tuid, err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest)\n\tif err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusCreated, gin.H{\n\t\t\"id\": uid,\n\t}))\n}", "func (ctl UserController) Create(c *gin.Context) {\n\tvar createRequest microsoft.CreateUserRequest\n\tif err := c.ShouldBindJSON(&createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusUnprocessableEntity, err.Error()))\n\t\treturn\n\t}\n\n\tif err := microsoft.NewUser().Create(c.Param(\"id\"), createRequest); err != nil {\n\t\tc.JSON(rootCtl.wrap(http.StatusInternalServerError, err.Error()))\n\t\treturn\n\t}\n\n\tc.JSON(rootCtl.wrap(http.StatusOK))\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\tauthUser, err := auth.GetUserFromJWT(w, r)\n\tif err != nil {\n\t\tresponse.FormatStandardResponse(false, \"error-auth\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\t// Decode the JSON body\n\tacct := datastore.Account{}\n\terr = json.NewDecoder(r.Body).Decode(&acct)\n\tswitch {\n\t// Check we have some data\n\tcase err == io.EOF:\n\t\tresponse.FormatStandardResponse(false, \"error-account-data\", \"\", \"No account data supplied.\", w)\n\t\treturn\n\t\t// Check for parsing errors\n\tcase err != nil:\n\t\tresponse.FormatStandardResponse(false, \"error-decode-json\", \"\", err.Error(), w)\n\t\treturn\n\t}\n\n\tcreateHandler(w, authUser, false, acct)\n}", "func db_check_user_exists(username string) bool {\n file_path := path.Join(\"db/users\", strings.ToLower(username) + \".json\")\n \n if _, err := os.Stat(file_path); !os.IsNotExist(err) {\n return true\n }\n return false\n}", "func AddUser(jsonData []uint8) {\n\tuser := new(models.Users)\n\n\tjson.Unmarshal(jsonData, user)\n\tfmt.Println(\"User================================>>>>>>>>>>>>>>>>\", string(jsonData))\n\n\tmodels.Db.NewRecord(user)\n\taffected := models.Db.Create(&user)\n\n\tfmt.Println(\"User Created :::::::::::::::::::::::\", models.Db.NewRecord(user), affected)\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\tu := models.User{}\n\n\tjson.NewDecoder(r.Body).Decode(&u)\n\n\t// create bson ID\n\t// u.ID = bson.NewObjectId().String()\n\n\t// store the user in mongodb\n\tusers[u.ID] = u\n\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated) // 201\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func createUserHandler(res http.ResponseWriter, req *http.Request) {\n\tvar user MongoUserSchema\n\tjson.NewDecoder(req.Body).Decode(&user)\n\t// fmt.Println(hash(user.Password))\n\tif checkEmailValidity(user.Email) == false {\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\tres.Write([]byte(\"Invalid e-mail id!\"))\n\t\treturn\n\t}\n\n\tusersCol := client.Database(\"Aviroop_Nandy_Appointy\").Collection(\"users\")\n\tctx, _ := context.WithTimeout(context.Background(), 15*time.Second)\n\tcursor, err := usersCol.Find(ctx, bson.M{})\n\n\tfor cursor.Next(ctx) {\n\t\tvar backlogUser MongoUserSchema\n\t\tcursor.Decode(&backlogUser)\n\t\tif backlogUser.Email == user.Email {\n\t\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\t\tres.Write([]byte(`{\"This e-mail is already registered!\":\"` + err.Error() + `\"}`))\n\t\t\treturn\n\t\t}\n\t}\n\n\thashedPswd := hashPassword(user.Password)\n\tuser.Password = hashedPswd\n\n\tuserResult, insertErrorUser := usersCol.InsertOne(ctx, user)\n\tif insertErrorUser != nil {\n\t\tfmt.Println(\"Error while creating user: \", insertErrorUser)\n\t} else {\n\t\tjson.NewEncoder(res).Encode(userResult)\n\t\tuserID := userResult.InsertedID\n\t\tfmt.Println(\"New user id: \", userID)\n\t}\n\n\tres.Header().Add(\"content-type\", \"application/json\")\n\tres.WriteHeader(http.StatusOK)\n}", "func (handler *Handler) handleUserCreate(w http.ResponseWriter, r *http.Request) {\n\n\t//Create an empty new user\n\tnewUser := handler.userHelper.NewEmptyUser()\n\n\t/**\n\tDefine a struct for just updating password\n\t*/\n\ttype newUserStruct struct {\n\t\tEmail string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t}\n\n\t//Create the new user\n\tnewUserInfo := &newUserStruct{}\n\n\t//decode the request body into struct and failed if any error occur\n\terr := json.NewDecoder(r.Body).Decode(newUserInfo)\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, err.Error())\n\t\treturn\n\n\t}\n\n\t//Copy over the new user data\n\tnewUser.SetEmail(newUserInfo.Email)\n\tnewUser.SetPassword(newUserInfo.Password)\n\n\t//Now create the new suer\n\terr = handler.userHelper.createUser(newUser)\n\n\tif err != nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, err.Error())\n\t\treturn\n\t}\n\n\t//Check to see if the user was created\n\tif err == nil {\n\t\tutils.ReturnJsonStatus(w, http.StatusCreated, true, \"create_user_added\")\n\t} else {\n\t\tutils.ReturnJsonStatus(w, http.StatusUnprocessableEntity, false, err.Error())\n\t}\n\n}", "func CreateNewUser(w http.ResponseWriter, r *http.Request) {\n\tfLog := userMgmtLogger.WithField(\"func\", \"CreateNewUser\").WithField(\"RequestID\", r.Context().Value(constants.RequestID)).WithField(\"path\", r.URL.Path).WithField(\"method\", r.Method)\n\n\tiauthctx := r.Context().Value(constants.HansipAuthentication)\n\tif iauthctx == nil {\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusUnauthorized, \"You are not authorized to access this resource\", nil, nil)\n\t\treturn\n\t}\n\n\tfLog.Trace(\"Creating new user\")\n\treq := &CreateNewUserRequest{}\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tfLog.Errorf(\"ioutil.ReadAll got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusInternalServerError, err.Error(), nil, nil)\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, req)\n\tif err != nil {\n\t\tfLog.Errorf(\"json.Unmarshal got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tisValidPassphrase := passphrase.Validate(req.Passphrase, config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\tif !isValidPassphrase {\n\t\tfLog.Errorf(\"Passphrase invalid\")\n\t\tinvalidMsg := fmt.Sprintf(\"Invalid passphrase. Passphrase must at least has %d characters and %d words and for each word have minimum %d characters\", config.GetInt(\"security.passphrase.minchars\"), config.GetInt(\"security.passphrase.minwords\"), config.GetInt(\"security.passphrase.mincharsinword\"))\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, \"invalid passphrase\", nil, invalidMsg)\n\t\treturn\n\t}\n\tuser, err := UserRepo.CreateUserRecord(r.Context(), req.Email, req.Passphrase)\n\tif err != nil {\n\t\tfLog.Errorf(\"UserRepo.CreateUserRecord got %s\", err.Error())\n\t\thelper.WriteHTTPResponse(r.Context(), w, http.StatusBadRequest, err.Error(), nil, nil)\n\t\treturn\n\t}\n\tresp := &CreateNewUserResponse{\n\t\tRecordID: user.RecID,\n\t\tEmail: user.Email,\n\t\tEnabled: user.Enabled,\n\t\tSuspended: user.Suspended,\n\t\tLastSeen: user.LastSeen,\n\t\tLastLogin: user.LastLogin,\n\t\tTotpEnabled: user.Enable2FactorAuth,\n\t}\n\tfLog.Warnf(\"Sending email\")\n\tmailer.Send(r.Context(), &mailer.Email{\n\t\tFrom: config.Get(\"mailer.from\"),\n\t\tFromName: config.Get(\"mailer.from.name\"),\n\t\tTo: []string{user.Email},\n\t\tCc: nil,\n\t\tBcc: nil,\n\t\tTemplate: \"EMAIL_VERIFY\",\n\t\tData: user,\n\t})\n\n\thelper.WriteHTTPResponse(r.Context(), w, http.StatusOK, \"Success creating user\", nil, resp)\n\treturn\n}", "func Create(folder string) {\n\tuser, err := cmd.GetStoredUser()\n\n\tcmd.Guard(user)\n\n\twd, err := os.Getwd()\n\n\tdata := processsInput(os.Stdin)\n\n\tdata[\"author\"] = fmt.Sprintf(\"%s <%s>\", user.Company, user.Email)\n\n\tname := data[\"title\"].(string)\n\n\tr, _ := regexp.Compile(\"[\\\\s?.$#,()^!&]+\")\n\n\tnormalizedName := r.ReplaceAllString(name, \"-\")\n\tnormalizedName = strings.ToLower(normalizedName)\n\tnormalizedName = strings.TrimLeft(normalizedName, \"_\")\n\n\tdata[\"name\"] = normalizedName\n\n\tcheck(err)\n\n\tpath := filepath.ToSlash(folder)\n\n\tif !filepath.IsAbs(path) {\n\t\tpath = filepath.Join(wd, path)\n\t}\n\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\tsi, err := os.Stat(wd)\n\n\t\tcheck(err)\n\n\t\terr = os.Mkdir(path, si.Mode())\n\n\t\tcheck(err)\n\t}\n\n\tresources, err := AssetDir(\"data\")\n\n\tcheck(err)\n\n\tfor key := range resources {\n\t\tentry := resources[key]\n\n\t\tasset := MustAsset(\"data/\" + entry)\n\n\t\tif entry == \"package.json\" {\n\t\t\tasset = cmd.MarshalIndent(data)\n\t\t}\n\n\t\tfilePath := path + \"/\" + entry\n\n\t\terr = ioutil.WriteFile(filePath, asset, os.ModePerm)\n\n\t\tcheck(err)\n\t}\n\n\tfmt.Println(\"Bot Created Successfully.\")\n\n}", "func (user User) Store(filename string) error {\n\tb, err := json.Marshal(user)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ioutil.WriteFile(filename, b, 0644)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) CreateUser(data, fingerprint, ipAddress string, idempotencyKey ...string) (*User, error) {\n\tlog.info(\"========== CREATE USER ==========\")\n\tvar user User\n\tuser.request = Request{\n\t\tclientID: c.ClientID,\n\t\tclientSecret: c.ClientSecret,\n\t\tfingerprint: fingerprint,\n\t\tipAddress: ipAddress,\n\t}\n\n\turl := buildURL(path[\"users\"])\n\tres, err := user.do(\"POST\", url, data, idempotencyKey)\n\tmapstructure.Decode(res, &user)\n\tuser.Response = res\n\n\treturn &user, err\n}", "func createProfile(w http.ResponseWriter, r *http.Request) {\n\n\tw.Header().Set(\"Content-Type\", \"application/json\") // for adding Content-type\n\n\tvar person user\n\terr := json.NewDecoder(r.Body).Decode(&person) // storing in person variable of type user\n\tif err != nil {\n\t\tfmt.Print(err)\n\t}\n\tinsertResult, err := userCollection.InsertOne(context.TODO(), person)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(\"Inserted a single document: \", insertResult)\n\tjson.NewEncoder(w).Encode(insertResult.InsertedID) // return the mongodb ID of generated document\n\n}", "func (c *myClient) createUser(user User, wait bool) (results map[string]interface{}, err error) {\n\tnamespace := \"user\"\n\tuserObj, err := c.findObjectByName(namespace, user.name)\n\tif err != nil {\n\t\treturn userObj, err\n\t}\n\n\tuserObjRef := userObj[\"reference\"]\n\tif userObjRef == nil {\n\t\turl := fmt.Sprintf(\"%s\", namespace)\n\t\tpostBody := createUser(user.name, user.password, user.passwordUpdateRequest)\n\t\taction, _, err := c.httpPost(url, postBody)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif wait {\n\t\t\tc.jobWaiter(action)\n\t\t\tuserObj, err = c.findObjectByName(namespace, user.name)\n\t\t} else {\n\t\t\treturn action, err\n\t\t}\n\t}\n\tlog.Debug(userObjRef)\n\tlog.Infof(\"%s already exists\", user.name)\n\treturn userObj, err\n\n}", "func createFile(name string, template interface{}) (interface{}, error) {\n\t// filling the template with a default value\n\tif err := iterateTemplate(template, true); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// casting a template to an array of bytes\n\tjsonBytes, err := json.MarshalIndent(template, \"\", \" \")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// write template to json file\n\tif err = ioutil.WriteFile(fmt.Sprintf(\"%s/%s.json\", configsDir, name), jsonBytes, 0644); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn template, err\n}", "func newUser() string {\n\treturn goherokuname.Haikunate()\n}", "func Create(u *User) (*User, error) {\n\tif u == nil {\n\t\treturn nil, errors.New(\"user is nil\")\n\t}\n\tu.ID = 0\n\tres, err := client.Post(\"/\", u)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tnewUser := new(User)\n\tif err := res.ReadJSON(newUser); err != nil {\n\t\treturn nil, err\n\t}\n\treturn newUser, nil\n}", "func (h *Handler) createUser(c *gin.Context) handlerResponse {\n\n\tvar newUser types.User\n\tif err := c.ShouldBindJSON(&newUser); err != nil {\n\t\treturn handleBadRequest(err)\n\t}\n\tstoredUser, err := h.service.User.Create(newUser, h.who(c))\n\tif err != nil {\n\t\treturn handleError(err)\n\t}\n\t// Remove password so we do not show in response\n\tstoredUser.Password = \"\"\n\treturn handleCreated(storedUser)\n}", "func Create(user User) error {\n\t\n}", "func db_update_user(username string, sessionid string, follow_username string, post Post){\n file_path := path.Join(\"db/users\", strings.ToLower(username)+\".json\")\n \n if _, err := os.Stat(file_path); os.IsNotExist(err) {\n return\n }\n user := db_JSON_to_user(username)\n \n if sessionid != \"\" {\n user.SessionID = sessionid\n }\n if follow_username != \"\" {\n user.Follows = append(user.Follows, follow_username)\n }\n if post.Content != \"\" {\n user.Posts = append(user.Posts, &post)\n }\n \n updated_user := db_user_to_JSON(user)\n \n writeerr := ioutil.WriteFile(file_path, updated_user, 0644)\n\n if writeerr != nil {\n panic(writeerr)\n }\n}", "func ProjectUserCreate(w http.ResponseWriter, r *http.Request) {\n\n\t// Init output\n\toutput := []byte(\"\")\n\n\t// Add content type header to the response\n\tcontentType := \"application/json\"\n\tcharset := \"utf-8\"\n\tw.Header().Add(\"Content-Type\", fmt.Sprintf(\"%s; charset=%s\", contentType, charset))\n\n\t// Grab url path variables\n\turlVars := mux.Vars(r)\n\turlUser := urlVars[\"user\"]\n\n\t// Grab context references\n\trefStr := gorillaContext.Get(r, \"str\").(stores.Store)\n\trefUserUUID := gorillaContext.Get(r, \"auth_user_uuid\").(string)\n\trefProjUUID := gorillaContext.Get(r, \"auth_project_uuid\").(string)\n\n\t// Read POST JSON body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\terr := APIErrorInvalidRequestBody()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Parse pull options\n\tpostBody, err := auth.GetUserFromJSON(body)\n\tif err != nil {\n\t\terr := APIErrorInvalidArgument(\"User\")\n\t\trespondErr(w, err)\n\t\tlog.Error(string(body[:]))\n\t\treturn\n\t}\n\n\t// omit service wide roles\n\tpostBody.ServiceRoles = []string{}\n\n\t// allow the user to be created to only have reference to the project under which is being created\n\tprName := projects.GetNameByUUID(refProjUUID, refStr)\n\tif prName == \"\" {\n\t\terr := APIErrGenericInternal(\"Internal Error\")\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\tprojectRoles := auth.ProjectRoles{}\n\n\tfor _, p := range postBody.Projects {\n\t\tif p.Project == prName {\n\t\t\tprojectRoles.Project = prName\n\t\t\tprojectRoles.Roles = p.Roles\n\t\t\tprojectRoles.Topics = p.Topics\n\t\t\tprojectRoles.Subs = p.Subs\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// if the project was not mentioned in the creation, add it\n\tif projectRoles.Project == \"\" {\n\t\tprojectRoles.Project = prName\n\t}\n\n\tpostBody.Projects = []auth.ProjectRoles{projectRoles}\n\n\tuuid := uuid.NewV4().String() // generate a new uuid to attach to the new project\n\ttoken, err := auth.GenToken() // generate a new user token\n\tcreated := time.Now().UTC()\n\n\t// Get Result Object\n\tres, err := auth.CreateUser(uuid, urlUser, \"\", \"\", \"\", \"\", postBody.Projects, token, postBody.Email, postBody.ServiceRoles, created, refUserUUID, refStr)\n\n\tif err != nil {\n\t\tif err.Error() == \"exists\" {\n\t\t\terr := APIErrorConflict(\"User\")\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"invalid\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\tif strings.HasPrefix(err.Error(), \"duplicate\") {\n\t\t\terr := APIErrorInvalidData(err.Error())\n\t\t\trespondErr(w, err)\n\t\t\treturn\n\t\t}\n\n\t\terr := APIErrGenericInternal(err.Error())\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Output result to JSON\n\tresJSON, err := res.ExportJSON()\n\tif err != nil {\n\t\terr := APIErrExportJSON()\n\t\trespondErr(w, err)\n\t\treturn\n\t}\n\n\t// Write response\n\toutput = []byte(resJSON)\n\trespondOK(w, output)\n\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tr.ParseForm()\n\n\tuser, err := json.Marshal(map[string]string{\n\t\t\"name\": r.FormValue(\"name\"),\n\t\t\"email\": r.FormValue(\"email\"),\n\t\t\"nick\": r.FormValue(\"nick\"),\n\t\t\"password\": r.FormValue(\"password\"),\n\t})\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusBadRequest, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\n\turl := fmt.Sprintf(\"%s/users\", config.APIURL)\n\tresponse, err := http.Post(url, \"application/json\", bytes.NewBuffer(user))\n\tif err != nil {\n\t\tresponses.JSON(w, http.StatusInternalServerError, responses.ErrorAPI{Err: err.Error()})\n\t\treturn\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode >= 400 {\n\t\tresponses.TreatStatusCode(w, response)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, response.StatusCode, nil)\n}", "func Create(w http.ResponseWriter, r *http.Request) {\n\n\taccountDecoder := json.NewDecoder(r.Body)\n\tvar accData Account\n\terr := accountDecoder.Decode(&accData)\n\tif err != nil {\n\t\tlog.Fatalln(\"error:\", err)\n\t}\n\taccData.CreateAccount()\n\tfmt.Fprintf(w, \"Account added successfully\")\n}", "func createTempUser(host string, adminToken string) (user ssUser, err error) {\n\t//double duty as unique name/login\n\tsuffix, err := diceware.Generate(2)\n\tif err != nil {\n\t\tsuffix = []string{string(time.Now().Nanosecond()), string(time.Now().UnixNano())}\n\t}\n\tpassword, err := diceware.Generate(3)\n\tif err != nil {\n\t\tpassword = []string{string(time.Now().Nanosecond()), os.Getenv(\"OPS_TEAM_NAME\"), string(time.Now().UnixNano())}\n\t}\n\terr = nil\n\tuser.login = os.Getenv(\"OPS_TEAM_NAME\") + \"-\" + strings.Join(suffix, \"\")\n\tuser.password = strings.Join(password, \"\")\n\n\tcreatePostForm := url.Values{}\n\tcreatePostForm.Set(\"login\", user.login)\n\tcreatePostForm.Set(\"name\", user.login)\n\tcreatePostForm.Set(\"password\", user.password)\n\n\treq, err := http.NewRequest(\"POST\", host+\"/api/users/create\", strings.NewReader(createPostForm.Encode()))\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(adminToken, \"\")\n\treq.Header.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\n\tcreateResp, err := http.DefaultClient.Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tdefer createResp.Body.Close()\n\tif createResp.StatusCode != 200 {\n\t\terr = errors.New(\"Failed to create user, expected status code 200 got\" + string(createResp.StatusCode))\n\t}\n\treturn\n}", "func (storage *UserStorage) Create(name string) (*User, error) {\n\tuserUuid := uuid.New()\n\tnewUser := &User{userUuid, name}\n\n\tstorage.users[userUuid] = newUser\n\n\treturn newUser, nil\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tdecoder := json.NewDecoder(r.Body)\n\tvar update models.User\n\terr := decoder.Decode(&update)\n\tu, err := user.CreateUser(update, r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.SuccessDataAPI(w, \"Ok\", u)\n}", "func resourceUserCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {\n\temail := d.Get(\"email\").(string)\n\tteamIDs := getTeamIDs(d)\n\tl := log.With().\n\t\tStr(\"email\", email).\n\t\tInts(\"teamIDs\", teamIDs).\n\t\tLogger()\n\tl.Info().Msg(\"Creating rollbar_user resource\")\n\td.SetId(email)\n\treturn resourceUserCreateOrUpdate(ctx, d, meta)\n}", "func (handler *UserHandler) Create(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {\n\tpayload := &User{}\n\n\tif err := json.NewDecoder(req.Body).Decode(payload); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1001\",\n\t\t\t\"Invalid JSON payload supplied.\", err.Error()))\n\t\treturn\n\t}\n\n\tif err := payload.Validate(); err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1002\",\n\t\t\t\"Unable to validate the payload provided.\", err.Error()))\n\t\treturn\n\t}\n\n\tuser, err := handler.UserService.CreateUser(payload)\n\n\tif err != nil {\n\t\thandler.Formatter.JSON(w, http.StatusBadRequest, util.NewError(\"1003\",\n\t\t\t\"Unable to create a new user.\", err.Error()))\n\t\treturn\n\t}\n\n\thandler.Formatter.JSON(w, http.StatusCreated, user.hidePassword())\n}", "func newHero(name string) (*Hero, error) {\n\tfilename := fmt.Sprintf(\"assets/heroes/%s.json\", name)\n\traw, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t\treturn nil, err\n\t}\n\tvar h Hero\n\tjson.Unmarshal(raw, &h)\n\treturn &h, nil\n}", "func (a *Server) CreateUser(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"create a new user\")\n}", "func createUserV1() user {\n\tu := user{\n\t\tname: \"Bill\",\n\t\temail: \"[email protected]\",\n\t}\n\n\tprintln(\"V1\", &u)\n\n\treturn u\n}", "func createUser(u *User) error {\n\tif u.Status == 0 {\n\t\treturn errors.New(\"Invalid user value\")\n\t}\n\n\treturn nil\n}", "func (uc UserController) CreateUser(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {\n\n\tu := models.User{}\n\n\tjson.NewDecoder(r.Body).Decode(&u) //decode the request body\n\n\t//create bson ID\n\tu.ID = bson.NewObjectId()\n\n\t//store the user in mongodb\n\tuc.session.DB(\"go-web-dev-db\").C(\"users\").Insert(u)\n\n\t//remarshal\n\tuj, _ := json.Marshal(u)\n\n\tw.Header().Set(\"Content-Type\", \"application.json\")\n\tw.WriteHeader(http.StatusOK)\n\tfmt.Fprintf(w, \"%s\\n\", uj)\n}", "func (u *UsersController) Create(ctx *gin.Context) {\n\tvar userJSON tat.UserCreateJSON\n\tctx.Bind(&userJSON)\n\tvar userIn tat.User\n\tuserIn.Username = u.computeUsername(userJSON)\n\tuserIn.Fullname = strings.TrimSpace(userJSON.Fullname)\n\tuserIn.Email = strings.TrimSpace(userJSON.Email)\n\tcallback := strings.TrimSpace(userJSON.Callback)\n\n\tif len(userIn.Username) < 3 || len(userIn.Fullname) < 3 || len(userIn.Email) < 7 {\n\t\terr := fmt.Errorf(\"Invalid username (%s) or fullname (%s) or email (%s)\", userIn.Username, userIn.Fullname, userIn.Email)\n\t\tAbortWithReturnError(ctx, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tif err := u.checkAllowedDomains(userJSON); err != nil {\n\t\tctx.JSON(http.StatusForbidden, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tuser := tat.User{}\n\tfoundEmail, errEmail := userDB.FindByEmail(&user, userJSON.Email)\n\tfoundUsername, errUsername := userDB.FindByUsername(&user, userJSON.Username)\n\tfoundFullname, errFullname := userDB.FindByFullname(&user, userJSON.Fullname)\n\n\tif foundEmail || foundUsername || foundFullname || errEmail != nil || errUsername != nil || errFullname != nil {\n\t\te := fmt.Errorf(\"Please check your username, email or fullname. If you are already registered, please reset your password\")\n\t\tAbortWithReturnError(ctx, http.StatusBadRequest, e)\n\t\treturn\n\t}\n\n\ttokenVerify, err := userDB.Insert(&userIn)\n\tif err != nil {\n\t\tlog.Errorf(\"Error while InsertUser %s\", err)\n\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tgo userDB.SendVerifyEmail(userIn.Username, userIn.Email, tokenVerify, callback)\n\n\tinfo := \"\"\n\tif viper.GetBool(\"username_from_email\") {\n\t\tinfo = fmt.Sprintf(\" Note that configuration of Tat forced your username to %s\", userIn.Username)\n\t}\n\tctx.JSON(http.StatusCreated, gin.H{\"info\": fmt.Sprintf(\"please check your mail to validate your account.%s\", info)})\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n\tusername := r.FormValue(\"user\")\n\tpass := r.FormValue(\"pass\")\n\tuser := User{}\n\terr := userDB.Find(bson.M{\"username\": username}).One(&user)\n\n\tif user.UserName == username {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(w, \"User already exists\")\n\t\treturn\n\t}\n\n\tif len(pass) < 8 {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(w, \"Password must contain at least 8 characters\")\n\t\treturn\n\t}\n\n\thash, _ := bcrypt.GenerateFromPassword([]byte(pass), 10)\n\tuser.UserName = username\n\tuser.Hash = hash\n\terr = userDB.Insert(&user)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tfmt.Fprintln(w, \"Error creating user.\")\n\t\treturn\n\t}\n\n\tr.URL.Path = \"/login\"\n}", "func (u *UserController) CreateUser(c *gin.Context) {\n var user models.UserRegister\n if err := c.ShouldBind(&user); err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Inavlid Json Provided\")\n return\n }\n\n hashPassword, _ := util.HashPassword(user.Password)\n user.Password = hashPassword\n\n err := u.service.CreateUser(user)\n if err != nil {\n util.ErrorJSON(c, http.StatusBadRequest, \"Failed to create user\")\n return\n }\n\n util.SuccessJSON(c, http.StatusOK, \"Successfully Created user\")\n}", "func (t *OpetCode) createDocument(APIstub shim.ChaincodeStubInterface, args []string) sc.Response {\n if len(args) != 3 {\n return shim.Error(\"Incorrect number of arguments. Expecting 3\")\n }\n\n user_uid := args[0]\n uid := args[1]\n json_props := args[2]\n doc_key, _ := APIstub.CreateCompositeKey(uid, []string{DOCUMENT_KEY})\n user_key, _ := APIstub.CreateCompositeKey(user_uid, []string{USER_KEY})\n\n if _, err := t.loadDocument(APIstub, doc_key); err == nil {\n return shim.Error(\"Document already exists\")\n }\n\n user, err := t.loadUser(APIstub, user_key)\n if err != nil {\n return shim.Error(fmt.Sprintf(\"The %s user doesn't not exist\", user_uid))\n }\n user.Documents = append(user.Documents, uid)\n\n\n new_doc := new(Document)\n new_doc.Data = make(map[string]interface{})\n err = json.Unmarshal([]byte(json_props), &new_doc.Data)\n if err != nil {\n return shim.Error(\"Can't parse json props\")\n }\n\n new_doc_json, _ := json.Marshal(new_doc)\n APIstub.PutState(doc_key, new_doc_json)\n\n user_json, _ := json.Marshal(user)\n APIstub.PutState(user_key, user_json)\n\n return shim.Success(nil)\n}", "func (t *HackidfChaincode) CreateUser(stub shim.ChaincodeStubInterface, args []string)pb.Response{\n\tvar UserID = args[0]\n\tvar Username = args[1]\n\tvar Email = args[2]\n\t// checking for an error or if the user already exists\n\tUserAsBytes, err := stub.GetState(Username)\n\tif err != nil {\n\t\treturn shim.Error(\"Failed to get Username:\" + err.Error())\n\t}else if UserAsBytes != nil{\n\t\treturn shim.Error(\"User with current username already exists\")\n\t}\n\tvar User = &User{Username:Username, Email:Email}\n\tUserJsonAsBytes, err :=json.Marshal(User)\n\tif err != nil {\n\t\tshim.Error(\"Error encountered while Marshalling\")\n\t}\n\terr = stub.PutState(UserID, UserJsonAsBytes)\n\tif err != nil {\n\t\tshim.Error(\"Error encountered while Creating User\")\n\t}\n\tfmt.Println(\"Ledger Updated Successfully\")\n\treturn shim.Success(nil)\n}", "func CreateUserHandler(connection *sql.DB, cnf config.Config) negroni.HandlerFunc {\n\treturn negroni.HandlerFunc(func(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\t\tuser := &models.UserCreate{}\n\t\terr := util.RequestToJSON(r, user)\n\t\tif err != nil {\n\t\t\tutil.SendBadRequest(w, errors.New(\"Bad json\"))\n\t\t\treturn\n\t\t}\n\n\t\tif err := user.Validate(); err == nil {\n\t\t\tif err := user.ValidatePassword(); err == nil {\n\n\t\t\t\thash, _ := bcrypt.GenerateFromPassword([]byte(user.Password), 10)\n\t\t\t\tuser.Hash = string(hash)\n\n\t\t\t\tcreatedID, err := db.CreateUser(connection, user)\n\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.SendBadRequest(w, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tcreatedUser, err := db.GetUserByID(connection, createdID)\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.SendBadRequest(w, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\t// create JWT object with claims\n\t\t\t\texpiration := time.Now().Add(time.Hour * 24 * 31).Unix()\n\t\t\t\ttoken := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{\n\t\t\t\t\t\"sub\": createdUser.ID,\n\t\t\t\t\t\"iat\": time.Now().Unix(),\n\t\t\t\t\t\"exp\": expiration,\n\t\t\t\t})\n\n\t\t\t\t// Load secret key from config and generate a signed token\n\t\t\t\tsecretKey := cnf.SecretKey\n\t\t\t\ttokenString, err := token.SignedString([]byte(secretKey))\n\t\t\t\tif err != nil {\n\t\t\t\t\tutil.SendError(w, err)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\ttype Token struct {\n\t\t\t\t\tToken string `json:\"token\"`\n\t\t\t\t\tExpiresOn string `json:\"expires_on\"`\n\t\t\t\t\tUser *models.UserResponse `json:\"user\"`\n\t\t\t\t}\n\n\t\t\t\tutil.SendOK(w, &Token{\n\t\t\t\t\tToken: tokenString,\n\t\t\t\t\tExpiresOn: strconv.Itoa(int(expiration)),\n\t\t\t\t\tUser: &createdUser,\n\t\t\t\t})\n\n\t\t\t} else {\n\t\t\t\tutil.SendBadRequest(w, err)\n\t\t\t}\n\t\t} else {\n\t\t\tutil.SendBadRequest(w, err)\n\t\t}\n\t})\n}", "func createPerson(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tvar person Person\n\t_ = json.NewDecoder(r.Body).Decode(&person)\n\tpeople = append(people, person)\n\tjson.NewEncoder(w).Encode(person)\n\n}", "func (h *ServiceUsersHandler) Create(ctx context.Context, project, service string, req CreateServiceUserRequest) (*ServiceUser, error) {\n\tpath := buildPath(\"project\", project, \"service\", service, \"user\")\n\tbts, err := h.client.doPostRequest(ctx, path, req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar r ServiceUserResponse\n\terrR := checkAPIResponse(bts, &r)\n\n\treturn r.User, errR\n}", "func createPerson(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {\n\tnewID := ps.ByName(\"id\")\n\tvar newPerson person\n\t_ = json.NewDecoder(r.Body).Decode(&newPerson)\n\tnewPerson.ID = string(newID)\n\tpeople = append(people, newPerson)\n\tjson.NewEncoder(w).Encode(people)\n}", "func CreateUser(c *gin.Context) {\n\ttype result struct {\n\t\tFirstName string `json:\"first_name\"`\n\t\tLastName string `json:\"last_name\"`\n\t\tEmail string `json:\"email\"`\n\t\tPassword string `json:\"password\"`\n\t\tDateOfBirth string `json:\"birth_date\"`\n\t}\n\tUserParams := result{}\n\n\terr := c.ShouldBindJSON(&UserParams)\n\tlayout := \"2006-01-02\"\n\tstr := UserParams.DateOfBirth\n\tt, er := time.Parse(layout, str)\n\n\tif er != nil {\n\t\tfmt.Println(er)\n\t}\n\n\tvar user model.User\n\tif err != nil {\n\t\tc.JSON(http.StatusBadRequest, err)\n\t\treturn\n\t}\n\tif len(UserParams.Password) == 0 {\n\t\tfmt.Println(\"err2\")\n\t\tlog.Println(err)\n\t\tc.JSON(http.StatusBadRequest, \"No given password\")\n\t\treturn\n\t}\n\tif age.Age(t) < 18 {\n\t\tlog.Println(err)\n\t\tc.JSON(http.StatusBadRequest, \"You are not adult!\")\n\t\treturn\n\t}\n\tif !db.Where(\"email = ?\", UserParams.Email).Find(&user).RecordNotFound() {\n\t\tc.JSON(http.StatusBadRequest, \"User with this email already exist\")\n\t\treturn\n\t}\n\tid := uuid.NewV4()\n\t// 1 = single user; 2 = admin\n\tuser.AccessLevel = 1\n\tuser.UUID = id.String()\n\tvar hash = hashPassword(UserParams.Password)\n\tuser.Password = hash\n\tuser.FirstName = UserParams.FirstName\n\tuser.LastName = UserParams.LastName\n\tuser.Email = UserParams.Email\n\tuser.DateOfBirth = t\n\tdb.Create(&user)\n\tuser.Password = \"\"\n\tc.JSON(200, &user)\n}", "func newUser(data userData, conn Connection) (User, error) {\n\tif data.Name == \"\" {\n\t\treturn nil, WithStack(InvalidArgumentError{Message: \"data.Name is empty\"})\n\t}\n\tif conn == nil {\n\t\treturn nil, WithStack(InvalidArgumentError{Message: \"conn is nil\"})\n\t}\n\treturn &user{\n\t\tdata: data,\n\t\tconn: conn,\n\t}, nil\n}", "func (s *Service) CreateUser(c *tokay.Context) {\n\tuParams := userStruct{}\n\n\terr = c.BindJSON(&uParams)\n\tif errorAlert(\"Bind fall down\", err, c) {\n\t\treturn\n\t}\n\tuParams.ID = ai.Next(\"user\")\n\n\thash, err := bcrypt.GenerateFromPassword([]byte(uParams.Hash), bcrypt.DefaultCost)\n\tif err != nil {\n\t\treturn\n\t}\n\tuParams.Hash = string(hash)\n\n\ttime := time.Now().Format(\"Jan 2, 2006 at 3:04pm\")\n\tuParams.RegistrationTime = time\n\n\terr = db.UserCol.Insert(uParams)\n\tif errorAlert(\"Error: Input parameteres already used\", err, c) {\n\t\treturn\n\t}\n\n\tc.JSON(200, obj{\"ok\": \"true\"})\n}", "func (u *UserServiceHandler) Create(ctx context.Context, email, name, password, apiEnabled string, acls []string) (*User, error) {\n\n\turi := \"/v1/user/create\"\n\n\tvalues := url.Values{\n\t\t\"email\": {email},\n\t\t\"name\": {name},\n\t\t\"password\": {password},\n\t\t\"acls[]\": acls,\n\t}\n\n\tif apiEnabled != \"\" {\n\t\tvalues.Add(\"api_enabled\", apiEnabled)\n\t}\n\n\treq, err := u.client.NewRequest(ctx, http.MethodPost, uri, values)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser := new(User)\n\n\terr = u.client.DoWithContext(ctx, req, user)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tuser.Name = name\n\tuser.Email = email\n\tuser.APIEnabled = apiEnabled\n\tuser.ACL = acls\n\n\treturn user, nil\n}", "func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) {\n\tlog.Print(\"/users POST handled\")\n\n\treq := &CreateRequest{}\n\tif err := util.ScanRequest(r, req); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tuser := &schema.User{\n\t\tName: req.Name,\n\t}\n\n\tif err := h.model.Validate(user); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tres, err := h.model.Create(user)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tif err := util.JSONWrite(w, res, http.StatusCreated); err != nil {\n\t\tlog.Println(err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}\n}", "func CreateUser(w http.ResponseWriter, r *http.Request) {\n\tvar user models.User\n\tbodyRequest, err := ioutil.ReadAll(r.Body)\n\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusUnprocessableEntity, err)\n\t\treturn\n\t}\n\n\tif err = json.Unmarshal(bodyRequest, &user); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := user.Prepare(true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tif err := validateUniqueDataUser(user, true); err != nil {\n\t\tresponses.Error(w, http.StatusBadRequest, err)\n\t\treturn\n\t}\n\n\tdb, err := database.Connect()\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t}\n\tdefer db.Close()\n\n\trepository := repository.NewRepositoryUser(db)\n\n\tuser.Id, err = repository.Insert(user)\n\tif err != nil {\n\t\tresponses.Error(w, http.StatusInternalServerError, err)\n\t\treturn\n\t}\n\n\tresponses.JSON(w, http.StatusCreated, user)\n\n}", "func createHandler(w http.ResponseWriter, r *http.Request) {\n user := new(User)\n user.Token = validateToken(r.FormValue(\"token\"))\n user.PasswordHash = validateHash(r.FormValue(\"passHash\"))\n user.PublicKey = validatePublicKey(r.FormValue(\"publicKey\"))\n user.PublicHash = computePublicHash(user.PublicKey)\n user.CipherPrivateKey = validateHex(r.FormValue(\"cipherPrivateKey\"))\n\n log.Printf(\"Woot! New user %s %s\\n\", user.Token, user.PublicHash)\n\n if !SaveUser(user) {\n http.Error(w, \"That username is taken\", http.StatusBadRequest)\n }\n}" ]
[ "0.7184839", "0.70120376", "0.6714416", "0.6661976", "0.65823704", "0.6569021", "0.6474795", "0.63668996", "0.63183564", "0.63151884", "0.62504303", "0.6196111", "0.613787", "0.6045717", "0.60371596", "0.6009682", "0.5983985", "0.5982372", "0.5954898", "0.59430826", "0.5937143", "0.5934307", "0.5925449", "0.5914808", "0.5904979", "0.59039336", "0.58975023", "0.58817095", "0.585091", "0.5846296", "0.5839768", "0.5831598", "0.5822863", "0.5815336", "0.58145887", "0.5813928", "0.57598424", "0.57320637", "0.5723674", "0.57147074", "0.5710782", "0.57104796", "0.5700037", "0.569185", "0.56865335", "0.5682747", "0.56792647", "0.56636155", "0.56570077", "0.5640012", "0.5637514", "0.56206954", "0.56187004", "0.56157976", "0.5614593", "0.56095886", "0.560459", "0.5600262", "0.55911523", "0.55876577", "0.55796325", "0.55697685", "0.5568945", "0.55641836", "0.5561096", "0.5553879", "0.55493104", "0.5545463", "0.5543312", "0.5539492", "0.55356336", "0.55341953", "0.55334353", "0.553331", "0.5527571", "0.552061", "0.55173343", "0.5515037", "0.5500162", "0.5491641", "0.54829854", "0.54716504", "0.54625684", "0.5457605", "0.5455637", "0.5453028", "0.54416966", "0.5439209", "0.54377705", "0.54376376", "0.54359657", "0.5431796", "0.542249", "0.5413881", "0.5407951", "0.5404632", "0.5400313", "0.5400273", "0.5396518", "0.53932035" ]
0.600093
16
returns ids with identical records and users with missing/empty values
func (list Users) GetInvalidIds() []string { invalidIds := []string{} idsWithIdenticalValues := list.getIdsWithIdenticalValues() invalidIds = append(invalidIds, idsWithIdenticalValues...) idsWithEmptyValues := list.getIdsWithEmptyValues() invalidIds = append(invalidIds, idsWithEmptyValues...) return invalidIds }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func duplicateExistsInUserTickets(record *PoolTicket, records []*PoolTicket) bool {\n\tfor _, r := range records {\n\t\tif *r == *record {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func duplicateExistsInInvalTickets(record *chainhash.Hash, records []*chainhash.Hash) bool {\n\tfor _, r := range records {\n\t\tif *r == *record {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func recordExistsInUserTickets(record *PoolTicket, records []*PoolTicket) (bool, int) {\n\tfor i, r := range records {\n\t\tif r.Ticket == record.Ticket {\n\t\t\treturn true, i\n\t\t}\n\t}\n\treturn false, 0\n}", "func findDuplicatesInBatchObjects(in []*storobj.Object) map[int]struct{} {\n\tcount := map[strfmt.UUID]int{}\n\tfor _, obj := range in {\n\t\tcount[obj.ID()] = count[obj.ID()] + 1\n\t}\n\n\tignore := map[int]struct{}{}\n\tfor i, obj := range in {\n\t\tif c := count[obj.ID()]; c > 1 {\n\t\t\tcount[obj.ID()] = c - 1\n\t\t\tignore[i] = struct{}{}\n\t\t}\n\t}\n\n\treturn ignore\n}", "func TestSelectUsersByIdsArray(t *testing.T) {\n\tdb, mock, repo := initUserTest(t)\n\tdefer db.Close()\n\n\t// Mock DB statements and execute\n\trows := getUserRows()\n\tmock.ExpectPrepare(\"^SELECT (.+) FROM users WHERE id IN (.+)\").\n\t\tExpectQuery().\n\t\tWillReturnRows(rows)\n\tgot, err := repo.SelectByIds(testUtils.Context, []uint{1})\n\tif err != nil {\n\t\tt.Errorf(\"Unexpected error %v\", err)\n\t}\n\n\t// Validate results\n\twant := map[uint]domains.User{\n\t\t1: getUser(),\n\t}\n\n\tif !reflect.DeepEqual(got, want) {\n\t\tt.Errorf(\"Values not equal: got = %v, want = %v\", got, want)\n\t}\n\tif err := mock.ExpectationsWereMet(); err != nil {\n\t\tt.Errorf(\"Unfulfilled expectations: %s\", err)\n\t}\n}", "func UserIDs(generator *Generator) Criterion {\n\treturn usersCriterion{g: generator}\n}", "func equalIds(wantedId, foundId, foundHref string) bool {\n\n\twantedUuid := extractUuid(wantedId)\n\tfoundUuid := \"\"\n\n\tif wantedUuid == \"\" {\n\t\treturn false\n\t}\n\tif foundId != \"\" {\n\t\t// In some entities, the ID is a simple UUID without prefix\n\t\tfoundUuid = extractUuid(foundId)\n\t} else {\n\t\tfoundUuid = extractUuid(foundHref)\n\t}\n\treturn foundUuid == wantedUuid\n}", "func getSameValues(results chan map[string]bool) []string {\n\tvar datas = make([]map[string]bool, len(results))\n\tminIndex := -1\n\tminSize := int(MaxUint >> 1)\n\ti := 0\n\tfor values := range results {\n\t\tsizeValues := len(values)\n\t\tif sizeValues < minSize && sizeValues > 0 {\n\t\t\tminSize = sizeValues\n\t\t\tminIndex = i\n\t\t}\n\t\tdatas[i] = values\n\t\ti++\n\t}\n\n\t// getting the same value from all the datas\n\tvar theSameValue []string\n\tfor value, _ := range datas[minIndex] {\n\t\t// check if all value is exist\n\t\tisExistAll := true\n\t\tfor _, data := range datas {\n\t\t\tisExistAll = isExistAll && data[value]\n\t\t}\n\n\t\tif isExistAll {\n\t\t\ttheSameValue = append(theSameValue, value)\n\t\t}\n\t}\n\n\treturn theSameValue\n}", "func onlyIDQuery(q *protocol.KontrolQuery) bool {\n\tfields := q.Fields()\n\n\t// check if any other key exist, if yes return a false\n\tfor _, k := range keyOrder {\n\t\tv := fields[k]\n\t\tif k != \"id\" && v != \"\" {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t// now all other keys are empty, check finally for our ID\n\tif fields[\"id\"] != \"\" {\n\t\treturn true\n\t}\n\n\t// ID is empty too!\n\treturn false\n}", "func TestCheckForDuplicates(t *testing.T) {\n\ttables := []struct {\n\t\tmyReq []string\n\t\tmyHeaders map[string]int\n\t\tmyDup map[string]bool\n\t\tmyLow map[string]int\n\t\tmyErr error\n\t}{\n\t\t{[]string{\"name\", \"id\", \"last_name\", \"last_name\"}, make(map[string]int), make(map[string]bool), make(map[string]int), ErrAmbiguousFieldName},\n\t\t{[]string{\"name\", \"id\", \"last_name\", \"another_name\"}, make(map[string]int), make(map[string]bool), make(map[string]int), nil},\n\t}\n\tfor _, table := range tables {\n\t\terr := checkForDuplicates(table.myReq, table.myHeaders, table.myDup, table.myLow)\n\t\tif err != table.myErr {\n\t\t\tt.Error()\n\t\t}\n\t}\n}", "func verify(records []Record) error {\n\trecordMap := make(map[int]Record)\n\tfor _, record := range records {\n\t\trecordMap[record.ID] = record\n\n\t\tif record.ID >= len(records) {\n\t\t\treturn errors.New(\"node id is larger than or equal to length\")\n\t\t}\n\n\t\tif record.ID == 0 && record.Parent != 0 {\n\t\t\treturn errors.New(\"root id != parent\")\n\t\t}\n\t\tif record.ID > 0 && record.Parent >= record.ID {\n\t\t\treturn errors.New(\"node parent should be smaller than id\")\n\t\t}\n\t}\n\n\tif _, ok := recordMap[0]; !ok {\n\t\treturn errors.New(\"no root node\")\n\t}\n\n\tif len(recordMap) != len(records) {\n\t\treturn errors.New(\"duplicate\")\n\t}\n\n\treturn nil\n}", "func (uc UserUseCase) checkDuplication(ID, email, mobilePhone string) (res bool, err error) {\n\tcountMail, err := uc.CountBy(ID, \"email\", email, \"=\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif countMail > 0 {\n\t\treturn true, errors.New(messages.EmailAlreadyExist)\n\t}\n\n\tcountMobilePhone, err := uc.CountBy(ID, \"mobile_phone\", mobilePhone, \"=\")\n\tif err != nil {\n\t\treturn false, err\n\t}\n\tif countMobilePhone > 0 {\n\t\treturn true, errors.New(messages.PhoneAlreadyExist)\n\t}\n\n\treturn false, nil\n}", "func ParamsExist(ids []int64, tx *sql.Tx) ([]int64, error) {\n\tvar nonExistingIDs []int64\n\tif err := tx.QueryRow(`SELECT ARRAY_AGG(id) FROM UNNEST($1::INT[]) AS id WHERE id NOT IN (SELECT id FROM parameter)`, pq.Array(ids)).Scan(pq.Array(&nonExistingIDs)); err != nil {\n\t\treturn nil, fmt.Errorf(\"querying parameters existence from id: %w\", err)\n\t}\n\tif len(nonExistingIDs) >= 1 {\n\t\treturn nonExistingIDs, nil\n\t}\n\treturn nil, nil\n}", "func resultsEmpty(resultValues [][]interface{}) bool {\n\tfor _, vals := range resultValues {\n\t\t// start the loop at 1 because we want to skip over the time value\n\t\tfor i := 1; i < len(vals); i++ {\n\t\t\tif vals[i] != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func uniqueDevices(sample []v1alpha1.DiscoveredDevice) []v1alpha1.DiscoveredDevice {\n\tvar unique []v1alpha1.DiscoveredDevice\n\ttype key struct{ value, value2 string }\n\tm := make(map[key]int)\n\tfor _, v := range sample {\n\t\tk := key{v.DeviceID, v.Path}\n\t\tif i, ok := m[k]; ok {\n\t\t\tunique[i] = v\n\t\t} else {\n\t\t\tm[k] = len(unique)\n\t\t\tunique = append(unique, v)\n\t\t}\n\t}\n\treturn unique\n}", "func FindUniqueIdxs(folds []Fold, nFitter int) (ups []PredictIndices) {\n\tnFolds := len(folds)\n\tups = make([]PredictIndices, len(folds))\n\tfor i := range folds {\n\t\tl := len(folds[i].Assess)\n\t\tups[i].Unique = make([]int, 0, l)\n\t\tups[i].ToUniqueIdx = make(map[int]int, l)\n\t}\n\n\t// Find the unique predictive distributions in assess and update.\n\tfor i := 0; i < nFolds; i++ {\n\t\tfor _, v := range folds[i].Assess {\n\t\t\tif _, ok := ups[i].ToUniqueIdx[v]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tups[i].ToUniqueIdx[v] = len(ups[i].Unique)\n\t\t\tups[i].Unique = append(ups[i].Unique, v)\n\t\t}\n\t\tfor _, v := range ups[i].ToUniqueIdx {\n\t\t\tif _, ok := ups[i].ToUniqueIdx[v]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tups[i].ToUniqueIdx[v] = len(ups[i].Unique)\n\t\t\tups[i].Unique = append(ups[i].Unique, v)\n\t\t}\n\t}\n\treturn ups\n}", "func (o *NotificationProjectBudgetNotification) GetUserIdsOk() (*[]int32, bool) {\n\tif o == nil || o.UserIds == nil {\n\t\treturn nil, false\n\t}\n\treturn o.UserIds, true\n}", "func uniqueUIDs(m map[uint64][]uint64) ([]uint64, []int) {\n\tuniq := make(map[uint64]int)\n\tfor _, v := range m {\n\t\tfor _, u := range v {\n\t\t\tuniq[u]++\n\t\t}\n\t}\n\tout := make([]uint64, 0, len(uniq))\n\toutCount := make([]int, 0, len(uniq))\n\tfor k, v := range uniq {\n\t\tout = append(out, k)\n\t\toutCount = append(outCount, v)\n\t}\n\treturn out, outCount\n}", "func HaveSameUIDs(pods1 []corev1.Pod, pods2 []corev1.Pod) bool {\n\tcount := len(pods1)\n\tif count != len(pods2) {\n\t\treturn false\n\t}\n\tids1, ids2 := make([]string, count), make([]string, count)\n\tfor i := 0; i < count; i++ {\n\t\tids1[i], ids2[i] = string(pods1[i].UID), string(pods2[i].UID)\n\t}\n\tsort.Strings(ids1)\n\tsort.Strings(ids2)\n\tfor i := 0; i < count; i++ {\n\t\tif ids1[i] != ids2[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestHasNoCollisions(t *testing.T) {\n\tCOUNT := 100 * 1000\n\tused := make(map[string]bool)\n\tfor i := 0; i < COUNT; i++ {\n\t\tid, err := Nanoid()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Nanoid error: %v\", err)\n\t\t}\n\t\tif used[id] {\n\t\t\tt.Errorf(\"Collision error! Id %v found for test arr %v\", id, used)\n\t\t}\n\t\tused[id] = true\n\t}\n}", "func userDuplicate(r *room, a string) bool {\n\tfor i := range r.users {\n\t\tif stripansi.Strip(r.users[i].name) == stripansi.Strip(a) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func UseridNotNil() predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.NotNull(s.C(FieldUserid)))\n\t})\n}", "func notMatchField(id int, fields []int) bool {\r\n\tfor _, i := range fields {\r\n\t\tif id == i {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func usersContain(actualUsers []githubUser, username string) bool {\n\tfor _, user := range actualUsers {\n\t\tif user.name == username {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (m *MockRepository) GetUsersByIDs(userIDs []int64) map[int64]*domain.User {\n\tuserMap := map[int64]*domain.User{}\n\tfor _, userID := range userIDs {\n\t\tuser, ok := MockData[userID]\n\t\tif ok {\n\t\t\tuserMap[userID] = &user\n\t\t}\n\t}\n\treturn userMap\n}", "func users(c *gin.Context) {\n\tvar result []interface{}\n\terr := tweetsColl().Find(bson.M{}).Distinct(\"user\", &result) // returns all the distict users in an array, not just the length which would be optimal\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tc.JSON(500, \"error\")\n\t\treturn\n\t}\n\n\tc.JSON(200, gin.H{\"users\": len(result)})\n}", "func ValidateTaskIds(AllTasks []config.Task) (err error) {\n\tdup := make(map[string]int)\n\tfor _, task := range AllTasks {\n\t\t_, exists := dup[task.ID]\n\t\tif exists {\n\t\t\terr = errors.New(\"Hay tareas duplicadas, se sale\")\n\t\t\tlog.Error(\"La tarea \" + task.ID + \" esta duplicada\")\n\t\t} else {\n\t\t\tdup[task.ID]++\n\t\t}\n\t}\n\treturn\n}", "func ArrayContainsUser(arr []*discordgo.User, el *discordgo.User) bool {\n\tif len(arr) == 0 {\n\t\treturn false\n\t}\n\n\tfor _, element := range arr {\n\t\tif element.ID == el.ID {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func MustBehaveLikeUsers(t *testing.T, us model.Users) {\n\t// Create and save a user\n\tu1 := model.User{\n\t\tName: \"Jane Doe\",\n\t\tGithubID: 66235,\n\t\tAPIKey: \"deadc0ffee\",\n\t}\n\terr := us.Save(&u1)\n\trequire.NoError(t, err, \"errored when saving a user\")\n\t// ID should be auto-generated, if not specified\n\trequire.NotEmpty(t, u1.ID, \"User ID should be auto-generated\")\n\n\t// added user record should find-able by its ID\n\tux, err := us.Find(u1.ID)\n\trequire.NoError(t, err, \"errored when finding a user\")\n\trequire.Equal(t, u1, *ux)\n\t// but not if it's a wrong one\n\tux, err = us.Find(u1.ID * 100)\n\trequire.Equal(t, model.ErrNotFound, err)\n\n\t// and by its Github ID\n\tux, err = us.FindByGithubID(u1.GithubID)\n\trequire.NoError(t, err)\n\trequire.Equal(t, u1, *ux)\n\t// but not if it's a wrong one\n\tux, err = us.FindByGithubID(u1.GithubID * 100)\n\trequire.Equal(t, model.ErrNotFound, err)\n\n\t// user, when added, should have the API key generated\n\tak := u1.APIKey\n\trequire.NotEmpty(t, ak)\n\t// which can be used to find the same user\n\tux, err = us.FindByAPIKey(ak)\n\trequire.NoError(t, err)\n\trequire.Equal(t, u1, *ux)\n\t// but, again, not if it's a wrong one\n\tux, err = us.FindByAPIKey(\"o_O\")\n\trequire.Equal(t, model.ErrNotFound, err)\n\n\t// the second user, when added, must receive a different ID\n\t// Create and save a user\n\tu2 := model.User{\n\t\tName: \"Gordon Freeman\",\n\t}\n\terr = us.Save(&u2)\n\trequire.NoError(t, err)\n\t// ID should be auto-generated, if not specified\n\trequire.NotEqual(t, u2.ID, 0, \"User ID should be auto-generated\")\n\trequire.NotEqual(t, u1.ID, u2.ID)\n}", "func (o *User) GetIdentitiesOk() ([]ObjectIdentity, bool) {\n\tif o == nil || o.Identities == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Identities, true\n}", "func (rs Reservations) findIDsByUserID(userID ID) (ids []ID) {\n\tfor _, r := range rs {\n\t\tif r.UserID == userID {\n\t\t\tids = append(ids, r.ID)\n\t\t}\n\t}\n\treturn ids\n}", "func ResultsEqualUnordered(r1, r2 []Result) bool {\n\tif len(r1) != len(r2) {\n\t\treturn false\n\t}\n\n\t// allRows is a hash map that contains a row hashed as a key and\n\t// the number of occurrence as the value. we use this map to ensure\n\t// equality between the two result sets. when analyzing r1, we\n\t// increment each key's value by one for each row's occurrence, and\n\t// then we decrement it by one each time we see the same key in r2.\n\t// if one of the key's value is not equal to zero, then r1 and r2 do\n\t// not match.\n\tallRows := map[string]int{}\n\tcountRows := 0\n\tfor _, r := range r1 {\n\t\tsaveRowsAnalysis(r, allRows, &countRows, true)\n\t}\n\tfor _, r := range r2 {\n\t\tsaveRowsAnalysis(r, allRows, &countRows, false)\n\t}\n\tif countRows != 0 {\n\t\treturn false\n\t}\n\tfor _, i := range allRows {\n\t\tif i != 0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func recordAdaptorDuplicateBidIDs(metricsEngine metrics.MetricsEngine, adapterBids map[openrtb_ext.BidderName]*entities.PbsOrtbSeatBid) bool {\n\tbidIDCollisionFound := false\n\tif nil == adapterBids {\n\t\treturn false\n\t}\n\tfor bidder, bid := range adapterBids {\n\t\tbidIDColisionMap := make(map[string]int, len(adapterBids[bidder].Bids))\n\t\tfor _, thisBid := range bid.Bids {\n\t\t\tif collisions, ok := bidIDColisionMap[thisBid.Bid.ID]; ok {\n\t\t\t\tbidIDCollisionFound = true\n\t\t\t\tbidIDColisionMap[thisBid.Bid.ID]++\n\t\t\t\tglog.Warningf(\"Bid.id %v :: %v collision(s) [imp.id = %v] for bidder '%v'\", thisBid.Bid.ID, collisions, thisBid.Bid.ImpID, string(bidder))\n\t\t\t\tmetricsEngine.RecordAdapterDuplicateBidID(string(bidder), 1)\n\t\t\t} else {\n\t\t\t\tbidIDColisionMap[thisBid.Bid.ID] = 1\n\t\t\t}\n\t\t}\n\t}\n\treturn bidIDCollisionFound\n}", "func uniqueOccurrences(arr []int) bool {\n\toccCount := make(map[int]int)\n\tfor _, val := range arr {\n\t\tc, ok := occCount[val]\n\t\tif !ok {\n\t\t\toccCount[val] = 1\n\t\t} else {\n\t\t\toccCount[val] = c + 1\n\t\t}\n\t}\n\tdistincNumCount := len(occCount) // all repeat numbers are collapsed\n\tdistinctOcc := make(map[int]int)\n\tfor val, occ := range occCount {\n\t\tdistinctOcc[occ] = val\n\t}\n\treturn len(distinctOcc) == distincNumCount\n}", "func MapUsersToIDs(vs []models.User) []uuid.UUID {\n\tvsm := make([]uuid.UUID, len(vs))\n\tfor i, v := range vs {\n\t\tvsm[i] = v.ID\n\t}\n\treturn vsm\n}", "func UseridIsNil() predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.IsNull(s.C(FieldUserid)))\n\t})\n}", "func SameUser(a *arn.User, b *arn.User) string {\n\tif a == nil {\n\t\treturn \"false\"\n\t}\n\n\tif b == nil {\n\t\treturn \"false\"\n\t}\n\n\tif a.ID == b.ID {\n\t\treturn \"true\"\n\t}\n\n\treturn \"false\"\n}", "func isUniq(list []stringSortKey) bool {\n\tfor i := range list {\n\t\tif i+1 < len(list) && list[i].value == list[i+1].value {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func CheckIfAlreadyExist(qr db.Queryer, diseaseid, userid int64) error {\n\n\tvar cnt int64\n\n\tsqlstr := `select count(*) from user_disease where disease_id=? and user_id=?`\n\n\terr := qr.Get(&cnt, sqlstr, diseaseid, userid)\n\n\tfmt.Println(\"err\", err)\n\n\tif err != nil {\n\t\treturn errors.New(\"Record is already present\")\n\t}\n\n\tif cnt > 0 {\n\t\treturn errors.New(\"Record is already present\")\n\t}\n\n\treturn nil\n\n}", "func ValidateUniqueIDs(c *Config) error {\n\t// Ensure no duplicate IDs\n\tIDs := make(map[int]string)\n\tfor name, node := range c.Topology {\n\t\tif first, seen := IDs[node.ID]; seen {\n\t\t\treturn fmt.Errorf(\"duplicate node ID %d seen for node %q and %q\", node.ID, first, name)\n\t\t}\n\t\tIDs[node.ID] = name\n\t\tglog.V(4).Infof(\"Node %q has ID %d\", name, node.ID)\n\t}\n\treturn nil\n}", "func selectUnique(num int, ids []string) []string {\n\tselected := make(map[string]bool)\n\tfor len(selected) < num {\n\t\tindex := rand.Intn(len(ids) - 1)\n\t\tid := ids[index]\n\t\tif _, found := selected[id]; !found {\n\t\t\tselected[id] = true\n\t\t}\n\t}\n\tresults := make([]string, 0)\n\tfor key := range selected {\n\t\tresults = append(results, key)\n\t}\n\treturn results\n}", "func (u *User) GetUserByNotUserIds(userIds []string) (users []map[string]string, err error) {\n\tdb := G.DB()\n\tvar rs *mysql.ResultSet\n\trs, err = db.Query(db.AR().From(Table_User_Name).Where(map[string]interface{}{\n\t\t\"user_id NOT\": userIds,\n\t\t\"is_delete\": User_Delete_False,\n\t}))\n\tif err != nil {\n\t\treturn\n\t}\n\tusers = rs.Rows()\n\treturn\n}", "func UseridNotIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.NotIn(s.C(FieldUserid), v...))\n\t})\n}", "func getAllStudentData() []string {\n studs := make(map[string]bool)\n for _, d := range data {\n studs[d.StudentId] = true\n }\n\n // make unique map of student names\n ids := make([]string, 0) // create a new slice\n for d := range studs {\n ids = append(ids, d)\n } \n\n return ids\n}", "func dedupLabelIdentites(labelIdentityIDs []uint32) []uint32 {\n\tseen := map[uint32]struct{}{}\n\tidx := 0\n\tfor _, id := range labelIdentityIDs {\n\t\tif _, exists := seen[id]; !exists {\n\t\t\tseen[id] = struct{}{}\n\t\t\tlabelIdentityIDs[idx] = id\n\t\t\tidx++\n\t\t}\n\t}\n\treturn labelIdentityIDs[:idx]\n}", "func (a *Api) ensureIdSet(ctx context.Context, userId string, confirmations []*models.Confirmation) {\n\n\tif len(confirmations) < 1 {\n\t\treturn\n\t}\n\tfor i := range confirmations {\n\t\t//set the userid if not set already\n\t\tif confirmations[i].UserId == \"\" {\n\t\t\tlog.Println(\"UserId wasn't set for invite so setting it\")\n\t\t\tconfirmations[i].UserId = userId\n\t\t\ta.Store.UpsertConfirmation(ctx, confirmations[i])\n\t\t}\n\t}\n\treturn\n}", "func IsTicketIDDuplicated(id string, slice []Ticket) bool {\n\tvar count = 0\n\tfor _, ticket := range slice {\n\t\tif ticket.Id == id {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count > 1\n}", "func (r *RatingRecords) TableUnique() [][]string {\n\treturn [][]string{\n\t\t[]string{\"Student\", \"Teacher\"},\n\t}\n}", "func deduplicate(data []float64) []float64 {\n\tkeys := make(map[float64]bool)\n\tuniq := []float64{}\n\tfor _, entry := range data {\n\t\tif _, value := keys[entry]; !value {\n\t\t\tkeys[entry] = true\n\t\t\tuniq = append(uniq, entry)\n\t\t}\n\t}\n\treturn uniq\n}", "func (ctx *Upgrader) getUsers(notReturn ...*Socket) []*Socket {\n\tvar users []*Socket\n\t//\n\tcontain := func(user *Socket) bool {\n\t\tfor indc := range notReturn {\n\t\t\tif user == notReturn[indc] {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\t//\n\tfor _, val := range ctx.usersSk {\n\t\tif !contain(val) {\n\t\t\tusers = append(users, val)\n\t\t}\n\t}\n\treturn users\n}", "func ArrayInt64Uniq(arr []int64) []int64 {\n\tm := make(map[int64]bool)\n\tuniq := []int64{}\n\tfor _, v := range arr {\n\t\tif !m[v] {\n\t\t\tm[v] = true\n\t\t\tuniq = append(uniq, v)\n\t\t}\n\t}\n\treturn uniq\n}", "func mergeFields(segments []*SegmentBase) (bool, []string) {\n\tfieldsSame := true\n\n\tvar segment0Fields []string\n\tif len(segments) > 0 {\n\t\tsegment0Fields = segments[0].Fields()\n\t}\n\n\tfieldsExist := map[string]struct{}{}\n\tfor _, segment := range segments {\n\t\tfields := segment.Fields()\n\t\tfor fieldi, field := range fields {\n\t\t\tfieldsExist[field] = struct{}{}\n\t\t\tif len(segment0Fields) != len(fields) || segment0Fields[fieldi] != field {\n\t\t\t\tfieldsSame = false\n\t\t\t}\n\t\t}\n\t}\n\n\trv := make([]string, 0, len(fieldsExist))\n\t// ensure _id stays first\n\trv = append(rv, \"_id\")\n\tfor k := range fieldsExist {\n\t\tif k != \"_id\" {\n\t\t\trv = append(rv, k)\n\t\t}\n\t}\n\n\tsort.Strings(rv[1:]) // leave _id as first\n\n\treturn fieldsSame, rv\n}", "func (m *AmbulanceMutation) HasuserIDs() (ids []int) {\n\tif id := m.hasuser; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (a BlogAuthor) CheckThatAuthorMatchesDuplicates(as []BlogAuthor) {\n\tfor _, da := range as {\n\t\tif a.Id == da.Id && a != da {\n\t\t\tpanic(\"Author does not match another field-by-field with same id\")\n\t\t}\n\t}\n}", "func populateObjectIds(infos []*resource.Info, t *testing.T) sets.String {\n\tuids := sets.NewString()\n\tfor _, currInfo := range infos {\n\t\tcurrObj := currInfo.Object\n\t\tmetadata, err := meta.Accessor(currObj)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Unexpected error retrieving object metadata: %#v\", err)\n\t\t}\n\t\tuid := string(metadata.GetUID())\n\t\tuids.Insert(uid)\n\t}\n\treturn uids\n}", "func (a *autoconnector) filterDuplicates(pks []cipher.PubKey, trs []*transport.ManagedTransport) []cipher.PubKey {\n\tvar absent []cipher.PubKey\n\tfor _, pk := range pks {\n\t\tfound := false\n\t\tfor _, tr := range trs {\n\t\t\tif tr.Entry.HasEdge(pk) {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\tabsent = append(absent, pk)\n\t\t}\n\t}\n\treturn absent\n}", "func (i *IdentityMapping) Empty() bool {\n\treturn len(i.uids) == 0 && len(i.gids) == 0\n}", "func (ids IDSlice) Equal(o IDSlice) bool {\n\tif len(ids) != len(o) {\n\t\treturn false\n\t}\n\tfor idx, id := range ids {\n\t\tif o[idx] != id {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func dedup(list []*OsuSearchMapset) []*OsuSearchMapset {\n\tuniq := []*OsuSearchMapset{}\n\tfor _, mapset := range list {\n\t\tcontains := false\n\t\tfor _, existing := range uniq {\n\t\t\tif mapset.ID == existing.ID {\n\t\t\t\tcontains = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !contains {\n\t\t\tuniq = append(uniq, mapset)\n\t\t}\n\t}\n\treturn uniq\n}", "func UseridEqualFold(v string) predicate.Project {\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\ts.Where(sql.EqualFold(s.C(FieldUserid), v))\n\t})\n}", "func (suite *FileSourceInternalTestSuite) TestUniqueForCombinedValues() {\n\tinput := []int{1, 2, 2}\n\tresut := unique(input)\n\tassert.Len(suite.T(), resut, 2)\n}", "func (c *User) HasID() bool { return c.ID > 0 }", "func TableIdsEach(timeTable map[string]map[rune][]uint, test func([]uint) bool) bool {\n\tb := true\n\tfor _, day := range timeTable {\n\t\tfor _, ids := range day {\n\t\t\tif test(ids) {\n\t\t\t\tb = false\n\t\t\t}\n\t\t}\n\t}\n\treturn b\n}", "func getUniqueFields(schemaFieldsRequired []string, fieldsRequired []string) []string {\n\tvar unique []string\n\tvar index *int\n\n\tfor j, schemaFieldRequired := range schemaFieldsRequired {\n\t\tindex = nil\n\t\tfor i, fieldRequired := range fieldsRequired {\n\t\t\ti := i\n\t\t\tif schemaFieldRequired == fieldRequired {\n\t\t\t\tindex = &i\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif index == nil {\n\t\t\tunique = append(unique, schemaFieldsRequired[j])\n\t\t}\n\t}\n\treturn unique\n}", "func (suite *FileSourceInternalTestSuite) TestUniqueForDuplicateValues() {\n\tinput := []int{1, 1}\n\tresut := unique(input)\n\tassert.Len(suite.T(), resut, 1)\n}", "func ProfilesExistByIDs(ids []int64, tx *sql.Tx) (bool, error) {\n\tcount := 0\n\tif err := tx.QueryRow(`SELECT count(*) from profile where id = ANY($1)`, pq.Array(ids)).Scan(&count); err != nil {\n\t\treturn false, errors.New(\"querying profiles existence from id: \" + err.Error())\n\t}\n\treturn count == len(ids), nil\n}", "func recordsSliceEquals(l, r []Record) bool {\n\tif len(l) != len(r) {\n\t\treturn false\n\t}\n\tfor i := range l {\n\t\tif l[i] != r[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (d UserData) HasUsers() bool {\n\treturn d.ModelData.Has(models.NewFieldName(\"Users\", \"user_ids\"))\n}", "func getRelevantUsers(s *PartyMatchState) map[string]struct{} {\n\trelevantUsers := make(map[string]struct{})\n\tfor userID := range s.presences {\n\t\trelevantUsers[userID] = struct{}{}\n\t}\n\n\tfor userID := range s.invitations {\n\t\trelevantUsers[userID] = struct{}{}\n\t}\n\n\tfor userID := range s.approvedForRejoin {\n\t\trelevantUsers[userID] = struct{}{}\n\t}\n\n\treturn relevantUsers\n}", "func FilterDuplicates(candidatesPtr *[]Candidate, hasUMI bool) {\n\tcandidates := *candidatesPtr\n\tcandidatesMap := groupCandidatesByGenePair(candidates)\n\tvar (\n\t\tuniqIndices []int\n\t\tuniqUMIs uniqueUMIs\n\t\tvalidIndices []int\n\t)\n\tfor _, indices := range candidatesMap {\n\t\tif hasUMI {\n\t\t\tuniqUMIs = uniqUMIs[:0]\n\t\t\tuniqUMIs = append(uniqUMIs, candidates[indices[0]].Frag.UMI())\n\t\t} else {\n\t\t\tuniqIndices = uniqIndices[:0]\n\t\t\tuniqIndices = append(uniqIndices, indices[0])\n\t\t}\n\t\tvalidIndices = append(validIndices, indices[0])\n\t\tfor _, ci := range indices[1:] {\n\t\t\tcB := candidates[ci]\n\t\t\tif hasUMI {\n\t\t\t\tumi := cB.Frag.UMI()\n\t\t\t\tfound := false\n\t\t\t\t// Check if umi is considered to be found in uniqUMIs and will replace\n\t\t\t\t// the found one in uniqUMIs if query_umi has less 'N's.\n\t\t\t\tfor ui := range uniqUMIs {\n\t\t\t\t\tif hammingDistance(umi, uniqUMIs[ui]) <= 2 {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tif numUnknownBases(umi) < numUnknownBases(uniqUMIs[ui]) {\n\t\t\t\t\t\t\tuniqUMIs[ui] = umi\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif ReproduceBug {\n\t\t\t\t\t\t\t// TODO(saito) need to replace other UMIs too.\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tvalidIndices = append(validIndices, ci)\n\t\t\t\t\tuniqUMIs = append(uniqUMIs, umi)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Arbitrarily set 5% distance threshold.\n\t\t\t\ttotalLen := len(cB.Frag.R1Seq) + len(cB.Frag.R2Seq)\n\t\t\t\tmaxDist := max(1, int(float64(totalLen)*0.05))\n\t\t\t\tfound := false\n\t\t\t\tfor _, ui := range uniqIndices {\n\t\t\t\t\tif d := cB.Frag.HammingDistance(candidates[ui].Frag); d <= maxDist {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\tuniqIndices = append(uniqIndices, ci)\n\t\t\t\t\tvalidIndices = append(validIndices, ci)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t*candidatesPtr = subsetCandidates(*candidatesPtr, validIndices)\n}", "func generateEmpty(meta TableMeta, values []map[string]interface{}) []map[string]interface{} {\n\tif PK_UUID != meta.Type {\n\t\treturn values\n\t}\n\n\tfor i, v := range values {\n\t\tif _, ok := v[meta.PrimaryKey]; !ok || nil == v[meta.PrimaryKey] {\n\t\t\tv4, _ := uuid.NewV4()\n\t\t\tvalues[i][meta.PrimaryKey] = v4.String()\n\t\t}\n\t\tif _, ok := v[CREATED_AT]; !ok || nil == v[CREATED_AT] {\n\t\t\tnow := time.Now().UTC()\n\t\t\tvalues[i][CREATED_AT] = now.Format(time.RFC3339)\n\t\t}\n\t}\n\n\treturn values\n}", "func removeDuplicates(collection *mongo.Collection) {\n\tctx := context.TODO()\n\t// Group transactions by OpenSea ID. Store MongoDB IDs and count of matching transactions for each ID\n\tgroupStage := bson.D{{\n\t\t\"$group\",\n\t\tbson.D{\n\t\t\t{\"_id\",\n\t\t\t\t\"$id\"},\n\t\t\t{\"dups\",\n\t\t\t\tbson.D{{\n\t\t\t\t\t\"$addToSet\",\n\t\t\t\t\t\"$_id\"}}},\n\t\t\t{\"count\",\n\t\t\t\tbson.D{{\n\t\t\t\t\t\"$sum\",\n\t\t\t\t\t1}}}}}}\n\t// Only match transactions that appear more than once in the database\n\tmatchStage := bson.D{{\n\t\t\"$match\",\n\t\tbson.D{\n\t\t\t{\"count\",\n\t\t\t\tbson.D{{\n\t\t\t\t\t\"$gt\",\n\t\t\t\t\t1}}}}}}\n\n\tcursor, err := collection.Aggregate(ctx, mongo.Pipeline{groupStage, matchStage})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tvar duplicates []interface{}\n\n\tfor cursor.Next(ctx) {\n\t\t// decode document\n\t\tvar dups Duplicates\n\t\terr := cursor.Decode(&dups)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\t// keep 1 item from slice\n\t\ttoRemove := dups.Dups[1:]\n\t\t// add all other ids from slice to duplicates array\n\t\tfor _, v := range toRemove {\n\t\t\tduplicates = append(duplicates, v)\n\t\t}\n\t}\n\tfmt.Printf(\"\\nDuplicates found: %v\\n\", len(duplicates))\n\t// remove duplicates\n\tif len(duplicates) > 0 {\n\t\tres, err := collection.DeleteMany(ctx, bson.D{{\"_id\", bson.D{{\"$in\", duplicates}}}})\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Printf(\"Duplicates removed: %v\\n\", res.DeletedCount)\n\t}\n}", "func (q Query) Unique() Query {\n\tsortByID(q.terms)\n\tr := Query{g: q.g}\n\tfor i, t := range q.terms {\n\t\tif i == 0 || t.UID != q.terms[i-1].UID {\n\t\t\tr.terms = append(r.terms, t)\n\t\t}\n\t}\n\treturn r\n}", "func FindDupes(s store.SecretStore, id store.SecretIdentifier, envs []store.Environment) ([]store.SecretIdentifier, error) {\n\tsecret, err := s.Read(id)\n\tif err != nil {\n\t\treturn []store.SecretIdentifier{}, err\n\t}\n\tvar dupes []store.SecretIdentifier\n\tfor _, e := range envs {\n\t\tlog.Printf(\"reading from %s\\n\", e.String())\n\t\tids, err := s.ListAll(e)\n\t\tlog.Printf(\"total secrets: %d\\n\", len(ids))\n\t\tif err != nil {\n\t\t\treturn []store.SecretIdentifier{}, err\n\t\t}\n\t\tfor num, id := range ids {\n\t\t\tif num%100 == 0 {\n\t\t\t\tlog.Printf(\"reading %04d/%04d\\n\", num, len(ids))\n\t\t\t}\n\t\t\t// With Parameter Store, the maximal normal limit is 40 requests per second.\n\t\t\t// 1000 ms / 67 ms ~= 15 secrets per second.\n\t\t\ttime.Sleep(67 * time.Millisecond)\n\t\t\tnewSecret, err := s.Read(id)\n\t\t\tif err != nil {\n\t\t\t\t// We assume that any missing secret isn't an issue\n\t\t\t\t// with the duplicate checking. We'll log instead of erroring.\n\t\t\t\tlog.Printf(\"error reading secret: %v\\n\", err)\n\t\t\t}\n\t\t\tif newSecret.Data == secret.Data {\n\t\t\t\tdupes = append(dupes, id)\n\t\t\t}\n\t\t}\n\t}\n\treturn dupes, nil\n}", "func (err *DuplicatedRecord) DuplicatedRecord() {}", "func (lkp *lookup) MapNonUniqueLookup(vcursor VCursor, ids []interface{}) ([][][]byte, error) {\n\tout := make([][][]byte, 0, len(ids))\n\tfor _, id := range ids {\n\t\tresult, err := vcursor.Execute(lkp.sel, map[string]interface{}{\n\t\t\tlkp.From: id,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"lookup.Map: %v\", err)\n\t\t}\n\t\tvar ksids [][]byte\n\t\tif lkp.isHashedIndex {\n\t\t\tfor _, row := range result.Rows {\n\t\t\t\tnum, err := getNumber(row[0].ToNative())\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"lookup.Map: %v\", err)\n\t\t\t\t}\n\t\t\t\tksids = append(ksids, vhash(num))\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, row := range result.Rows {\n\t\t\t\tksids = append(ksids, row[0].Raw())\n\t\t\t}\n\t\t}\n\t\tout = append(out, ksids)\n\t}\n\treturn out, nil\n}", "func (r *role) Idxs(peers [2]wire.Address) (our, their channel.Index) {\n\tif r.setup.Identity.Address().Equal(peers[0]) {\n\t\treturn 0, 1\n\t} else if r.setup.Identity.Address().Equal(peers[1]) {\n\t\treturn 1, 0\n\t}\n\tpanic(\"identity not in peers\")\n}", "func distanceLimitedPathsExist(n int, edgeList [][]int, queries [][]int) []bool {\n\tans := make([]bool, len(queries))\n\tarr := make([]int, n)\n\tfor i := range arr {\n\t\tarr[i] = -1\n\t}\n\tmapp := make(map[[2]int]struct{})\n\tnewqueries := make([][]int, len(queries))\n\tfor i := range newqueries {\n\t\tnewqueries[i] = []int{queries[i][0], queries[i][1], queries[i][2], i}\n\t}\n\n\t// sort edges and queries\n\tsort.Slice(edgeList, func(i, j int) bool {\n\t\treturn edgeList[i][2] < edgeList[j][2]\n\t})\n\tsort.Slice(newqueries, func(i, j int) bool {\n\t\treturn newqueries[i][2] < newqueries[j][2]\n\t})\n\n\t// main logic\n\tei := 0\n\tfor _, q := range newqueries {\n\t\t// union: add edge[ei] that less than query to union set\n\t\tfor ei < len(edgeList) && edgeList[ei][2] < q[2] {\n\t\t\ta, b := edgeList[ei][0], edgeList[ei][1]\n\t\t\tei++\n\t\t\tif _, ok := mapp[[2]int{a, b}]; ok { // ignore duplicated edge\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tmapp[[2]int{a, b}] = struct{}{}\n\n\t\t\t// union\n\t\t\tra, rb := root(arr, a), root(arr, b)\n\t\t\tif ra == rb { // already in same set\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tarr[rb] = ra\n\t\t}\n\t\t// find: test if two query points are in same set\n\t\tr0, r1 := root(arr, q[0]), root(arr, q[1])\n\t\tif r0 == r1 {\n\t\t\tans[q[3]] = true // set original index\n\t\t}\n\t}\n\treturn ans\n}", "func (u *DnsUpdater) getCurrentRecordIDs(topRecord TXTRecord) (bool, string, []string) {\n\tvar topRecordIDToUpdate string\n\tvar recordIDsToDelete []string = []string{}\n\n\tallTopRecordIDs, _ := u.Api.FilterTXTRecords(u.topDomain, \"v=spf1\")\n\tif len(allTopRecordIDs) == 0 {\n\t\t// no top record found, can't really do anything\n\t\t// still need to add new DNS records\n\t\treturn true, topRecordIDToUpdate, recordIDsToDelete\n\t}\n\n\tgoodTopRecordIDs, _ := u.Api.FilterTXTRecords(u.topDomain, topRecord.txt)\n\tvar goodTopRecordID string\n\tif len(goodTopRecordIDs) > 0 {\n\t\t// It's possible that multiple match. Let the others get deleted.\n\t\tgoodTopRecordID = goodTopRecordIDs[0]\n\t}\n\n\tif len(allTopRecordIDs) == 1 && allTopRecordIDs[0] == goodTopRecordID {\n\t\t// Everything is correct, so do nothing!\n\t\treturn false, topRecordIDToUpdate, recordIDsToDelete\n\t}\n\n\tfor _, topRecordID := range allTopRecordIDs {\n\t\tif topRecordIDToUpdate == \"\" {\n\t\t\ttopRecordIDToUpdate = topRecordID\n\t\t} else {\n\t\t\trecordIDsToDelete = append(recordIDsToDelete, topRecordID)\n\t\t}\n\t\tif content, err := u.Api.GetTXTRecordContent(topRecordID); err == nil {\n\t\t\ttopSPF := spf.NewSPF()\n\t\t\tif topSPF.Parse(content) == nil {\n\t\t\t\tfor _, include := range topSPF.Include {\n\t\t\t\t\tsubRecordIDs, _ := u.Api.FilterTXTRecords(include, \"v=spf1\")\n\t\t\t\t\trecordIDsToDelete = append(recordIDsToDelete, subRecordIDs...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn true, topRecordIDToUpdate, recordIDsToDelete\n}", "func concatUnique(collections ...[]string) []string {\n\tresultSet := make(map[string]struct{})\n\tfor _, c := range collections {\n\t\tfor _, i := range c {\n\t\t\tif _, ok := resultSet[i]; !ok {\n\t\t\t\tresultSet[i] = struct{}{}\n\t\t\t}\n\t\t}\n\t}\n\tresult := make([]string, 0, len(resultSet))\n\tfor k := range resultSet {\n\t\tresult = append(result, k)\n\t}\n\treturn result\n}", "func (m *MockDatabase) GetUsersID() ([]uint64, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersID\")\n\tret0, _ := ret[0].([]uint64)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (m *NamespaceMapper) checkMapUniqueness() bool {\n\tvar labelSelector = labels.Set(map[string]string{liqoconst.RemoteClusterID: m.foreignClusterID}).AsSelector()\n\tret, err := m.lister.ByNamespace(m.namespace).List(labelSelector)\n\tif err != nil {\n\t\treturn false\n\t}\n\tif len(ret) > 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *MockUserRepositoryInterface) GetUsersWhereUserIDs(arg0 []uint64) ([]*db.User, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetUsersWhereUserIDs\", arg0)\n\tret0, _ := ret[0].([]*db.User)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func newUnique(UUIDs []string) (unique string) {\n\tvar stored bool\n\tfor {\n\t\tunique = uuid.New().String()\n\t\tfor _, UUID := range UUIDs {\n\t\t\tif UUID == unique {\n\t\t\t\tstored = true\n\t\t\t}\n\t\t}\n\t\tif !stored {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn\n}", "func GetValidBids(r *http.Request, jUUID uuid.UUID) (*sql.Rows, error) {\n\tsqlStmt := `\n\tSELECT b1.uuid, b1.rate\n\tFROM bids b1\n\tWHERE b1.job_uuid = $1 AND\n\t\tb1.meets_requirements = true AND\n\t\tb1.late = false AND\n\t\tNOT EXISTS(SELECT 1\n\t\t\tFROM bids b2\n\t\t\tINNER JOIN jobs j ON (b2.uuid = j.win_bid_uuid)\n\t\t\tWHERE j.active = true \n\t\t\t\tAND b2.device_uuid = b1.device_uuid\n\t\t\t\tAND b2.miner_uuid = b2.miner_uuid\n\t\t)\n\tORDER BY\n\t\tb1.rate ASC,\n\t\tb1.created_at ASC\n\tLIMIT 2\n\t`\n\trows, err := db.Query(sqlStmt, jUUID)\n\tif err != nil {\n\t\tmessage := \"error querying for valid bids\"\n\t\tpqErr, ok := err.(*pq.Error)\n\t\tif ok {\n\t\t\tlog.Sugar.Errorw(message,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"url\", r.URL,\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"jID\", jUUID,\n\t\t\t\t\"pq_sev\", pqErr.Severity,\n\t\t\t\t\"pq_code\", pqErr.Code,\n\t\t\t\t\"pq_msg\", pqErr.Message,\n\t\t\t\t\"pq_detail\", pqErr.Detail,\n\t\t\t)\n\t\t} else {\n\t\t\tlog.Sugar.Errorw(message,\n\t\t\t\t\"method\", r.Method,\n\t\t\t\t\"url\", r.URL,\n\t\t\t\t\"err\", err.Error(),\n\t\t\t\t\"jID\", jUUID,\n\t\t\t)\n\t\t}\n\t}\n\treturn rows, err\n}", "func QueryResponsesEqual(r1, r2 []QueryResponse) bool {\n\tif len(r1) != len(r2) {\n\t\treturn false\n\t}\n\tfor i, r := range r1 {\n\t\tif !r.QueryResult.Equal(r2[i].QueryResult) {\n\t\t\treturn false\n\t\t}\n\t\tif !reflect.DeepEqual(r.QueryError, r2[i].QueryError) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func inQueryBuilder(identifiers []*sharedModels.GetUsernamesRequest) string {\n\tif len(identifiers) < 1 {\n\t\treturn \"\"\n\t}\n\n\tquery := \"SELECT id, username FROM users WHERE id IN\"\n\tquery += \"(\"\n\n\tfor i := 0; i < len(identifiers); i++ {\n\t\tif i+1 < len(identifiers) {\n\t\t\t// NOT LAST\n\t\t\tquery += strconv.Itoa(identifiers[i].ID) + \",\"\n\t\t} else {\n\t\t\t//LAST\n\t\t\tquery += strconv.Itoa(identifiers[i].ID)\n\t\t}\n\t}\n\n\tquery += \")\"\n\treturn query\n}", "func diffItems(val []int) int {\n hashed := make(map[int]bool)\n for _, v := range val {\n hashed[v] = true\n }\n\n return len(hashed)\n}", "func (m *UserMutation) UserofIDs() (ids []int) {\n\tfor id := range m.userof {\n\t\tids = append(ids, id)\n\t}\n\treturn\n}", "func mapDedupe(s []int) []int {\n\tnewS := []int{}\n\tm := make(map[int]bool)\n\tfor _, v := range s {\n\t\tif ok := m[v]; !ok {\n\t\t\tm[v] = true\n\t\t\tnewS = append(newS, v)\n\t\t}\n\t}\n\treturn newS\n}", "func UsersEmpty() (bool, error) {\n\tq := \"SELECT count(*) FROM users\"\n\tc := 0\n\terr := dbConn.QueryRow(q).Scan(&c)\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn c == 0, nil\n}", "func uniq(duplicated []string) []string {\n\tkeys := make(map[string]bool)\n\tresult := []string{}\n\tfor _, entry := range duplicated {\n\t\tif _, value := keys[entry]; !value {\n\t\t\tkeys[entry] = true\n\t\t\tresult = append(result, entry)\n\t\t}\n\t}\n\treturn result\n}", "func TestHasNoCollisions(t *testing.T) {\n\tCOUNT := 100 * 1000\n\tused := make(map[string]bool)\n\tfor i := 0; i < COUNT; i++ {\n\t\tid, err := Gonoid()\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Nanoid error: %v\", err)\n\t\t}\n\t\tif used[id] {\n\t\t\tt.Errorf(\"Collision error! Id %v found for test arr %v\", id, used)\n\t\t}\n\t\tused[id] = true\n\t}\n}", "func UseridIn(vs ...string) predicate.Project {\n\tv := make([]interface{}, len(vs))\n\tfor i := range v {\n\t\tv[i] = vs[i]\n\t}\n\treturn predicate.Project(func(s *sql.Selector) {\n\t\t// if not arguments were provided, append the FALSE constants,\n\t\t// since we can't apply \"IN ()\". This will make this predicate falsy.\n\t\tif len(vs) == 0 {\n\t\t\ts.Where(sql.False())\n\t\t\treturn\n\t\t}\n\t\ts.Where(sql.In(s.C(FieldUserid), v...))\n\t})\n}", "func getSelectedUserIds(form url.Values) (values map[string]string) {\n\tvalues = make(map[string]string)\n\tfor k, _ := range form {\n\t\tif strings.Contains(k, \"remember-\") {\n\t\t\ttmp := strings.Split(k, \"-\")\n\t\t\tuserId := tmp[1]\n\t\t\tvalues[userId] = \"not yet figured out\"\n\t\t}\n\t}\n\n\t// for any userIds selected, get the access value\n\tfor k, _ := range values {\n\t\taccessValue, found := form[\"access-\"+k]\n\t\tif found {\n\t\t\tvalues[k] = accessValue[0]\n\t\t}\n\t}\n\treturn values\n}", "func batchNovel(absent hash.HashSet, batch int) (remainder hash.HashSet, batches []hash.HashSet) {\n\tcurr := make(hash.HashSet, batch)\n\tfor h := range absent {\n\t\tcurr.Insert(h)\n\t\tif curr.Size() >= batch {\n\t\t\tbatches = append(batches, curr)\n\t\t\tcurr = make(hash.HashSet, batch)\n\t\t}\n\t}\n\tremainder = curr\n\treturn\n}", "func UserIDIn(vs ...string) predicate.OfflineSession {\n\treturn predicate.OfflineSession(sql.FieldIn(FieldUserID, vs...))\n}", "func deduplicate(rows []map[string]string) []map[string]string {\n\tvar deduplicated []map[string]string\n\n\tseenKeys := make(map[string]bool)\n\n\tfor _, row := range rows {\n\t\tif _, ok := seenKeys[row[\"fullkey\"]]; !ok {\n\t\t\tseenKeys[row[\"fullkey\"]] = true\n\t\t\tdeduplicated = append(deduplicated, row)\n\t\t}\n\t}\n\n\treturn deduplicated\n}", "func (m *UserMutation) CreateByIDs() (ids []int) {\n\tif id := m.create_by; id != nil {\n\t\tids = append(ids, *id)\n\t}\n\treturn\n}", "func (v ID) Nil() bool {\n\treturn !v.present\n}" ]
[ "0.59897", "0.5627775", "0.55748653", "0.5514046", "0.5288824", "0.5166681", "0.50685716", "0.501695", "0.49544287", "0.49241403", "0.4921661", "0.4905855", "0.49051106", "0.49011508", "0.48972017", "0.48917225", "0.48443356", "0.48391682", "0.48253223", "0.4823398", "0.47944167", "0.47831717", "0.47762704", "0.47680867", "0.4731125", "0.4730115", "0.47228843", "0.47196382", "0.47116628", "0.46817645", "0.46748143", "0.46713042", "0.46695068", "0.4669113", "0.46682525", "0.46615356", "0.46604374", "0.46556646", "0.46525866", "0.46514034", "0.46421748", "0.46387196", "0.46230477", "0.46138296", "0.46120554", "0.4607786", "0.46047756", "0.46005654", "0.4594208", "0.45873857", "0.45859745", "0.4579004", "0.45676506", "0.45614976", "0.4535775", "0.45272505", "0.452398", "0.4519029", "0.45187697", "0.45186543", "0.4514035", "0.4513743", "0.45111537", "0.4505213", "0.4502702", "0.45026615", "0.44919097", "0.44892374", "0.44865754", "0.44822207", "0.44806606", "0.44762155", "0.44713563", "0.44704154", "0.4467355", "0.44613445", "0.445279", "0.44489738", "0.44457522", "0.44422397", "0.4441892", "0.44412953", "0.44401738", "0.44389012", "0.443833", "0.443323", "0.44286358", "0.4424114", "0.44215202", "0.44197783", "0.4415411", "0.44047087", "0.4403304", "0.44015002", "0.4401139", "0.43921903", "0.43855834", "0.4382913", "0.43779895", "0.43727282" ]
0.4786434
21
Info fills out and returns a WalletInfo struct.
func (w *Wallet) Info() modules.WalletInfo { wi := modules.WalletInfo{ Balance: w.Balance(false), FullBalance: w.Balance(true), } counter := w.mu.RLock() wi.NumAddresses = len(w.keys) w.mu.RUnlock(counter) var sortingSpace crypto.HashSlice for va := range w.visibleAddresses { sortingSpace = append(sortingSpace, crypto.Hash(va)) } sort.Sort(sortingSpace) for _, va := range sortingSpace { wi.VisibleAddresses = append(wi.VisibleAddresses, types.UnlockHash(va)) } return wi }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (dcr *ExchangeWallet) Info() *asset.WalletInfo {\n\treturn WalletInfo\n}", "func (dcr *ExchangeWallet) Info() *asset.WalletInfo {\n\treturn WalletInfo\n}", "func (d *Driver) Info() *asset.WalletInfo {\n\treturn WalletInfo\n}", "func (d *Driver) Info() *asset.WalletInfo {\n\treturn WalletInfo\n}", "func (d *Driver) Info() *asset.WalletInfo {\n\treturn walletInfo\n}", "func (btc *ExchangeWallet) Info() *asset.WalletInfo {\n\treturn btc.walletInfo\n}", "func (c Client) Info(w Wallet) (wtx Wallet, err error) {\n\tc.header[\"X-Api-Key\"] = w.Adminkey\n\tresp, err := req.Get(w.url+\"/api/v1/wallet\", w.header, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif resp.Response().StatusCode >= 300 {\n\t\tvar reqErr Error\n\t\tresp.ToJSON(&reqErr)\n\t\terr = reqErr\n\t\treturn\n\t}\n\n\terr = resp.ToJSON(&wtx)\n\treturn\n}", "func (trading *TradingProvider) Info() (ui schemas.UserInfo, err error) {\n\tvar resp map[string]UserBalance\n\tvar b []byte\n\n\tuserBalance := make(map[string]schemas.Balance)\n\n\tpayload := httpclient.Params()\n\tnonce := time.Now().UnixNano()\n\tpayload.Set(\"nonce\", strconv.FormatInt(nonce, 10))\n\tpayload.Set(\"command\", commandBalance)\n\n\tb, err = trading.httpClient.Post(tradingAPI, httpclient.Params(), payload, true)\n\tif err != nil {\n\t\treturn\n\t}\n\tif err = json.Unmarshal(b, &resp); err != nil {\n\t\treturn\n\t}\n\tfor coin, value := range resp {\n\t\tuserBalance[coin] = value.Map(coin)\n\t}\n\n\tprices, err := trading.prices()\n\tif err != nil {\n\t\tlog.Println(\"Error getting prices for balances\", err)\n\t}\n\n\tui.Balances = userBalance\n\tui.Prices = prices\n\treturn\n}", "func (blockchain *Blockchain) Info(_ abciTypes.RequestInfo) (resInfo abciTypes.ResponseInfo) {\n\thash := blockchain.appDB.GetLastBlockHash()\n\theight := int64(blockchain.appDB.GetLastHeight())\n\treturn abciTypes.ResponseInfo{\n\t\tVersion: version.Version,\n\t\tAppVersion: version.AppVer,\n\t\tLastBlockHeight: height,\n\t\tLastBlockAppHash: hash,\n\t}\n}", "func (f *FFS) Info(ctx context.Context) (api.InstanceInfo, error) {\n\tres, err := f.client.Info(ctx, &rpc.InfoRequest{})\n\tif err != nil {\n\t\treturn api.InstanceInfo{}, err\n\t}\n\n\tbalances := make([]api.BalanceInfo, len(res.Info.Balances))\n\tfor i, bal := range res.Info.Balances {\n\t\tbalances[i] = api.BalanceInfo{\n\t\t\tAddrInfo: api.AddrInfo{\n\t\t\t\tName: bal.Addr.Name,\n\t\t\t\tAddr: bal.Addr.Addr,\n\t\t\t\tType: bal.Addr.Type,\n\t\t\t},\n\t\t\tBalance: uint64(bal.Balance),\n\t\t}\n\t}\n\n\tpins := make([]cid.Cid, len(res.Info.Pins))\n\tfor i, pin := range res.Info.Pins {\n\t\tc, err := util.CidFromString(pin)\n\t\tif err != nil {\n\t\t\treturn api.InstanceInfo{}, err\n\t\t}\n\t\tpins[i] = c\n\t}\n\n\treturn api.InstanceInfo{\n\t\tID: ffs.APIID(res.Info.Id),\n\t\tDefaultStorageConfig: fromRPCStorageConfig(res.Info.DefaultStorageConfig),\n\t\tBalances: balances,\n\t\tPins: pins,\n\t}, nil\n}", "func WalletInfo(chains []kmdgo.AppType) []WInfo {\n\tvar wallets []WInfo\n\n\t// fmt.Println(chains)\n\n\tstats, err := kmdgo.NewAppType(\"DEX\").DEXStats()\n\tif err != nil {\n\t\tfmt.Printf(\"Code: %v\\n\", stats.Error.Code)\n\t\tfmt.Printf(\"Message: %v\\n\\n\", stats.Error.Message)\n\t\t// log.Fatalln(\"Err happened\", err)\n\t}\n\n\t// fmt.Println(\"stats value\", stats)\n\t// fmt.Println(\"Recvaddr\", stats.Result.Recvaddr)\n\t// fmt.Println(\"RecvZaddr\", stats.Result.RecvZaddr)\n\n\tfor _, v := range chains {\n\t\t// fmt.Println(i)\n\t\t// fmt.Println(v)\n\t\tif v == \"KMD\" {\n\t\t\tv = \"komodo\"\n\t\t}\n\n\t\tappName := kmdgo.NewAppType(v)\n\n\t\tvar info kmdgo.GetInfo\n\n\t\tinfo, err := appName.GetInfo()\n\t\t// fmt.Println(info.Error.Message)\n\t\tif err != nil {\n\t\t\t// fmt.Printf(\"Code: %v\\n\", info.Error.Code)\n\t\t\t// fmt.Printf(\"Message: %v\\n\\n\", info.Error.Message)\n\t\t\tif info.Error.Message == \"Loading block index...\" {\n\t\t\t\tfmt.Println(v, \"- Err happened:\", info.Error.Message)\n\t\t\t\twallets = append(wallets, WInfo{string(v), \"Loading...\", 0.0, 0, false})\n\t\t\t} else if info.Error.Message == \"Rescanning...\" {\n\t\t\t\tfmt.Println(v, \"- Err happened:\", info.Error.Message)\n\t\t\t\twallets = append(wallets, WInfo{string(v), \"Rescanning...\", 0.0, 0, false})\n\t\t\t} else {\n\t\t\t\tfmt.Println(v, \"- Err happened:\", err)\n\t\t\t\twallets = append(wallets, WInfo{string(v), \"Offline\", 0.0, 0, false})\n\t\t\t}\n\t\t} else {\n\t\t\tif info.Error.Message == \"connection refused\" {\n\t\t\t\tfmt.Println(v, \"- Err happened:\", info.Error.Message)\n\t\t\t\twallets = append(wallets, WInfo{string(v), \"Offline\", 0.0, 0, false})\n\t\t\t} else {\n\t\t\t\t// Check status of the blockchain sync\n\t\t\t\tvar tempSyncStatus bool\n\t\t\t\tif info.Result.Longestchain != info.Result.Blocks {\n\t\t\t\t\ttempSyncStatus = false\n\t\t\t\t} else {\n\t\t\t\t\ttempSyncStatus = true\n\t\t\t\t}\n\n\t\t\t\tif v == \"PIRATE\" {\n\t\t\t\t\t// fmt.Println(\"it is PIRATE\")\n\t\t\t\t\tvar zblc kmdgo.ZGetBalance\n\n\t\t\t\t\targs := make(kmdgo.APIParams, 2)\n\t\t\t\t\targs[0] = stats.Result.RecvZaddr\n\t\t\t\t\t//args[1] = 1\n\t\t\t\t\t// fmt.Println(args)\n\n\t\t\t\t\tzblc, err := appName.ZGetBalance(args)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Printf(\"Code: %v\\n\", zblc.Error.Code)\n\t\t\t\t\t\tfmt.Printf(\"Message: %v\\n\\n\", zblc.Error.Message)\n\t\t\t\t\t\t// log.Fatalln(\"Err happened\", err)\n\t\t\t\t\t}\n\n\t\t\t\t\t// fmt.Println(\"zblc value\", zblc)\n\t\t\t\t\t// fmt.Println(\"-------\")\n\t\t\t\t\t// fmt.Printf(\"\\n%0.8f\\n\", zblc.Result)\n\n\t\t\t\t\twallets = append(wallets, WInfo{\n\t\t\t\t\t\tTicker: info.Result.Name,\n\t\t\t\t\t\tStatus: \"Online\",\n\t\t\t\t\t\tBalance: zblc.Result,\n\t\t\t\t\t\tBlocks: info.Result.Longestchain,\n\t\t\t\t\t\tSynced: tempSyncStatus,\n\t\t\t\t\t})\n\n\t\t\t\t} else {\n\t\t\t\t\twallets = append(wallets, WInfo{\n\t\t\t\t\t\tTicker: info.Result.Name,\n\t\t\t\t\t\tStatus: \"Online\",\n\t\t\t\t\t\tBalance: info.Result.Balance,\n\t\t\t\t\t\tBlocks: info.Result.Longestchain,\n\t\t\t\t\t\tSynced: tempSyncStatus,\n\t\t\t\t\t})\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t// fmt.Println(wallets)\n\treturn wallets\n}", "func (a *Transactions) Info(ctx context.Context, id crypto.Digest) (TransactionInfo, *Response, error) {\n\turl, err := joinUrl(a.options.BaseUrl, fmt.Sprintf(\"/transactions/info/%s\", id.String()))\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\treq, err := http.NewRequest(\"GET\", url.String(), nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tbuf := new(bytes.Buffer)\n\tresponse, err := doHttp(ctx, a.options, req, buf)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\n\tvar tt proto.TransactionTypeVersion\n\tif err = json.Unmarshal(buf.Bytes(), &tt); err != nil {\n\t\treturn nil, response, errors.Wrap(err, \"TransactionTypeVersion unmarshal\")\n\t}\n\n\tout, err := guessTransactionInfoType(&tt)\n\tif err != nil {\n\t\treturn nil, response, errors.Wrap(err, \"Guess transaction info type failed\")\n\t}\n\n\terr = json.Unmarshal(buf.Bytes(), &out)\n\tif err != nil {\n\t\treturn nil, response, &ParseError{Err: err}\n\t}\n\n\treturn out, response, nil\n}", "func (sess *Session) Info() *payment.UserInfo {\n\n\tvar info = &payment.UserInfo{}\n\tif sess.Payment != nil {\n\t\tinfo = sess.Payment.Info()\n\t}\n\n\tif sess.IP != \"\" {\n\t\tinfo.Ip = sess.IP\n\t}\n\n\treturn info\n}", "func Info(mi models.MarketInfo, ratio float64, blocks int64) *genModels.Info {\n\tp := mi.GetPrice()\n\tp24 := mi.GetPriceChange()\n\tratioInPercent := ratio * 100\n\tvol := mi.GetVolume()\n\tmc := mi.GetMarketCap()\n\treturn &genModels.Info{\n\t\tPrice: &p,\n\t\tPrice24hChange: &p24,\n\t\tStakingRatio: &ratioInPercent,\n\t\tAnnualYield: annualYield,\n\t\tMarketCap: mc,\n\t\tVolume24h: vol,\n\t\tCirculatingSupply: mi.GetSupply(),\n\t\tBlocksInCycle: blocks,\n\t}\n}", "func (v Account) GetInfo(params AccountGetInfoParams) (*AccountGetInfoResponse, error) {\n\tr, err := v.API.Request(\"account.getInfo\", params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp AccountGetInfoResponse\n\terr = json.Unmarshal(r, &resp)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resp, nil\n}", "func (s *Service) Info(ctx context.Context, req *InfoRequest) (*InfoReply, error) {\n\ti, err := s.getInstanceByToken(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tinfo, err := i.Info(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treply := &InfoReply{\n\t\tInfo: &InstanceInfo{\n\t\t\tID: info.ID.String(),\n\t\t\tDefaultCidConfig: &DefaultCidConfig{\n\t\t\t\tHot: &HotConfig{\n\t\t\t\t\tEnabled: info.DefaultCidConfig.Hot.Enabled,\n\t\t\t\t\tAllowUnfreeze: info.DefaultCidConfig.Hot.AllowUnfreeze,\n\t\t\t\t\tIpfs: &IpfsConfig{\n\t\t\t\t\t\tAddTimeout: int64(info.DefaultCidConfig.Hot.Ipfs.AddTimeout),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tCold: &ColdConfig{\n\t\t\t\t\tEnabled: info.DefaultCidConfig.Cold.Enabled,\n\t\t\t\t\tFilecoin: &FilConfig{\n\t\t\t\t\t\tRepFactor: int64(info.DefaultCidConfig.Cold.Filecoin.RepFactor),\n\t\t\t\t\t\tDealDuration: info.DefaultCidConfig.Cold.Filecoin.DealDuration,\n\t\t\t\t\t\tExcludedMiners: info.DefaultCidConfig.Cold.Filecoin.ExcludedMiners,\n\t\t\t\t\t\tCountryCodes: info.DefaultCidConfig.Cold.Filecoin.CountryCodes,\n\t\t\t\t\t\tRenew: &FilRenew{\n\t\t\t\t\t\t\tEnabled: info.DefaultCidConfig.Cold.Filecoin.Renew.Enabled,\n\t\t\t\t\t\t\tThreshold: int64(info.DefaultCidConfig.Cold.Filecoin.Renew.Threshold),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tWallet: &WalletInfo{\n\t\t\t\tAddress: info.Wallet.Address,\n\t\t\t\tBalance: info.Wallet.Balance,\n\t\t\t},\n\t\t\tPins: make([]string, len(info.Pins)),\n\t\t},\n\t}\n\tfor i, p := range info.Pins {\n\t\treply.Info.Pins[i] = p.String()\n\t}\n\treturn reply, nil\n}", "func (a *Account) GetInfo(fields string) (AccountGetInfoResponse, error) {\n\tparams := map[string]string{\"fields\": fields }\n\tresp, err := a.vk.Request(\"account.getInfo\", params)\n\tif err != nil {\n\t\treturn AccountGetInfoResponse{}, err\n\t}\n\tvar info AccountGetInfoResponse\n\terr = json.Unmarshal(resp, &info)\n\tif err != nil {\n\t\treturn AccountGetInfoResponse{}, err\n\t}\n\treturn info, nil\n}", "func (p *Base) Info() (uuid, id, pass string) {\n\treturn p.UUID, p.ID, p.Password\n}", "func (_ERC20HecoManager *ERC20HecoManagerCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _ERC20HecoManager.contract.Call(opts, &out, \"wallet\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (w WavesClient) GetInfo() (*transport.CoinState, error) {\n\tvar res WavesGetBlockResponse\n\n\terr := w.GET(\"/blocks/last\", nil, &res)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error getting latest waves block\")\n\t}\n\n\treturn &transport.CoinState{\n\t\tData: transport.CoinData{\n\t\t\tChain: \"main\",\n\t\t\tBlockHeight: res.Height,\n\t\t\tCurrentBlock: fmt.Sprintf(\"%d\", res.Height),\n\t\t},\n\t}, nil\n}", "func (dstv Dstv) AccountInfo(accountNumber string,\n\tcountry ...string) (*AccountInfoResponse, error) {\n\n\tcustomerNumber, smartCardNumber := \"\", \"\"\n\taccountNumberType(accountNumber, &customerNumber, &smartCardNumber)\n\n\tif len(country) > 0 {\n\t\tdstv.AddQueryData(paymenex.PCountry, country[0])\n\t} else {\n\t\tdstv.AddQueryData(paymenex.PCountry, \"GH\")\n\t}\n\tdstv.AddQueryData(paymenex.PActId, \"LKDCT\")\n\tdstv.AddQueryData(paymenex.PDstvCustomerNo, customerNumber)\n\tdstv.AddQueryData(paymenex.PDstvSmartCardNo, smartCardNumber)\n\txml, err := dstv.MakeRequest()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// writeFile(\"account-info.xml\", xml) // DEBUG\n\tresponse := new(AccountInfoResponse)\n\tok := dstv.ParseAndVerifyResponse(xml, response)\n\tif !ok {\n\t\treturn response, errors.New(errVerifyMsg)\n\t}\n\treturn response, nil\n}", "func (c *Client) Info() (*boxutil.Info, error) {\n\tvar info boxutil.Info\n\tu, err := url.Parse(c.addr + \"/info\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !u.IsAbs() {\n\t\treturn nil, errors.New(\"box address must be absolute\")\n\t}\n\treq, err := http.NewRequest(\"GET\", u.String(), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treq.Header.Set(\"Accept\", \"application/json; charset=utf-8\")\n\tresp, err := c.HTTPClient.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode < 200 || resp.StatusCode >= 300 {\n\t\treturn nil, errors.New(resp.Status)\n\t}\n\tif err := json.NewDecoder(resp.Body).Decode(&info); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &info, nil\n}", "func (app *BaseApp) Info(req abci.RequestInfo) abci.ResponseInfo {\n\tlastCommitID := app.cms.LastCommitID()\n\n\treturn abci.ResponseInfo{\n\t\tData: app.name,\n\t\tLastBlockHeight: lastCommitID.Version,\n\t\tLastBlockAppHash: lastCommitID.Hash,\n\t}\n}", "func (o BackupOutput) EncryptionInfo() EncryptionInfoResponseOutput {\n\treturn o.ApplyT(func(v *Backup) EncryptionInfoResponseOutput { return v.EncryptionInfo }).(EncryptionInfoResponseOutput)\n}", "func (c *Client) AccountInfo() (AccInfo, error) {\n\tdata, err := c.apiCall(\"account.info\", nil)\n\tif err != nil {\n\t\treturn AccInfo{}, err\n\t}\n\n\tvar info AccInfo\n\terr = json.Unmarshal(data, &info)\n\tif err != nil {\n\t\treturn AccInfo{}, err\n\t}\n\n\treturn info, nil\n}", "func (_FinalizableCrowdsaleImpl *FinalizableCrowdsaleImplCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _FinalizableCrowdsaleImpl.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func (j *JustAddPowerReciever) Info(ctx context.Context) (interface{}, error) {\n\tvar details Info\n\n\taddr, e := net.LookupAddr(j.Address)\n\tif e != nil {\n\t\tdetails.Hostname = j.Address\n\t} else {\n\t\tdetails.Hostname = strings.Trim(addr[0], \".\")\n\t}\n\n\t//Send the request to the Just Add Power API\n\tresult, err := justAddPowerRequest(fmt.Sprintf(\"http://%s/cgi-bin/api/details/device\", j.Address), \"\", \"GET\")\n\tif err != nil {\n\t\treturn details, fmt.Errorf(\"Error occured whilemaking request:%w\", err)\n\t}\n\n\t//jsonResult is the response back from the API, it has all the information\n\tvar jsonResult JustAddPowerDetailsResult\n\tgerr := json.Unmarshal(result, &jsonResult)\n\tif gerr != nil {\n\t\treturn details, fmt.Errorf(\"Error occured whilemaking request:%w\", err)\n\t}\n\n\tdetails.ModelName = jsonResult.Data.Model //Model of the device\n\tdetails.FirmwareVersion = jsonResult.Data.Firmware.Version //Version of firmware on the device\n\tdetails.BuildDate = jsonResult.Data.Firmware.Date //The Date the firmware was released\n\tdetails.PowerStatus = jsonResult.Data.Uptime //Reports on how long the device has been booted\n\n\t// Get the Network info stuff\n\tdetails.IPAddress = jsonResult.Data.Network.Ipaddress\n\tdetails.MACAddress = jsonResult.Data.Network.Mac\n\n\treturn details, nil\n}", "func (m Miner) GetInfo() (MinerInfo, error) {\n\tvar mi MinerInfo\n\tvar reply []string\n\tclient, err := jsonrpc.Dial(\"tcp\", m.Address)\n\tif err != nil {\n\t\treturn mi, err\n\t}\n\tdefer client.Close()\n\targs.psw = m.Password\n\terr = client.Call(methodGetInfo, args, &reply)\n\tif err != nil {\n\t\treturn mi, err\n\t}\n\treturn parseResponse(reply), nil\n}", "func (_Dospayment *DospaymentCaller) PaymentInfo(opts *bind.CallOpts, requestID *big.Int) (common.Address, *big.Int, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t\tret1 = new(*big.Int)\n\t)\n\tout := &[]interface{}{\n\t\tret0,\n\t\tret1,\n\t}\n\terr := _Dospayment.contract.Call(opts, out, \"paymentInfo\", requestID)\n\treturn *ret0, *ret1, err\n}", "func (marketApp *MarketPlaceApp) Info() error {\n\tresponse, err := client.Call(\"one.marketapp.info\", marketApp.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tmarketApp.body = response.Body()\n\treturn nil\n}", "func (e EthereumClient) GetInfo() (*transport.CoinState, error) {\n\tchain, err := e.Client.NetworkID(context.Background())\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error fetching network id for ethereum node\")\n\t}\n\n\tcurrent, err := e.Client.BlockByNumber(context.Background(), nil)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error fetching latest block number for ethereum node\")\n\t}\n\n\thash := current.ReceiptHash().String()\n\treturn &transport.CoinState{\n\t\tData: transport.CoinData{\n\t\t\tChain: chain.String(),\n\t\t\tBlockHeight: int(current.Number().Int64()),\n\t\t\tCurrentBlock: hash,\n\t\t},\n\t}, nil\n}", "func GetAccountInfo(w http.ResponseWriter, r *http.Request) {\n\n\t// Add header so that received knows they're receiving JSON\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// Retrieving name of node from query request\n\tnodeName := r.URL.Query().Get(\"name\")\n\tconfirmation, socket := checkNodeName(nodeName)\n\tif confirmation == false {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Node name requested doesn't exist\"})\n\t\treturn\n\t}\n\n\t// Retrieving height from query request\n\trecvHeight := r.URL.Query().Get(\"height\")\n\theight := checkHeight(recvHeight)\n\tif height == -1 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Unexepcted value found, height needs to be string of int!\"})\n\t\treturn\n\t}\n\n\t// Note Make sure that public key that is being sent is coded properly\n\t// Example A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU+h+blS9pto= should be\n\t// A1X90rT/WK4AOTh/dJsUlOqNDV/nXM6ZU%2Bh%2BblS9pto=\n\t//var pubKey common_signature.PublicKey\n\townerKey := r.URL.Query().Get(\"ownerKey\")\n\tif len(ownerKey) == 0 {\n\n\t\t// Stop code here no need to establish connection and reply\n\t\tlgr.Warning.Println(\n\t\t\t\"Request at /api/staking/accountinfo failed, ownerKey can't be \" +\n\t\t\t\t\"empty!\")\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"ownerKey can't be empty!\"})\n\t\treturn\n\t}\n\n\t// Unmarshall text into public key object\n\t//err := pubKey.UnmarshalText([]byte(ownerKey))\n\t//if err != nil {\n\t//\tlgr.Error.Println(\"Failed to UnmarshalText into Public Key\", err)\n\t//\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t//\t\tError: \"Failed to UnmarshalText into Public Key.\"})\n\t//\treturn\n\t//}\n\n\tvar address staking.Address\n\terr := address.UnmarshalText([]byte(ownerKey))\n\tif err != nil {\n\t\tlgr.Error.Println(\"Failed to UnmarshalText into Address\", err)\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to UnmarshalText into Address.\"})\n\t\treturn\n\t}\n\n\t// Attempt to load connection with staking client\n\tconnection, so := loadStakingClient(socket)\n\n\t// Close connection once code underneath executes\n\tdefer connection.Close()\n\n\t// If null object was retrieved send response\n\tif so == nil {\n\n\t\t// Stop code here faild to establish connection and reply\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to establish connection using socket : \" + socket})\n\t\treturn\n\t}\n\n\t// Create an owner query to be able to retrieve data with regards to account\n\t//query := staking.OwnerQuery{Height: height, Owner: pubKey}\n\tquery := staking.OwnerQuery{Height: height, Owner: address}\n\n\t// Retrieve account information using created query\n\taccount, err := so.Account(context.Background(), &query)\n\tif err != nil {\n\t\tjson.NewEncoder(w).Encode(responses.ErrorResponse{\n\t\t\tError: \"Failed to get Account!\"})\n\t\tlgr.Error.Println(\n\t\t\t\"Request at /api/staking/accountinfo failed to retrieve Account \"+\n\t\t\t\t\"Info : \", err)\n\t\treturn\n\t}\n\n\t// Return account information for created query\n\tlgr.Info.Println(\"Request at /api/staking/accountinfo responding with \" +\n\t\t\"Account!\")\n\tjson.NewEncoder(w).Encode(responses.AccountResponse{AccountInfo: account})\n}", "func GetChainInfo(chain uint64) *BaseInfo {\n\tvar pStat BaseInfo\n\tgetDataFormDB(chain, dbStat{}, []byte{StatBaseInfo}, &pStat)\n\treturn &pStat\n}", "func (base Base) Info() (result map[string]string) {\n\treturn\n}", "func (c *Client) AccountInfo(listenKey string) (*AccountInfo, error) {\n\tvar b strings.Builder\n\tb.WriteString(baseWS)\n\tb.WriteString(listenKey)\n\tconn, err := fastws.Dial(b.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn.ReadTimeout = 0\n\treturn &AccountInfo{wsClient{conn: conn}}, nil\n}", "func (s *PublicTransactionPoolAPI) GetAccountInfo(ctx context.Context, tokenID *common.Address, addr *common.Address) (*wtypes.GetAccountInfoResult, error) {\n\tif tokenID == nil {\n\t\ttokenID = &common.EmptyAddress\n\t}\n\tret, err := s.wallet.GetAccountInfo(tokenID, addr)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}", "func (db *DB) Info() *Info {\n\treturn &Info{\n\t\tuintptr(unsafe.Pointer(&db.data[0])),\n\t\tdb.pageSize,\n\t}\n}", "func (r *Account) Information() (*Entities.Account, error) {\n\tbody, err := r.cl.Request(mkm.Get, \"/account\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\taccount := &Entities.Account{}\n\terr = json.Unmarshal(body, account)\n\treturn account, err\n}", "func (_BREMICO *BREMICOCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _BREMICO.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func (b *Bucket) Info(ctx context.Context) (info Info, err error) {\n\tctx, err = b.Context(ctx)\n\tif err != nil {\n\t\treturn\n\t}\n\trep, err := b.clients.Buckets.Root(ctx, b.Key())\n\tif err != nil {\n\t\treturn\n\t}\n\treturn pbRootToInfo(rep.Root)\n}", "func (g *altsTC) Info() credentials.ProtocolInfo {\n\treturn *g.info\n}", "func (t *TezTracker) GetBakerInfo(accountID string) (bi *models.Baker, err error) {\n\tr := t.repoProvider.GetBaker()\n\tfound, baker, err := r.Find(accountID)\n\tif err != nil {\n\t\treturn bi, err\n\t}\n\tif !found {\n\t\treturn nil, nil\n\t}\n\n\terr = t.calcDepositRewards(&baker.BakerStats, baker.AccountID)\n\tif err != nil {\n\t\treturn bi, err\n\t}\n\n\tblock, err := t.repoProvider.GetBlock().Last()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//Get last snapshot\n\t_, snap, err := t.repoProvider.GetSnapshots().Find(block.MetaCycle - PreservedCycles - 2)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbaker.StakingCapacity = t.calcBakerCapacity(baker, snap.Rolls)\n\n\treturn &baker, nil\n}", "func (s AccountInfo) String() string {\n\treturn awsutil.Prettify(s)\n}", "func BakerInfo(bi *models.Baker) *genModels.BakerInfo {\n\tif bi == nil {\n\t\treturn nil\n\t}\n\n\tmedia := &genModels.BakerInfoMedia{}\n\tif len(bi.Media) != 0 {\n\t\tjson.Unmarshal([]byte(bi.Media), media)\n\t}\n\n\tbakingSince := bi.BakingSince.Unix()\n\n\treturn &genModels.BakerInfo{\n\t\tName: bi.Name,\n\t\tBakingSince: &bakingSince,\n\t\tRolls: &bi.Rolls,\n\t\tFee: &bi.Fee,\n\t\tBlocks: &bi.Blocks,\n\t\tEndorsements: &bi.Endorsements,\n\t\tActiveDelegators: &bi.ActiveDelegations,\n\t\tStakingBalance: &bi.StakingBalance,\n\t\tStakingCapacity: &bi.StakingCapacity,\n\t\tEvaluatedBalance: &bi.Balance,\n\t\tFrozenBalance: &bi.FrozenBalance,\n\t\tBakingDeposits: &bi.BakingDeposits,\n\t\tBakingRewards: &bi.BakingRewards,\n\t\tEndorsementDeposits: &bi.EndorsementDeposits,\n\t\tEndorsementRewards: &bi.EndorsementRewards,\n\t\tTotalPaidFees: bi.TotalPaidFees,\n\t\tMedia: media,\n\t}\n}", "func (_IncreasingPriceCrowdsaleImpl *IncreasingPriceCrowdsaleImplCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _IncreasingPriceCrowdsaleImpl.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func (c *Contract) GetInfo() metadata.InfoMetadata {\n\treturn c.Info\n}", "func NewInfo() *Info {\n\treturn &Info{\n\t\tTypes: map[string]bool{},\n\t}\n}", "func (n NemClient) GetInfo() (*transport.CoinState, error) {\n\tvar info NemGetLastBlockResponse\n\n\tif err := n.GET(\"/chain/last-block\", nil, &info); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &transport.CoinState{\n\t\tData: transport.CoinData{\n\t\t\tChain: \"main\",\n\t\t\tBlockHeight: int(info.Height),\n\t\t\tCurrentBlock: info.PrevBlockHash.Data,\n\t\t},\n\t}, nil\n}", "func (_Authority *AuthorityCaller) GetBuyInfo(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Authority.contract.Call(opts, out, \"getBuyInfo\")\n\treturn *ret0, err\n}", "func (c *Client) ChainInfo(p net.Peer) (*chain.Info, error) {\n\tresp, err := c.client.ChainInfo(context.TODO(), p, &drand.ChainInfoRequest{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn chain.InfoFromProto(resp)\n}", "func GetInfo() Info {\n\treturn Info{\n\t\tVersion: Version,\n\t\tBuildDate: BuildDate,\n\t\tGitCommit: GitCommit,\n\t}\n}", "func NewAccountInfo(name string, bic string, iban string, balance int32, predecessor string) *AccountInfo {\n\taccountInfo := AccountInfo{Name: name, BIC: bic, IBAN: iban, Balance: balance, Predecessor: predecessor}\n\taccountInfo.Transactions = []*Transaction{}\n\n\treturn &accountInfo\n}", "func (s *LocalStore) Info(_ context.Context, _ *storepb.InfoRequest) (*storepb.InfoResponse, error) {\n\treturn s.info, nil\n}", "func (_Crowdsale *CrowdsaleCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _Crowdsale.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func (b *Bootstrapper) Info() ([]byte, error) {\n\tclasses := map[string][]byte{}\n\tfor class, ref := range b.classRefs {\n\t\tclasses[class] = ref[:]\n\t}\n\treturn json.MarshalIndent(map[string]interface{}{\n\t\t\"root_domain\": b.rootDomainRef[:],\n\t\t\"root_member\": b.rootMemberRef[:],\n\t\t\"classes\": classes,\n\t}, \"\", \" \")\n}", "func GetInfo(accountID string, tx *sql.Tx) (info Info, err error) {\n\tmapper := rlt.NewAccountMapper(tx)\n\trow, err := mapper.FindAccountByID(accountID)\n\tif err != nil {\n\t\treturn info, err\n\t}\n\tinfo.ID = row.ID\n\tinfo.Domain = row.Domain.String\n\tinfo.UserName = row.UserName\n\tinfo.DisplayName = row.DisplayName\n\tinfo.Email = row.Email\n\treturn\n}", "func (w *rpcWallet) AddressInfo(ctx context.Context, address string) (*AddressInfo, error) {\n\ta, err := stdaddr.DecodeAddress(address, w.chainParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tres, err := w.client().ValidateAddress(ctx, a)\n\tif err != nil {\n\t\treturn nil, translateRPCCancelErr(err)\n\t}\n\tif !res.IsValid {\n\t\treturn nil, fmt.Errorf(\"address is invalid\")\n\t}\n\tif !res.IsMine {\n\t\treturn nil, fmt.Errorf(\"address does not belong to this wallet\")\n\t}\n\tif res.Branch == nil {\n\t\treturn nil, fmt.Errorf(\"no account branch info for address\")\n\t}\n\treturn &AddressInfo{Account: res.Account, Branch: *res.Branch}, nil\n}", "func (id ID) Info() Info {\n\t// note to avoid circular dependency these are hard coded\n\t// values are checked for non regression in code generation\n\tswitch id {\n\tcase BLS12_377:\n\t\treturn newInfo(&config.BLS12_377)\n\tcase BLS12_381:\n\t\treturn newInfo(&config.BLS12_381)\n\tcase BN254:\n\t\treturn newInfo(&config.BN254)\n\tcase BW6_761:\n\t\treturn newInfo(&config.BW6_761)\n\tcase BW6_633:\n\t\treturn newInfo(&config.BW6_633)\n\tcase BLS24_315:\n\t\treturn newInfo(&config.BLS24_315)\n\tdefault:\n\t\tpanic(\"unimplemented ecc ID\")\n\t}\n}", "func (user User) Info(w http.ResponseWriter, gp *core.Goploy) {\n\ttype RepData struct {\n\t\tUserInfo struct {\n\t\t\tID int64 `json:\"id\"`\n\t\t\tAccount string `json:\"account\"`\n\t\t\tName string `json:\"name\"`\n\t\t\tRole string `json:\"role\"`\n\t\t} `json:\"userInfo\"`\n\t}\n\tuserData, err := core.GetUserInfo(gp.TokenInfo.ID)\n\n\tif err != nil {\n\t\tresponse := core.Response{Code: 1, Message: err.Error()}\n\t\tresponse.JSON(w)\n\t\treturn\n\t}\n\n\tdata := RepData{}\n\tdata.UserInfo.ID = gp.TokenInfo.ID\n\tdata.UserInfo.Name = userData.Name\n\tdata.UserInfo.Account = userData.Account\n\tdata.UserInfo.Role = userData.Role\n\tresponse := core.Response{Data: data}\n\tresponse.JSON(w)\n}", "func (b *Bitmex) UpdateAccountInfo(ctx context.Context, assetType asset.Item) (account.Holdings, error) {\n\tvar info account.Holdings\n\n\tuserMargins, err := b.GetAllUserMargin(ctx)\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\taccountBalances := make(map[string][]account.Balance)\n\t// Need to update to add Margin/Liquidity availability\n\tfor i := range userMargins {\n\t\taccountID := strconv.FormatInt(userMargins[i].Account, 10)\n\n\t\tvar wallet WalletInfo\n\t\twallet, err = b.GetWalletInfo(ctx, userMargins[i].Currency)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\taccountBalances[accountID] = append(\n\t\t\taccountBalances[accountID], account.Balance{\n\t\t\t\tCurrency: currency.NewCode(wallet.Currency),\n\t\t\t\tTotal: wallet.Amount,\n\t\t\t},\n\t\t)\n\t}\n\n\tif info.Accounts, err = account.CollectBalances(accountBalances, assetType); err != nil {\n\t\treturn account.Holdings{}, err\n\t}\n\tinfo.Exchange = b.Name\n\n\tcreds, err := b.GetCredentials(ctx)\n\tif err != nil {\n\t\treturn account.Holdings{}, err\n\t}\n\tif err := account.Process(&info, creds); err != nil {\n\t\treturn account.Holdings{}, err\n\t}\n\n\treturn info, nil\n}", "func (_ERC20HecoManager *ERC20HecoManagerCallerSession) Wallet() (common.Address, error) {\n\treturn _ERC20HecoManager.Contract.Wallet(&_ERC20HecoManager.CallOpts)\n}", "func (app *KVStoreApplication) Info(req abcitypes.RequestInfo) abcitypes.ResponseInfo {\n\treturn abcitypes.ResponseInfo{}\n}", "func GetInfo() *Info {\n\tif info == nil {\n\t\tinfo = &Info{\n\t\t\tsvcName: make(map[string]string),\n\t\t\tobjInfo: make(map[string]objInfo),\n\t\t}\n\t}\n\treturn info\n}", "func (_IncreasingPriceCrowdsale *IncreasingPriceCrowdsaleCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _IncreasingPriceCrowdsale.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func getWallet() walletStruct {\n\n\ts := \"START getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\ts = \"END getWallet() - Gets the wallet\"\n\tlog.Debug(\"WALLET: GUTS \" + s)\n\n\treturn wallet\n}", "func (p *Peer) Info() map[string]interface{} {\n\tp.mtx.RLock()\n\tdefer p.mtx.RUnlock()\n\n\td := map[string]PeerState{}\n\tfor k, v := range p.data {\n\t\td[k] = v\n\t}\n\n\treturn map[string]interface{}{\n\t\t\"self\": p.mlist.LocalNode(),\n\t\t\"members\": p.mlist.Members(),\n\t\t\"n\": p.mlist.NumMembers(),\n\t\t\"state\": d,\n\t}\n}", "func (_IndividuallyCappedCrowdsaleImpl *IndividuallyCappedCrowdsaleImplCaller) Wallet(opts *bind.CallOpts) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _IndividuallyCappedCrowdsaleImpl.contract.Call(opts, out, \"wallet\")\n\treturn *ret0, err\n}", "func (_ERC20HecoManager *ERC20HecoManagerSession) Wallet() (common.Address, error) {\n\treturn _ERC20HecoManager.Contract.Wallet(&_ERC20HecoManager.CallOpts)\n}", "func (_Cakevault *CakevaultSession) UserInfo(arg0 common.Address) (struct {\n\tShares *big.Int\n\tLastDepositedTime *big.Int\n\tCakeAtLastUserAction *big.Int\n\tLastUserActionTime *big.Int\n}, error) {\n\treturn _Cakevault.Contract.UserInfo(&_Cakevault.CallOpts, arg0)\n}", "func (as AccountStorage) GetInfo(ctx sdk.Context, accKey types.AccountKey) (*AccountInfo, sdk.Error) {\n\tstore := ctx.KVStore(as.key)\n\tinfoByte := store.Get(GetAccountInfoKey(accKey))\n\tif infoByte == nil {\n\t\treturn nil, ErrAccountInfoNotFound()\n\t}\n\tinfo := new(AccountInfo)\n\tif err := as.cdc.UnmarshalJSON(infoByte, info); err != nil {\n\t\treturn nil, ErrFailedToUnmarshalAccountInfo(err)\n\t}\n\treturn info, nil\n}", "func getwalletinfo() {\n\tsearchterms := []string{\"approx.speed\", \"Current balance\"}\n\tdwarfpoolurl := \"https://dwarfpool.com/xmr/address?wallet=\"\n\tdwarfpoolurl = dwarfpoolurl + WalletAdress\n\tnum := getconversion()\n\tresponse, err := http.Get(dwarfpoolurl)\n\tif err != nil {\n\t\tfmt.Printf(\"%s\", err)\n\t\tos.Exit(1)\n\t} else {\n\t\tdefer response.Body.Close()\n\t\tcontents, err := ioutil.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"%s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tdata := strings.Split(string(contents), \"\\n\")\n\t\tfor iter, term := range searchterms {\n\t\t\tfor i := 0; i < len(data); i++ {\n\t\t\t\tif strings.Contains(data[i], term) {\n\t\t\t\t\tline := strings.Split(data[i-1], \" \")\n\t\t\t\t\tfor _, val := range line {\n\t\t\t\t\t\tif strings.Contains(val, `badge-money\">`) {\n\t\t\t\t\t\t\tans := strings.TrimPrefix(val, `badge-money\">`)\n\t\t\t\t\t\t\ti, err := strconv.ParseFloat(ans, 64)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tfmt.Println(\"Problem with float64 conversion\")\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif term == \"approx.speed\" {\n\t\t\t\t\t\t\t\tHashRate = ans\n\t\t\t\t\t\t\t} else if term == \"Current balance\" {\n\t\t\t\t\t\t\t\tConversionRate = strconv.FormatFloat(num, 'f', 6, 64)\n\t\t\t\t\t\t\t\tXmrAmount = ans\n\t\t\t\t\t\t\t\tDollarAmount = strconv.FormatFloat((num * i), 'f', 6, 64)\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\tfmt.Println(\"String Array not right at: \", iter)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (d *btrfs) Info() Info {\n\treturn Info{\n\t\tName: \"btrfs\",\n\t\tVersion: btrfsVersion,\n\t\tOptimizedImages: true,\n\t\tOptimizedBackups: true,\n\t\tOptimizedBackupHeader: true,\n\t\tPreservesInodes: !d.state.OS.RunningInUserNS,\n\t\tRemote: d.isRemote(),\n\t\tVolumeTypes: []VolumeType{VolumeTypeBucket, VolumeTypeCustom, VolumeTypeImage, VolumeTypeContainer, VolumeTypeVM},\n\t\tBlockBacking: false,\n\t\tRunningCopyFreeze: false,\n\t\tDirectIO: true,\n\t\tIOUring: true,\n\t\tMountedRoot: true,\n\t\tBuckets: true,\n\t}\n}", "func (_Authority *AuthorityCallerSession) GetBuyInfo() (common.Address, error) {\n\treturn _Authority.Contract.GetBuyInfo(&_Authority.CallOpts)\n}", "func New(options ...Option) (wallet *Wallet) {\n\t// create wallet\n\twallet = &Wallet{\n\t\tassetRegistry: NewAssetRegistry(),\n\t}\n\n\t// configure wallet\n\tfor _, option := range options {\n\t\toption(wallet)\n\t}\n\n\t// initialize wallet with default address manager if we did not import a previous wallet\n\tif wallet.addressManager == nil {\n\t\twallet.addressManager = NewAddressManager(seed.NewSeed(), 0, []bitmask.BitMask{})\n\t}\n\n\t// initialize asset registry if none was provided in the options.\n\tif wallet.assetRegistry == nil {\n\t\twallet.assetRegistry = NewAssetRegistry()\n\t}\n\n\t// initialize wallet with default connector (server) if none was provided\n\tif wallet.connector == nil {\n\t\tpanic(\"you need to provide a connector for your wallet\")\n\t}\n\n\t// initialize output manager\n\twallet.unspentOutputManager = NewUnspentOutputManager(wallet.addressManager, wallet.connector)\n\terr := wallet.unspentOutputManager.Refresh(true)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn\n}", "func (p MigProfileInfo) GetInfo() MigProfileInfo {\n\treturn p\n}", "func (_Smartchef *SmartchefSession) UserInfo(arg0 common.Address) (struct {\n\tAmount *big.Int\n\tRewardDebt *big.Int\n}, error) {\n\treturn _Smartchef.Contract.UserInfo(&_Smartchef.CallOpts, arg0)\n}", "func NewAccountInfoOK() *AccountInfoOK {\n\treturn &AccountInfoOK{}\n}", "func (s *swapKit) swapInfo() *SwapInfo {\n\treturn &SwapInfo{\n\t\tSwapContract: *s.contract,\n\t\tSwapHash: s.hash,\n\t\tSwapType: s.swapType,\n\t\tLastUpdate: s.lastUpdateTime,\n\t\tSwapStateData: loopdb.SwapStateData{\n\t\t\tState: s.state,\n\t\t\tCost: s.cost,\n\t\t},\n\t}\n}", "func (w *Wallet) AddressInfo(a btcutil.Address) (waddrmgr.ManagedAddress, er.R) {\n\tvar managedAddress waddrmgr.ManagedAddress\n\terr := walletdb.View(w.db, func(tx walletdb.ReadTx) er.R {\n\t\taddrmgrNs := tx.ReadBucket(waddrmgrNamespaceKey)\n\t\tvar err er.R\n\t\tmanagedAddress, err = w.Manager.Address(addrmgrNs, a)\n\t\treturn err\n\t})\n\treturn managedAddress, err\n}", "func (_Cakevault *CakevaultCallerSession) UserInfo(arg0 common.Address) (struct {\n\tShares *big.Int\n\tLastDepositedTime *big.Int\n\tCakeAtLastUserAction *big.Int\n\tLastUserActionTime *big.Int\n}, error) {\n\treturn _Cakevault.Contract.UserInfo(&_Cakevault.CallOpts, arg0)\n}", "func (_Authority *AuthoritySession) GetBuyInfo() (common.Address, error) {\n\treturn _Authority.Contract.GetBuyInfo(&_Authority.CallOpts)\n}", "func Info() VersionInfo {\n\treturn VersionInfo{\n\t\tVersion: version,\n\t\tGoVersion: goVersion,\n\t\tCommit: commit,\n\t\tBuildDate: buildDate,\n\t}\n}", "func (c *Client) GetAccountInfo(ctx context.Context, base58Addr string) (AccountInfo, error) {\n\tres, err := c.RpcClient.GetAccountInfoWithConfig(ctx, base58Addr, rpc.GetAccountInfoConfig{\n\t\tEncoding: rpc.GetAccountInfoConfigEncodingBase64,\n\t})\n\terr = checkRpcResult(res.GeneralResponse, err)\n\tif err != nil {\n\t\treturn AccountInfo{}, err\n\t}\n\tif res.Result.Value == (rpc.GetAccountInfoResultValue{}) {\n\t\treturn AccountInfo{}, nil\n\t}\n\n\tdata, ok := res.Result.Value.Data.([]interface{})\n\tif !ok {\n\t\treturn AccountInfo{}, fmt.Errorf(\"failed to cast raw response to []interface{}\")\n\t}\n\tif data[1] != string(rpc.GetAccountInfoConfigEncodingBase64) {\n\t\treturn AccountInfo{}, fmt.Errorf(\"encoding mistmatch\")\n\t}\n\trawData, err := base64.StdEncoding.DecodeString(data[0].(string))\n\tif err != nil {\n\t\treturn AccountInfo{}, fmt.Errorf(\"failed to base64 decode data\")\n\t}\n\treturn AccountInfo{\n\t\tLamports: res.Result.Value.Lamports,\n\t\tOwner: res.Result.Value.Owner,\n\t\tExcutable: res.Result.Value.Excutable,\n\t\tRentEpoch: res.Result.Value.RentEpoch,\n\t\tData: rawData,\n\t}, nil\n}", "func (_Smartchef *SmartchefCallerSession) UserInfo(arg0 common.Address) (struct {\n\tAmount *big.Int\n\tRewardDebt *big.Int\n}, error) {\n\treturn _Smartchef.Contract.UserInfo(&_Smartchef.CallOpts, arg0)\n}", "func (s *Solo) Info() (map[string]string, error) {\n\tinfo := map[string]string{\n\t\t\"type\": \"solo\",\n\t\t\"tx_index\": strconv.Itoa(s.txIndex),\n\t}\n\treturn info, nil\n}", "func Info(r *kite.Request) (interface{}, error) {\n\tproviderName, err := CheckProvider()\n\tif err != nil {\n\t\treturn info{}, err\n\t}\n\n\ti := info{\n\t\tProviderName: providerName.String(),\n\t}\n\n\treturn i, nil\n}", "func (m *Application) GetInfo()(InformationalUrlable) {\n return m.info\n}", "func Info(ctx context.Context, msg string, fields ...zap.Field) {\n\tFromContext(ctx).WithOptions(zap.AddCallerSkip(1)).Info(msg, fields...)\n}", "func (s *Sync) Info() *Info {\n\titems, queued := s.a.Status()\n\n\treturn &Info{\n\t\tID: s.mountID,\n\t\tMount: s.m,\n\t\tSyncCount: s.lidx.Count(-1),\n\t\tAllCount: s.ridx.Count(-1),\n\t\tSyncDiskSize: s.lidx.DiskSize(-1),\n\t\tAllDiskSize: s.ridx.DiskSize(-1),\n\t\tQueued: items,\n\t\tSyncing: items - queued,\n\t}\n}", "func (c *Customer) Info() string {\n\treturn \"TODO\"\n}", "func (k *Kraken) GetAccountInfo() (exchange.AccountInfo, error) {\n\tvar info exchange.AccountInfo\n\tinfo.Exchange = k.GetName()\n\n\tbal, err := k.GetBalance()\n\tif err != nil {\n\t\treturn info, err\n\t}\n\n\tvar balances []exchange.AccountCurrencyInfo\n\tfor key, data := range bal {\n\t\tbalances = append(balances, exchange.AccountCurrencyInfo{\n\t\t\tCurrencyName: currency.NewCode(key),\n\t\t\tTotalValue: data,\n\t\t})\n\t}\n\n\tinfo.Accounts = append(info.Accounts, exchange.Account{\n\t\tCurrencies: balances,\n\t})\n\n\treturn info, nil\n}", "func (_Dospayment *DospaymentCallerSession) PaymentInfo(requestID *big.Int) (common.Address, *big.Int, error) {\n\treturn _Dospayment.Contract.PaymentInfo(&_Dospayment.CallOpts, requestID)\n}", "func GetInfo() (*Info, error) {\n\tvar result Info\n\terr := result.discover()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &result, nil\n}", "func (_FinalizableCrowdsaleImpl *FinalizableCrowdsaleImplCallerSession) Wallet() (common.Address, error) {\n\treturn _FinalizableCrowdsaleImpl.Contract.Wallet(&_FinalizableCrowdsaleImpl.CallOpts)\n}", "func (*WalletInfo) Descriptor() ([]byte, []int) {\n\treturn file_pkt_proto_rawDescGZIP(), []int{3}\n}", "func Info() Information {\n\treturn Information{\n\t\tVersion: version,\n\t\tRevision: revision,\n\t\tBranch: branch,\n\t\tBuildUser: buildUser,\n\t\tBuildDate: buildDate,\n\t\tGoVersion: goVersion,\n\t}\n}", "func (d *common) Info() *api.NetworkACL {\n\t// Copy internal info to prevent modification externally.\n\tinfo := api.NetworkACL{}\n\tinfo.Name = d.info.Name\n\tinfo.Description = d.info.Description\n\tinfo.Ingress = append(make([]api.NetworkACLRule, 0, len(d.info.Ingress)), d.info.Ingress...)\n\tinfo.Egress = append(make([]api.NetworkACLRule, 0, len(d.info.Egress)), d.info.Egress...)\n\tinfo.Config = util.CopyConfig(d.info.Config)\n\tinfo.UsedBy = nil // To indicate its not populated (use Usedby() function to populate).\n\n\treturn &info\n}", "func (a *Address) Info() {\n fmt.Printf(\"Country %s, City %s\\n\", a.country, a.city)\n}", "func (_BREMICO *BREMICOCallerSession) Wallet() (common.Address, error) {\n\treturn _BREMICO.Contract.Wallet(&_BREMICO.CallOpts)\n}", "func (c *Jrpc) ShowPrivacyAccountInfo(in *pty.ReqPrivacyAccount, result *json.RawMessage) error {\n\treply, err := c.cli.ExecWalletFunc(pty.PrivacyX, \"ShowPrivacyAccountInfo\", in)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*result, err = types.PBToJSON(reply)\n\treturn err\n}" ]
[ "0.8092361", "0.8092361", "0.8089147", "0.8089147", "0.79879147", "0.7909782", "0.78342617", "0.658371", "0.63826746", "0.6154448", "0.6121526", "0.5942231", "0.5940345", "0.5929081", "0.5924688", "0.5737779", "0.56235343", "0.55903804", "0.5588205", "0.5579243", "0.55534166", "0.55484146", "0.5477271", "0.54757", "0.54541135", "0.54445463", "0.5433491", "0.539976", "0.53971696", "0.53761506", "0.53649855", "0.5362314", "0.53584576", "0.5349996", "0.53359866", "0.533526", "0.5326337", "0.5319168", "0.53144866", "0.5313449", "0.53098845", "0.53096634", "0.5271099", "0.5262847", "0.52492857", "0.5248296", "0.5237898", "0.52349037", "0.52313983", "0.52264684", "0.5222315", "0.52206916", "0.5212747", "0.5211704", "0.52073836", "0.520312", "0.5196114", "0.5195878", "0.51953334", "0.5191171", "0.5189489", "0.51886755", "0.51873314", "0.5176127", "0.5167931", "0.516353", "0.51521593", "0.5141021", "0.51285934", "0.51278555", "0.51010156", "0.5100516", "0.509544", "0.5083853", "0.50830615", "0.50824755", "0.50681937", "0.5063119", "0.50559205", "0.5054806", "0.50470877", "0.5046908", "0.5045536", "0.50445515", "0.5038117", "0.5021515", "0.50148225", "0.50146264", "0.5010317", "0.5002221", "0.49986738", "0.4997883", "0.49966073", "0.49933693", "0.49929547", "0.49924517", "0.4989881", "0.4986752", "0.49852884", "0.4984746" ]
0.75912964
7
AuthDropTempAuthKeys invokes method auth.dropTempAuthKeys8e48a188 returning error if any. Delete all temporary authorization keys except for the ones specified See for reference. Can be used by bots.
func (c *Client) AuthDropTempAuthKeys(ctx context.Context, exceptauthkeys []int64) (bool, error) { var result BoolBox request := &AuthDropTempAuthKeysRequest{ ExceptAuthKeys: exceptauthkeys, } if err := c.rpc.InvokeRaw(ctx, request, &result); err != nil { return false, err } _, ok := result.Bool.(*BoolTrue) return ok, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *schg) dropTmpDirs() (err error) {\n\tfor _, p := range s.tmp {\n\t\te := os.RemoveAll(p)\n\t\tif err == nil {\n\t\t\terr = e\n\t\t}\n\t}\n\ts.tmp = make([]string, 0)\n\treturn\n}", "func (c *CryptohomeBinary) TPMAttestationDeleteKeys(ctx context.Context, username, prefix string) ([]byte, error) {\n\treturn c.call(ctx, \"--action=tpm_attestation_delete_keys\", \"--user=\"+username, \"--prefix=\"+prefix)\n}", "func (s *Service) cleanAuthTokens(authTokens []*model.AuthToken) {\n\tfor _, authToken := range authTokens {\n\t\tvar (\n\t\t\tbytes []byte\n\t\t\terr error\n\t\t)\n\t\tif bytes, err = base64.StdEncoding.DecodeString(authToken.Token); err != nil {\n\t\t\tlog.Error(\"cleanAuthTokens base64 decode err %v\", err)\n\t\t\tcontinue\n\t\t}\n\t\ttoken := hex.EncodeToString(bytes)\n\t\tlog.Info(\"auth binlog clear cleanAuthTokens,msg is (%+v)\", authToken)\n\t\tt := &model.AccessInfo{\n\t\t\tMid: authToken.Mid,\n\t\t\tAppID: int32(authToken.AppID),\n\t\t\tToken: token,\n\t\t\tExpires: authToken.Expires,\n\t\t}\n\t\ts.cleanToken(t)\n\t}\n}", "func (gc *GlobalOpts) CleanupTmp() {\n\terr := os.RemoveAll(gc.TmpDir)\n\tif err != nil {\n\t\tlog.Printf(\"[ERROR] Failed to remove temporary directory %v\", err)\n\t}\n}", "func (c *ConfigChanEvent) CleanTmpFiles() error {\n\tlog.Debugf(\"ConfigChanEvent::CleanTmpFiles(): cleaning up temporary files\")\n\tfor _, r := range c.Repo {\n\t\tfor _, f := range r.TmpFile {\n\t\t\tlog.Debugf(\"ConfigChanEvent::CleanTmpFiles(): removing file %#v\", f)\n\t\t\tos.Remove(f)\n\t\t}\n\t}\n\n\tif c.TmpFile != nil {\n\t\tos.Remove(c.TmpFile.Name())\n\t}\n\treturn nil\n}", "func (ms *MemStore) CleanupSessionKeys(t uint64) error {\n\tvar oldKeys []string\n\tfor hash, sk := range ms.sessionKeys {\n\t\tif sk.cleanupTime < t {\n\t\t\toldKeys = append(oldKeys, hash)\n\t\t}\n\t}\n\tfor _, hash := range oldKeys {\n\t\tdelete(ms.sessionKeys, hash)\n\t}\n\treturn nil\n}", "func RemoveTemporaryFiles(files ...*string) {\n\tfor _, _file := range files {\n\t\tif err := os.Remove(*_file); err != nil {\n\t\t\tlog.Printf(\"An error arised while removing %v: %v\", _file, err)\n\t\t}\n\t}\n}", "func (b *BoltAuthRepository) CleanUp() {\n\tb.db.Update(func(tx *bolt.Tx) error {\n\t\tb := tx.Bucket([]byte(b.bucket))\n\t\tc := b.Cursor()\n\t\tvar toDelete [][]byte\n\t\tfor k, v := c.First(); k != nil; k, v = c.Next() {\n\t\t\tvar tkn models.Token\n\t\t\tif json.Unmarshal(v, &tkn) != nil {\n\t\t\t\t// Prevents password from being cleaned with tokens.\n\t\t\t\t//\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfmt.Printf(\"key=%s, value=%s\\n\", k, tkn.Expires)\n\t\t\tif tkn.Expires.Before(time.Now()) {\n\t\t\t\ttoDelete = append(toDelete, k)\n\t\t\t}\n\t\t}\n\t\tfor _, key := range toDelete {\n\t\t\tb.Delete(key)\n\t\t}\n\t\treturn nil\n\t})\n}", "func (s *Server) cleanTmpFiles(dir string) {\n\tnow := time.Now()\n\tpackdir := filepath.Join(dir, \".git\", \"objects\", \"pack\")\n\terr := filepath.Walk(packdir, func(path string, info os.FileInfo, err error) error {\n\t\tif path != packdir && info.IsDir() {\n\t\t\treturn filepath.SkipDir\n\t\t}\n\t\tfile := filepath.Base(path)\n\t\tif strings.HasPrefix(file, \"tmp_pack_\") {\n\t\t\tif now.Sub(info.ModTime()) > longGitCommandTimeout {\n\t\t\t\terr := os.Remove(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tlog15.Error(\"error removing tmp_pack_* files\", \"error\", err)\n\t}\n}", "func RemoveTempFolders() {\n\tclose(folders)\n\tfor f := range folders {\n\t\tos.RemoveAll(f)\n\t}\n}", "func (m *ServiceMgr) deleteTempStore(appName string) (info *runtimeInfo) {\n\tlogPrefix := \"ServiceMgr::deleteTempStore\"\n\n\tinfo = &runtimeInfo{}\n\tlogging.Infof(\"%s Function: %s deleting drafts from temporary store\", logPrefix, appName)\n\n\tcheckIfDeployed := false\n\tfor _, app := range util.ListChildren(metakvTempAppsPath) {\n\t\tif app == appName {\n\t\t\tcheckIfDeployed = true\n\t\t}\n\t}\n\n\tif !checkIfDeployed {\n\t\tinfo.Code = m.statusCodes.errAppNotDeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s not deployed\", appName)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tappState := m.superSup.GetAppState(appName)\n\tif appState != common.AppStateUndeployed {\n\t\tinfo.Code = m.statusCodes.errAppNotUndeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s skipping delete request from temp store, as it hasn't been undeployed\", appName)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\n\tif err := util.DeleteAppContent(metakvTempAppsPath, metakvTempChecksumPath, appName); err != nil {\n\t\tinfo.Code = m.statusCodes.errDelAppTs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Function: %s failed to delete, err: %v\", appName, err)\n\t\tlogging.Errorf(\"%s %s\", logPrefix, info.Info)\n\t\treturn\n\t}\n\tinfo.Code = m.statusCodes.ok.Code\n\tinfo.Info = fmt.Sprintf(\"Function: %s deleting in the background\", appName)\n\tlogging.Infof(\"%s %s\", logPrefix, info.Info)\n\treturn\n}", "func (s *Satellite) CleanupTempFiles() {\n\tif !util.IsInDirectory(env.GetPublicPath(), s.ExtractedFilePath) {\n\t\tutil.Delete(s.ExtractedFilePath)\n\t}\n}", "func (m *ServiceMgr) deleteTempStore(appName string) (info *runtimeInfo) {\n\tinfo = &runtimeInfo{}\n\tlogging.Infof(\"Deleting drafts from temporary store: %v\", appName)\n\n\tcheckIfDeployed := false\n\tfor _, app := range util.ListChildren(metakvTempAppsPath) {\n\t\tif app == appName {\n\t\t\tcheckIfDeployed = true\n\t\t}\n\t}\n\n\tif !checkIfDeployed {\n\t\tinfo.Code = m.statusCodes.errAppNotDeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"App: %v not deployed\", appName)\n\t\treturn\n\t}\n\n\tappState := m.superSup.GetAppState(appName)\n\tif appState != common.AppStateUndeployed {\n\t\tinfo.Code = m.statusCodes.errAppNotUndeployed.Code\n\t\tinfo.Info = fmt.Sprintf(\"Skipping delete request from temp store for app: %v as it hasn't been undeployed\", appName)\n\t\treturn\n\t}\n\n\tif err := util.DeleteAppContent(metakvTempAppsPath, metakvTempChecksumPath, appName); err != nil {\n\t\tinfo.Code = m.statusCodes.errDelAppTs.Code\n\t\tinfo.Info = fmt.Sprintf(\"Failed to delete App definition : %v, err: %v\", appName, err)\n\t\treturn\n\t}\n\tinfo.Code = m.statusCodes.ok.Code\n\tinfo.Info = fmt.Sprintf(\"Deleting app: %v in the background\", appName)\n\treturn\n}", "func cleanup() {\n\tlog.Verbose(\"Cleaning up sensitive and temp files\")\n\tif _, err := os.Stat(\"ca.crt\"); err == nil {\n\t\tdeleteFile(\"ca.crt\")\n\t}\n\n\tif _, err := os.Stat(\"ca.key\"); err == nil {\n\t\tdeleteFile(\"ca.key\")\n\t}\n\n\tif _, err := os.Stat(\"client.crt\"); err == nil {\n\t\tdeleteFile(\"client.crt\")\n\t}\n\n\tif _, err := os.Stat(\"bearer.token\"); err == nil {\n\t\tdeleteFile(\"bearer.token\")\n\t}\n\n\tfor _, app := range s.Apps {\n\t\tif _, err := os.Stat(app.SecretsFile + \".dec\"); err == nil {\n\t\t\tdeleteFile(app.SecretsFile + \".dec\")\n\t\t}\n\t\tfor _, secret := range app.SecretsFiles {\n\t\t\tif _, err := os.Stat(secret + \".dec\"); err == nil {\n\t\t\t\tdeleteFile(secret + \".dec\")\n\t\t\t}\n\t\t}\n\t}\n\n}", "func cleanExit(code int) {\n\tif *verbose {\n\t\tfmt.Println(\"Cleaning up private keys\")\n\t}\n\tfor k := range keys {\n\t\tsys.ClearBuffer(keys[k].Key)\n\t}\n\tif type2_secret != nil {\n\t\tsys.ClearBuffer(type2_secret)\n\t}\n\tos.Exit(code)\n}", "func createTmpFiles() (*tmpCredsFiles, error) {\n\ttmpFiles := &tmpCredsFiles{}\n\tvar err error\n\ttmpFiles.clientCertTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpFiles.clientKeyTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpFiles.clientTrustTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpFiles.serverCertTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpFiles.serverKeyTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpFiles.serverTrustTmp, err = os.CreateTemp(os.TempDir(), \"pre-\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn tmpFiles, nil\n}", "func (dsl *DeleteDSL) BfdAuthKeys(bfdKey string) linux.DeleteDSL {\n\tdsl.vppDelete.BfdAuthKeys(bfdKey)\n\treturn dsl\n}", "func deleteKeys(ctx context.Context, backend driver.StorageDriver, prefix string, forced bool) error {\n\tlist, err := backend.List(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorContentNotFound.Format(prefix)\n\t}\n\tif len(list) > 0 && !forced {\n\t\treturn ErrorNeedForcedDelete.Format(prefix)\n\t}\n\terr = backend.Delete(ctx, prefix)\n\tif err != nil {\n\t\treturn ErrorInternalUnknown.Format(err)\n\t}\n\treturn nil\n}", "func NewTemporaryTaoDelegatedKeys(keyTypes KeyType, t Tao) (*Keys, error) {\n\tk, err := NewTemporaryKeys(keyTypes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif t != nil && k.SigningKey != nil {\n\n\t\tself, err := t.GetTaoName()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ts := &auth.Speaksfor{\n\t\t\tDelegate: k.SigningKey.ToPrincipal(),\n\t\t\tDelegator: self,\n\t\t}\n\t\tif k.Delegation, err = t.Attest(&self, nil, nil, s); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn k, nil\n}", "func NewTempCredentials(k keyring.Keyring, config *Config) (*credentials.Credentials, error) {\n\tprovider, err := NewTempCredentialsProvider(k, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn credentials.NewCredentials(provider), nil\n}", "func NewTempCredentials(k keyring.Keyring, config Config) (*credentials.Credentials, error) {\n\tprovider, err := NewTempCredentialsProvider(k, config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn credentials.NewCredentials(provider), nil\n}", "func removeTempdir(d string) {\n\tif CLEARTEMP == false {\n\t\treturn\n\t}\n\tos.RemoveAll(d)\n}", "func CleanUnbindOauth(db *mgo.Database) error {\n\tc:=db.C(OAUTH_2)\n\t_,err:=c.RemoveAll(bson.M{\"uid\":bson.Undefined})\n\treturn err\n}", "func CleanupObjectsFromDynamicServiceAccountTokenAccess(ctx context.Context, targetClient kubernetes.Interface) error {\n\treturn flow.Parallel(func(ctx context.Context) error {\n\t\treturn targetClient.Client().DeleteAllOf(ctx, &corev1.ServiceAccount{}, client.InNamespace(namespaceE2ETestServiceAccountTokenAccess), client.MatchingLabels(labelsE2ETestDynamicServiceAccountTokenAccess))\n\t}, func(ctx context.Context) error {\n\t\treturn targetClient.Client().DeleteAllOf(ctx, &rbacv1.ClusterRoleBinding{}, client.MatchingLabels(labelsE2ETestDynamicServiceAccountTokenAccess))\n\t})(ctx)\n}", "func (validatorObj *ValidatorStruct) RemoveFromTemp() {\n\tfor i, timpValidator := range TempValidatorlst {\n\t\tif validatorObj.ValidatorIP == timpValidator.ValidatorObjec.ValidatorIP {\n\t\t\tTempValidatorlst = append(TempValidatorlst[:i], TempValidatorlst[i+1:]...) // delete validator from temp list\n\t\t}\n\t}\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) CleanUpAccessGroups(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"cleanUpAccessGroups\")\n}", "func CleanupTempFile(t *testing.T, fileName string) {\n\terr := os.Remove(fileName)\n\tif err != nil {\n\t\tt.Logf(\"Could not remove temp file: %v. Err: %v\\n\", fileName, err)\n\t}\n}", "func deleteAuthKey(ctx context.Context, secretName string) error {\n\t// m is a JSON Patch data structure, see https://jsonpatch.com/ or RFC 6902.\n\tm := []struct {\n\t\tOp string `json:\"op\"`\n\t\tPath string `json:\"path\"`\n\t}{\n\t\t{\n\t\t\tOp: \"remove\",\n\t\t\tPath: \"/data/authkey\",\n\t\t},\n\t}\n\tvar b bytes.Buffer\n\tif err := json.NewEncoder(&b).Encode(m); err != nil {\n\t\treturn err\n\t}\n\treq, err := http.NewRequest(\"PATCH\", fmt.Sprintf(\"/api/v1/namespaces/%s/secrets/%s?fieldManager=tailscale-container\", kubeNamespace, secretName), &b)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/json-patch+json\")\n\tif resp, err := doKubeRequest(ctx, req); err != nil {\n\t\tif resp != nil && resp.StatusCode == http.StatusUnprocessableEntity {\n\t\t\t// This is kubernetes-ese for \"the field you asked to\n\t\t\t// delete already doesn't exist\", aka no-op.\n\t\t\treturn nil\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}", "func removeTempRepos() {\n\tos.RemoveAll(\"/tmp/github.com\")\n}", "func filterK8sConfigAuthInfos(authInfos map[string]*clientcmdapi.AuthInfo) error {\n\tfor key, authInfo := range authInfos {\n\t\t// If clientCertficateData or the bearer token is not present then proceed to check\n\t\t// the client certicate path\n\t\tif len(authInfo.ClientCertificateData) == 0 && len(authInfo.Token) == 0 && authInfo.AuthProvider == nil {\n\t\t\t// If the path for clientCertficate and the bearer token, both are inaccessible or invalid then delete that authinfo\n\t\t\t_, errCC := os.Stat(authInfo.ClientCertificate)\n\t\t\t_, errToken := os.Stat(authInfo.TokenFile)\n\t\t\tif errCC != nil && errToken != nil {\n\t\t\t\tdelete(authInfos, key)\n\t\t\t}\n\t\t}\n\t}\n\n\t// In the end if the authInfos map is empty then the kubeconfig is\n\t// invalid and cannot be used for communicating with kubernetes\n\tif len(authInfos) == 0 {\n\t\treturn ErrAuthInfosInvalidMsg\n\t}\n\n\treturn nil\n}", "func Cleanup() {\n\ttransactionID := clientid + strconv.Itoa(totaltransactions)\n\tfor _, lockInfo := range clientReadLockSet.SetToArray() {\n\t\tserver := strings.Split(lockInfo, \".\")[0]\n\t\taccountName := strings.Split(lockInfo, \".\")[1]\n\t\tRPCToServer(\"UpdateAccount\", server, accountName, \"\", transactionID)\n\t}\n\tclienttempstore = make(map[string]map[string]string)\n\tclientReadLockSet = NewSet()\n\tclientCommandsqueue.Clear()\n\tRPCToCoor(\"REMOVE\", transactionID, []string{})\n}", "func (k *Keys) Clean() {\n\tif k != nil {\n\t\tif k.Admin != nil {\n\t\t\tk.Admin.Clean()\n\t\t\tk.Admin = nil\n\t\t}\n\t\tif k.Server != nil {\n\t\t\tk.Server.Clean()\n\t\t\tk.Server = nil\n\t\t}\n\t\tk.Nonce = nil\n\t}\n}", "func DeleteTempMeasurements(c *gin.Context) {\n\tdeviceName := c.Param(\"device_name\")\n\tstartTime, endTime := helpers.ParamReader(c.Param(\"start_time\"),\n\t\tc.Param(\"end_time\"))\n\terr := database.DeleteTempMeasurements(c, deviceName,\n\t\tstartTime, endTime)\n\tif err != nil {\n\t\tc.Status(http.StatusNotFound)\n\t} else {\n\t\tc.Status(http.StatusOK)\n\t}\n}", "func (te *TestEnvironment) Clean() {\n\tuserIDs, err := te.UserDAO.ListAllUserIDs()\n\tif err != nil {\n\t\tte.Logger.Error(fmt.Sprintf(\"ListAllUserIDs returns err: %v\", err))\n\t}\n\n\tfor _, uid := range userIDs {\n\t\tuser, err := te.UserDAO.GetUserByID(uid)\n\t\tif err != nil {\n\t\t\tte.Logger.Error(fmt.Sprintf(\"GetUserByID(%s) returns err: %v\", uid, err))\n\t\t}\n\n\t\tgDrive, err := te.GDriveFactory.New(user)\n\t\tif err != nil {\n\t\t\tte.Logger.Error(fmt.Sprintf(\"Error initializing gdrive client for user %q\", user.Id))\n\t\t\treturn\n\t\t}\n\t\tfileIDs, err := gDrive.ListFileIDs(googledrive.AllMP4s)\n\t\tif err != nil {\n\t\t\tte.Logger.Error(fmt.Sprintf(\"Error listing all file IDs for user %q\", user.Id))\n\t\t}\n\t\tfor _, fid := range fileIDs {\n\t\t\tfor _, prefix := range googledrive.FilePrefixes {\n\t\t\t\tif err := gDrive.MarkFileByID(fid, prefix, true); err != nil {\n\t\t\t\t\tte.Logger.Error(fmt.Sprintf(\"gDrive.MarkFileByID(%s, %s, true) for user %q returns err: %v\", fid, prefix, user.Id, err))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err := data.DeleteAllUserData(uid, false, te.sqlService, te.SimpleStorage, te.Logger); err != nil {\n\t\t\tte.Logger.Error(fmt.Sprintf(\"DeleteAllUserDataInDB(%s, %t, _) returns err: %v\", uid, false, err))\n\t\t}\n\t}\n}", "func (manager *usersManager) UnlockTemporary(\n\tctx context.Context,\n\topts *ablbind.TransactOpts,\n\tidentityPreimage common.Hash,\n\tnewOwner common.Address,\n) error {\n\treceipt, err := manager.UsersContract.UnlockTemporary(ctx, opts, identityPreimage, newOwner)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to transact\")\n\t}\n\n\tevt, err := manager.UsersContract.ParseTemporaryUnlockedFromReceipt(receipt)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to parse a event from the receipt\")\n\t}\n\n\tmanager.log.Info(\"Temporary user unlocked.\", logger.Attrs{\n\t\t\"user-id\": fmt.Sprintf(\"%x\", evt[0].UserId),\n\t\t\"new-owner\": evt[0].NewOwner.Hex(),\n\t})\n\treturn nil\n}", "func deleteTempDir() error {\n\tif !FileExists(tempDir) {\n\t\treturn nil\n\t}\n\n\tDebugFunc(tempDir)\n\n\terr := filepath.Walk(tempDir, func(path string, info os.FileInfo, err error) error {\n\t\tif !info.IsDir() && !IsFileReadOnly(path) {\n\t\t\terr := SetFileReadOnly(path, false)\n\t\t\tif Error(err) {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\tif Error(err) {\n\t\treturn err\n\t}\n\n\terr = os.RemoveAll(tempDir)\n\tif Error(err) {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func DeleteGenericPassword(service string, account string, accessGroup string) error {\n\titem := keychain.NewItem()\n\titem.SetSecClass(keychain.SecClassGenericPassword)\n\titem.SetService(service)\n\titem.SetAccount(account)\n\titem.SetAccessGroup(accessGroup)\n\treturn keychain.DeleteItem(item)\n}", "func (be *s3) removeKeys(t backend.Type) error {\n\tdone := make(chan struct{})\n\tdefer close(done)\n\tfor key := range be.List(backend.Data, done) {\n\t\terr := be.Remove(backend.Data, key)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func unusedKeys(obj interface{}) error {\n\tval := reflect.ValueOf(obj)\n\tif val.Kind() == reflect.Ptr {\n\t\tval = reflect.Indirect(val)\n\t}\n\treturn unusedKeysImpl([]string{}, val)\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) CleanUpContentTypes(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"cleanUpContentTypes\")\n}", "func (m *UserMutation) ResetAuthHistories() {\n\tm.authHistories = nil\n\tm.clearedauthHistories = false\n\tm.removedauthHistories = nil\n}", "func (p *NoteStoreClient) UntagAll(ctx context.Context, authenticationToken string, guid GUID) (err error) {\n var _args81 NoteStoreUntagAllArgs\n _args81.AuthenticationToken = authenticationToken\n _args81.GUID = guid\n var _result82 NoteStoreUntagAllResult\n if err = p.Client_().Call(ctx, \"untagAll\", &_args81, &_result82); err != nil {\n return\n }\n switch {\n case _result82.UserException!= nil:\n return _result82.UserException\n case _result82.SystemException!= nil:\n return _result82.SystemException\n case _result82.NotFoundException!= nil:\n return _result82.NotFoundException\n }\n\n return nil\n}", "func (s *Storage) DropTables() (err error) {\n\t_, err = s.db.Exec(`SET FOREIGN_KEY_CHECKS = 0`)\n\tif err != nil {\n\t\treturn\n\t}\n\t_, err = s.db.Exec(`drop table if exists character_data`)\n\tif err != nil {\n\t\treturn\n\t}\n\ttables := []string{\n\t\t\"account\",\n\t\t\"activities\",\n\t\t\"base\",\n\t\t\"bazaar\",\n\t\t\"character_data\",\n\t\t\"faction\",\n\t\t\"forum\",\n\t\t\"goal\",\n\t\t\"item\",\n\t\t\"lootdrop\",\n\t\t\"lootdropentry\",\n\t\t\"loottable\",\n\t\t\"loottablentry\",\n\t\t\"spells_new\",\n\t\t\"npc\",\n\t\t\"npcloot\",\n\t\t\"post\",\n\t\t\"tasks\",\n\t\t\"topic\",\n\t\t\"user\",\n\t\t\"zone\",\n\t}\n\tfor _, table := range tables {\n\t\t_, err = s.db.Exec(fmt.Sprintf(`DROP TABLE IF EXISTS %s`, table))\n\t\tif err != nil {\n\t\t\terrors.Wrap(err, fmt.Sprintf(\"Failed to delete %s\", table))\n\t\t\treturn\n\t\t}\n\t}\n\t_, err = s.db.Exec(`SET FOREIGN_KEY_CHECKS = 1`)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn\n}", "func (p *predictionDataset) CleanupTempFiles() {\n\tp.params.DatasetConstructor.CleanupTempFiles()\n}", "func (b *BootstrapClient) unmountGeneric() error {\n\treturn b.usingVaultRootToken(func() error {\n\t\tfor _, entry := range b.config.genericData {\n\t\t\tif err := b.unmount(entry.Path); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func clearPassword() {\n if runtime.GOOS == \"darwin\" {\n err := keychain.DeleteGenericPasswordItem(KC_SERVICE, KC_ACCOUNT)\n if err != keychain.ErrorItemNotFound {\n check(err)\n }\n }\n\n return\n}", "func (d *swiftDriver) CleanupAccount(account keppel.Account) error {\n\tc, _, err := d.getBackendConnection(account)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn c.Delete(nil)\n}", "func cleanKeychain(label string) error {\n\tquery := keychain.NewItem()\n\tquery.SetSecClass(keychain.SecClassGenericPassword)\n\tquery.SetLabel(label)\n\tquery.SetMatchLimit(keychain.MatchLimitOne)\n\tquery.SetReturnData(true)\n\n\treturn keychain.DeleteItem(query)\n}", "func (m *UserMutation) RemoveAuthIDs(ids ...int) {\n\tif m.removedauths == nil {\n\t\tm.removedauths = make(map[int]struct{})\n\t}\n\tfor i := range ids {\n\t\tm.removedauths[ids[i]] = struct{}{}\n\t}\n}", "func (a *api) cleanUpTestData() {\n\tfmt.Println(\"Nothing to see here - move along\")\n\n\t/* Set up authorization with the token obtained earlier in the test */\n\ta.c.SetJWTSigner(&goaclient.APIKeySigner{\n\t\tSignQuery: false,\n\t\tKeyName: \"Authorization\",\n\t\tKeyValue: savedToken,\n\t\tFormat: \"Bearer %s\",\n\t})\n\n\t/* Delete the workitem */\n\tInfo.Println(\"The ID of the workitem to be deleted is:\", idString)\n\tresp, err := a.c.DeleteWorkitem(context.Background(), \"/api/workitems/\"+idString)\n\ta.resp = resp\n\ta.err = err\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func (al *AccessLayer) DeleteBackupTables() error {\n\tquery := fmt.Sprintf(\"DROP TABLES %s\", strings.Join([]string{\n\t\tfmt.Sprintf(\"%s_bkup\", routesTable),\n\t\tfmt.Sprintf(\"%s_bkup\", stopsTable),\n\t\tfmt.Sprintf(\"%s_bkup\", stopTimesTable),\n\t\tfmt.Sprintf(\"%s_bkup\", tripsTable),\n\t\tfmt.Sprintf(\"%s_bkup\", calendarTable)}, \", \"))\n\tif _, err := al.AL.Exec(query); err != nil {\n\t\treturn fmt.Errorf(\"Unable to delete temp tables: %s\", err)\n\t}\n\n\treturn nil\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) CleanUpAll(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"cleanUpAll\")\n}", "func NewTemporaryKeys(keyTypes KeyType) (*Keys, error) {\n\tk := &Keys{\n\t\tkeyTypes: keyTypes,\n\t}\n\tif k.keyTypes == 0 || (k.keyTypes & ^Signing & ^Crypting & ^Deriving != 0) {\n\t\treturn nil, errors.New(\"bad key type\")\n\t}\n\n\tvar err error\n\tif k.keyTypes&Signing == Signing {\n\t\tk.SigningKey = GenerateAnonymousSigner()\n\t\tif k.SigningKey == nil {\n\t\t\treturn nil, errors.New(\"Can't generate signer\")\n\t\t}\n\t\tk.VerifyingKey = k.SigningKey.GetVerifierFromSigner()\n\t\tif k.VerifyingKey == nil {\n\t\t\treturn nil, errors.New(\"Can't get verifier from signer\")\n\t\t}\n\t}\n\n\tif k.keyTypes&Crypting == Crypting {\n\t\tk.CryptingKey = GenerateAnonymousCrypter()\n\t\tif k.CryptingKey == nil {\n\t\t\treturn nil, errors.New(\"Can't generate crypter\")\n\t\t}\n\t}\n\n\tif k.keyTypes&Deriving == Deriving {\n\t\tk.DerivingKey = GenerateAnonymousDeriver()\n\t\tif k.DerivingKey == nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn k, nil\n}", "func ClearSecretsOnDeprovision(mctx MetaContext, username NormalizedUsername) error {\n\t// 1. Delete all the user's secret keys!!!\n\t// 2. Delete the user's ephemeralKeys\n\t// 3. Delete the user from the config file.\n\t// 4. Db nuke.\n\n\tepick := FirstErrorPicker{}\n\n\tvar logger func(string, ...interface{})\n\tif mctx.UIs().LogUI == nil {\n\t\tlogger = mctx.Info\n\t} else {\n\t\tlogger = mctx.UIs().LogUI.Info\n\t}\n\n\tif clearSecretErr := ClearStoredSecret(mctx, username); clearSecretErr != nil {\n\t\tmctx.Warning(\"ClearStoredSecret error: %s\", clearSecretErr)\n\t}\n\n\t// XXX: Delete the user's secret keyring. It's very important that we never\n\t// do this to the wrong user. Please do not copy this code :)\n\tlogger(\"Deleting %s's secret keys file...\", username.String())\n\tfilename := mctx.G().SKBFilenameForUser(username)\n\tepick.Push(ShredFile(filename))\n\n\tlogger(\"Deleting %s's ephemeralKeys...\", username.String())\n\t// NOTE: We only store userEK/teamEK boxes locally and these are removed in\n\t// the LocalDb.Nuke() below so we just delete any deviceEKs here.\n\tdeviceEKStorage := mctx.G().GetDeviceEKStorage()\n\tif deviceEKStorage != nil {\n\t\tepick.Push(deviceEKStorage.ForceDeleteAll(mctx, username))\n\t}\n\n\tlogger(\"Deleting %s from config.json...\", username.String())\n\tepick.Push(mctx.SwitchUserDeprovisionNukeConfig(username))\n\n\tlogger(\"Clearing the local cache db...\")\n\t_, err := mctx.G().LocalDb.Nuke()\n\tepick.Push(err)\n\n\tlogger(\"Clearing the local cache chat db...\")\n\t_, err = mctx.G().LocalChatDb.Nuke()\n\tepick.Push(err)\n\n\tlogger(\"Deprovision finished.\")\n\treturn epick.Error()\n}", "func (t *tInfo) cleanupPolicies() error {\n\tif t.apiClient != nil {\n\t\t// delete all alerts\n\t\talerts, err := t.apiClient.MonitoringV1().Alert().List(context.Background(), &api.ListWatchOptions{ObjectMeta: api.ObjectMeta{Tenant: \"default\"}})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, a := range alerts {\n\t\t\tt.apiClient.MonitoringV1().Alert().Delete(context.Background(), &a.ObjectMeta)\n\t\t}\n\n\t\t// delete all alert destinations\n\t\talertDestinations, err := t.apiClient.MonitoringV1().AlertDestination().List(context.Background(), &api.ListWatchOptions{ObjectMeta: api.ObjectMeta{Tenant: \"default\"}})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, ad := range alertDestinations {\n\t\t\tt.apiClient.MonitoringV1().AlertDestination().Delete(context.Background(), &ad.ObjectMeta)\n\t\t}\n\n\t\t// delete all alert policies\n\t\talertPolicies, err := t.apiClient.MonitoringV1().AlertPolicy().List(context.Background(), &api.ListWatchOptions{ObjectMeta: api.ObjectMeta{Tenant: \"default\"}})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, ap := range alertPolicies {\n\t\t\tt.apiClient.MonitoringV1().AlertPolicy().Delete(context.Background(), &ap.ObjectMeta)\n\t\t}\n\t}\n\n\treturn nil\n}", "func CleanupObjectsFromStaticServiceAccountTokenAccess(ctx context.Context, shootClient kubernetes.Interface) error {\n\treturn flow.Parallel(func(ctx context.Context) error {\n\t\treturn shootClient.Client().DeleteAllOf(ctx, &corev1.ServiceAccount{}, client.InNamespace(namespaceE2ETestServiceAccountTokenAccess), client.MatchingLabels(labelsE2ETestStaticServiceAccountToken))\n\t}, func(ctx context.Context) error {\n\t\treturn shootClient.Client().DeleteAllOf(ctx, &corev1.Secret{}, client.InNamespace(namespaceE2ETestServiceAccountTokenAccess), client.MatchingLabels(labelsE2ETestStaticServiceAccountToken))\n\t}, func(ctx context.Context) error {\n\t\treturn shootClient.Client().DeleteAllOf(ctx, &rbacv1.ClusterRoleBinding{}, client.MatchingLabels(labelsE2ETestStaticServiceAccountToken))\n\t})(ctx)\n}", "func filterK8sConfigAuthInfos(authInfos map[string]*clientcmdapi.AuthInfo) error {\n\tfor key, authInfo := range authInfos {\n\t\t// If clientCertficateData is not present then proceed to check\n\t\t// the client certicate path\n\t\tif len(authInfo.ClientCertificateData) == 0 {\n\t\t\tif _, err := os.Stat(authInfo.ClientCertificate); err != nil {\n\t\t\t\t// If the path is inaccessible or invalid then delete that authinfo\n\t\t\t\tdelete(authInfos, key)\n\t\t\t}\n\t\t}\n\t}\n\n\t// In the end if the authInfos map is empty then the kubeconfig is\n\t// invalid and cannot be used for communicating with kubernetes\n\tif len(authInfos) == 0 {\n\t\treturn ErrAuthInfosInvalidMsg\n\t}\n\n\treturn nil\n}", "func (b *BruteBlocker) CleanUp() {\n\tvar response = make(chan struct{})\n\tfor id, timestamp := range b.lastFailedAttempt {\n\t\tif time.Since(timestamp) > b.dropAfter {\n\t\t\t// NOTE that delete must happen as request, just like all accesses\n\t\t\t// to the maps.\n\t\t\t// HINT: We synchronize calls using response to not surprise the\n\t\t\t// with not being done with cleanup after CleanUp() returns\n\t\t\tb.requests <- func() {\n\t\t\t\tdelete(b.lastFailedAttempt, id)\n\t\t\t\tdelete(b.countFailedAttempts, id)\n\t\t\t\tresponse <- struct{}{}\n\t\t\t}\n\t\t\t<-response\n\t\t}\n\t}\n}", "func (s *CacheLastPasswordSent) cleanup() {\n\ttickEvery := time.NewTicker(1 * time.Minute)\n\tdefer tickEvery.Stop()\n\n\tclearOutAfter := time.Duration(10 * time.Minute)\n\nLoop:\n\tfor {\n\t\tselect {\n\t\tcase <-s.stop:\n\t\t\tbreak Loop\n\t\tcase <-tickEvery.C:\n\t\t}\n\n\t\ts.mu.Lock()\n\t\tnow := time.Now().UTC()\n\t\tfor key, t := range s.data {\n\t\t\tif now.Sub(t) >= clearOutAfter {\n\t\t\t\tdelete(s.data, key)\n\t\t\t}\n\t\t}\n\t\ts.mu.Unlock()\n\t}\n}", "func (t *DIC3) PurgeUnusedTriplets(req ListRequest, reply *int) error {\n\tfmt.Println(\"Purging Unused triplets \")\n\tvar req2 ListRequest\n\tif req.SourceId == -1 {\n\t\treq2.SourceId = chordid\n\t} else {\n\t\treq2.SourceId = req.SourceId\n\t}\n\tinterval := req.Interval * 1000000000\n\tfor k, v := range dict3 {\n\t\taccess := v[\"permission\"].(string)\n\t\tif strings.EqualFold(\"RW\", access) {\n\t\t\taccess_time, err := time.Parse(time.RFC3339, v[\"accessed\"].(string))\n\t\t\tcheckError(err)\n\t\t\tduration := time.Since(access_time)\n\t\t\tvar durationAsInt64 = int64(duration)\n\t\t\tif durationAsInt64 > interval {\n\t\t\t\t//delete triplet\n\t\t\t\tfmt.Println(\"Deleting \", k)\n\t\t\t\tdelete(dict3, k)\n\t\t\t}\n\t\t}\n\t}\n\n\tif successor.Chordid == req.SourceId || successor.Chordid == chordid {\n\t\tfmt.Println(req.SourceId, \" \", successor.Chordid)\n\t\treturn nil\n\t} else {\n\t\tclient, err := jsonrpc.Dial(protocol, successor.Address)\n\t\tif err != nil {\n\t\t\tlog.Fatal(\"dialing:\", err)\n\t\t}\n\t\tvar reply2 int\n\t\tRpcCall := client.Go(\"DIC3.PurgeUnusedTriplets\", &req2, &reply2, nil)\n\t\treplyCall := <-RpcCall.Done\n\t\tif replyCall != nil {\n\t\t}\n\t\tclient.Close()\n\t\treturn nil\n\t}\n\n\treturn nil\n}", "func RpcDeleteAllAccounts(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule, payload string) (string, error) {\n\tif err := storage.DeleteAll(db, \"collection = 'user'\"); err != nil {\n\t return \"\", err\n }\n\tlogger.Info(\"Deleted all accounts\")\n\treturn \"\", nil\n}", "func (c *ChallengeProvider) CleanUp(ctx context.Context, _ acme.Challenge) error {\n\tfor _, s := range c.servers {\n\t\ts.PersonalKeyAuth = \"\"\n\t}\n\treturn nil\n}", "func (e *PermissionDeniedError) Temporary() bool { return false }", "func TestCompactionRemoveTemp(t *testing.T) {\n\tctx := context.Background()\n\n\ttempDir := t.TempDir()\n\n\tf := NewFactory()\n\tcfg := f.CreateDefaultConfig().(*Config)\n\tcfg.Directory = tempDir\n\n\textension, err := f.CreateExtension(context.Background(), extensiontest.NewNopCreateSettings(), cfg)\n\trequire.NoError(t, err)\n\n\tse, ok := extension.(storage.Extension)\n\trequire.True(t, ok)\n\n\tclient, err := se.GetClient(\n\t\tctx,\n\t\tcomponent.KindReceiver,\n\t\tnewTestEntity(\"my_component\"),\n\t\t\"\",\n\t)\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, client.Close(ctx))\n\t})\n\n\t// check if only db exists in tempDir\n\tfiles, err := os.ReadDir(tempDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(files))\n\tfileName := files[0].Name()\n\n\t// perform compaction in the same directory\n\tc, ok := client.(*fileStorageClient)\n\trequire.True(t, ok)\n\terr = c.Compact(tempDir, cfg.Timeout, 1)\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, client.Close(ctx))\n\t})\n\n\t// check if only db exists in tempDir\n\tfiles, err = os.ReadDir(tempDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, len(files))\n\trequire.Equal(t, fileName, files[0].Name())\n\n\t// perform compaction in different directory\n\temptyTempDir := t.TempDir()\n\n\tc, ok = client.(*fileStorageClient)\n\trequire.True(t, ok)\n\terr = c.Compact(emptyTempDir, cfg.Timeout, 1)\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, client.Close(ctx))\n\t})\n\n\t// check if emptyTempDir is empty after compaction\n\tfiles, err = os.ReadDir(emptyTempDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, len(files))\n}", "func TmpFiles(t *testing.T, names ...*string) func() {\n\tdir, err := ioutil.TempDir(\"\", \"go-golden\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tfor _, name := range names {\n\t\t*name = filepath.Join(dir, *name)\n\t}\n\treturn func() {\n\t\tos.RemoveAll(dir)\n\t}\n}", "func removeSelectedAccountFromOSSettings(ctx context.Context, tconn *chrome.TestConn) error {\n\ttesting.ContextLog(ctx, \"Removing account\")\n\n\tui := uiauto.New(tconn).WithTimeout(DefaultUITimeout)\n\tremoveAccountButton := RemoveActionButton()\n\tif err := uiauto.Combine(\"Click Remove account\",\n\t\tui.WaitUntilExists(removeAccountButton),\n\t\tui.LeftClick(removeAccountButton),\n\t)(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to to click Remove account\")\n\t}\n\n\treturn nil\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) CleanUpContentObjects(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"cleanUpContentObjects\")\n}", "func TestRemovedCredentialKey(t *testing.T) {\n\tvar _, f = GenUser() // generate user\n\n\t// remove credential_key\n\tremoveUserCredKey(s.db, f.Get(\"UUID\"))\n\n\tr := PostRequest(\"\", f, s.CredentialHandler)\n\tvar newCreds Credentials\n\t_ = json.Unmarshal(r.Body.Bytes(), &newCreds)\n\tif len(newCreds.Key) == 0 || len(newCreds.Value) != 0 {\n\t\tt.Errorf(\"Error fetching new Credentials for user %v. Expected new key\", newCreds)\n\t}\n}", "func (db JiraDb) cleanTables() {\n\tfmt.Println(\"cleaning tables..\")\n\n\t_, err := db.db.Exec(\"DROP TABLE tasks\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\t_, err = db.db.Exec(\"DROP TABLE users\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func DropAllTables() {\n\tdot, err := dotsql.LoadFromFile(\"../../dbschema.sql\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttables := []string{\n\t\t\"user-auth\",\n \"follow\",\n\t}\n\tfor _, table := range tables {\n\t\t_, err = dot.Exec(DB, \"drop-\" + table)\n\t}\n}", "func (o *Auth) doAfterDeleteHooks(exec boil.Executor) (err error) {\n\tfor _, hook := range authAfterDeleteHooks {\n\t\tif err := hook(exec, o); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func UnlockTemp(duration int) {\n\tUnlock()\n\t// TO DO: WAIT for <duration>\n\tLock()\n}", "func (a *LocalKeyAgent) DeleteKeys() error {\n\t// Remove keys from the filesystem.\n\terr := a.keyStore.DeleteKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\t// Remove all keys from the Teleport and system agents.\n\terr = a.UnloadKeys()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\n\treturn nil\n}", "func (uu *UserUpdate) RemoveAuthHistories(a ...*Auth) *UserUpdate {\n\tids := make([]int, len(a))\n\tfor i := range a {\n\t\tids[i] = a[i].ID\n\t}\n\treturn uu.RemoveAuthHistoryIDs(ids...)\n}", "func prepareTempDir(rootDir string) (string, error) {\n\tvar tmpDir string\n\tif tmpDir = os.Getenv(\"DOCKER_TMPDIR\"); tmpDir == \"\" {\n\t\ttmpDir = filepath.Join(rootDir, \"tmp\")\n\t\tnewName := tmpDir + \"-old\"\n\t\tif err := os.Rename(tmpDir, newName); err == nil {\n\t\t\tgo func() {\n\t\t\t\tif err := os.RemoveAll(newName); err != nil {\n\t\t\t\t\tlog.G(context.TODO()).Warnf(\"failed to delete old tmp directory: %s\", newName)\n\t\t\t\t}\n\t\t\t}()\n\t\t} else if !os.IsNotExist(err) {\n\t\t\tlog.G(context.TODO()).Warnf(\"failed to rename %s for background deletion: %s. Deleting synchronously\", tmpDir, err)\n\t\t\tif err := os.RemoveAll(tmpDir); err != nil {\n\t\t\t\tlog.G(context.TODO()).Warnf(\"failed to delete old tmp directory: %s\", tmpDir)\n\t\t\t}\n\t\t}\n\t}\n\treturn tmpDir, idtools.MkdirAllAndChown(tmpDir, 0o700, idtools.CurrentIdentity())\n}", "func DbDropNewTickets(dbTx database.Tx, height uint32) error {\n\tmeta := dbTx.Metadata()\n\tbucket := meta.Bucket(dbnamespace.TicketsInBlockBucketName)\n\tk := make([]byte, 4)\n\tdbnamespace.ByteOrder.PutUint32(k, height)\n\n\treturn bucket.Delete(k)\n}", "func (h *cryptoSetup) rejected0RTT() {\n\th.logger.Debugf(\"0-RTT was rejected. Dropping 0-RTT keys.\")\n\n\th.mutex.Lock()\n\thad0RTTKeys := h.zeroRTTSealer != nil\n\th.zeroRTTSealer = nil\n\th.mutex.Unlock()\n\n\tif had0RTTKeys {\n\t\th.events = append(h.events, Event{Kind: EventDiscard0RTTKeys})\n\t}\n}", "func TestRemovedCredentials(t *testing.T) {\n\tvar _, f = GenUser() // generate user\n\n\t// remove Credentials and credential_key\n\tremoveUserCreds(s.db, f.Get(\"UUID\"))\n\n\tr := PostRequest(\"\", f, s.CredentialHandler)\n\tvar newCreds Credentials\n\t_ = json.Unmarshal(r.Body.Bytes(), &newCreds)\n\n\t// expects a new credential key to be returned only\n\tif len(newCreds.Key) == 0 || len(newCreds.Value) == 0 {\n\t\tt.Errorf(\"Error fetching new Credentials for user %v. Expected new Credentials and key\", newCreds)\n\t}\n}", "func ClearTestTables() (err error) {\n\terr = dropTable(\"users\")\n\treturn\n}", "func truncateAuthAndPrevEvents(auth, prev []string) (\n\ttruncAuth, truncPrev []string,\n) {\n\ttruncAuth, truncPrev = auth, prev\n\tif len(truncAuth) > 10 {\n\t\ttruncAuth = truncAuth[:10]\n\t}\n\tif len(truncPrev) > 20 {\n\t\ttruncPrev = truncPrev[:20]\n\t}\n\treturn\n}", "func truncateAuthAndPrevEvents(auth, prev []string) (\n\ttruncAuth, truncPrev []string,\n) {\n\ttruncAuth, truncPrev = auth, prev\n\tif len(truncAuth) > 10 {\n\t\ttruncAuth = truncAuth[:10]\n\t}\n\tif len(truncPrev) > 20 {\n\t\ttruncPrev = truncPrev[:20]\n\t}\n\treturn\n}", "func (c *Conn) Tempfail() {\n\tswitch c.curcmd {\n\tcase HELO, EHLO:\n\t\tc.reply(ReplyServiceNotAvailable)\n\tcase AUTH:\n\t\tc.authDone(false)\n\t\tc.reply(ReplyAuthTmpFail)\n\tcase MAILFROM, RCPTTO, DATA:\n\t\tc.reply(ReplyMailboxNotAvailable)\n\t}\n\tc.replied = true\n}", "func (u *CryptohomeClient) CleanupSession(ctx context.Context, authSessionID string) error {\n\t// Kill the AuthSession.\n\tif _, err := u.binary.invalidateAuthSession(ctx, authSessionID); err != nil {\n\t\treturn errors.Wrap(err, \"failed to invaldiate AuthSession\")\n\t}\n\t// Clean up obsolete state, in case there's any.\n\tif err := u.UnmountAll(ctx); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmount vaults for cleanup\")\n\t}\n\treturn nil\n}", "func deleteTempFile(filename string) {\n\t_ = os.Remove(filename)\n}", "func (_BaseAccessWallet *BaseAccessWalletTransactor) CleanUpLibraries(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _BaseAccessWallet.contract.Transact(opts, \"cleanUpLibraries\")\n}", "func DeleteAllApplicationKeys(db gorp.SqlExecutor, applicationID int64) error {\n\tquery := `DELETE FROM application_key WHERE application_id = $1`\n\tif _, err := db.Exec(query, applicationID); err != nil {\n\t\treturn sdk.WrapError(err, \"cannot delete application key\")\n\t}\n\treturn nil\n}", "func userInstalledPlugins(restPluginsMap restPlugins) restPlugins {\n\tlog.Debug(\"removing plugins that are not 'user-installed'\")\n\tvar tempMap restPlugins\n\tfor _, plugin := range restPluginsMap.Plugins {\n\t\tif bool(plugin.UserInstalled) {\n\t\t\ttempMap.Plugins = append(tempMap.Plugins, plugin)\n\t\t} else {\n\t\t\tswitch plugin.Name {\n\t\t\tcase \"Atlassian Universal Plugin Manager Plugin\":\n\t\t\t\ttempMap.Plugins = append(tempMap.Plugins, plugin)\n\t\t\tcase \"Atlassian Troubleshooting and Support Tools\":\n\t\t\t\ttempMap.Plugins = append(tempMap.Plugins, plugin)\n\t\t\tdefault:\n\t\t\t\tlog.Debug(\"dropping: \", plugin.Name)\n\t\t\t}\n\t\t}\n\t}\n\treturn tempMap\n}", "func (s PgTokenStore) Cleanup() *model.AppErr {\n\tif _, err := s.db.Exec(\"DELETE FROM public.token\"); err != nil {\n\t\treturn model.NewAppErr(\"PgTokenStore.Cleanup\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgCleanup, http.StatusInternalServerError, nil)\n\t}\n\treturn nil\n}", "func (d *MockDataResyncDSL) BfdAuthKeys(val *bfd.SingleHopBFD_Key) vppclient.DataResyncDSL {\n\top := dsl.TxnOp{Key: bfd.AuthKeysKey(string(val.Id)), Value: val}\n\td.Ops = append(d.Ops, op)\n\treturn d\n}", "func (o AuthTokenSlice) DeleteAllGP() {\n\tif err := o.DeleteAllG(); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (a *SubAccountApiService) DeleteSubAccountKeys(ctx context.Context, userId int32, key string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/sub_accounts/{user_id}/keys/{key}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"user_id\"+\"}\", url.QueryEscape(parameterToString(userId, \"\")), -1)\n\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"key\"+\"}\", url.QueryEscape(parameterToString(key, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\tif ctx.Value(ContextGateAPIV4) == nil {\n\t\t// for compatibility, set configuration key and secret to context if ContextGateAPIV4 value is not present\n\t\tctx = context.WithValue(ctx, ContextGateAPIV4, GateAPIV4{\n\t\t\tKey: a.client.cfg.Key,\n\t\t\tSecret: a.client.cfg.Secret,\n\t\t})\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status + \", \" + string(localVarBody),\n\t\t}\n\t\tvar gateErr GateAPIError\n\t\tif e := a.client.decode(&gateErr, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\")); e == nil && gateErr.Label != \"\" {\n\t\t\tgateErr.APIError = newErr\n\t\t\treturn localVarHTTPResponse, gateErr\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (s *ShardDescriptor) ClearTemporary() {\n\ts.ShardVersionPath = \"\"\n\ts.Version = nil\n\n\ts.DocIDCounterPath = \"\"\n\ts.DocIDCounter = nil\n\n\ts.PropLengthTrackerPath = \"\"\n\ts.PropLengthTracker = nil\n}", "func deleteAllKeys() error {\n\tetcd, err := newEtcdClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer etcd.Cli.Close()\n\n\tetcd.Kv.Delete(etcd.Ctx, \"\", clientv3.WithPrefix())\n\treturn nil\n}", "func (tk *RedisAuthService) DeleteTokens(authD *AccessDetails) error {\n\t//get the refresh uuid\n\trefreshUuid := fmt.Sprintf(\"%s++%s\", authD.TokenUuid, authD.UserId)\n\t//delete access token\n\tdeletedAt, err := tk.client.Del(authD.TokenUuid).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\t//delete refresh token\n\tdeletedRt, err := tk.client.Del(refreshUuid).Result()\n\tif err != nil {\n\t\treturn err\n\t}\n\t//When the record is deleted, the return value is 1\n\tif deletedAt != 1 || deletedRt != 1 {\n\t\treturn errors.New(\"something went wrong\")\n\t}\n\treturn nil\n}", "func TgDestroyAll(t *testing.T, options *terraform.Options, workingDir string) string {\n\tout, err := TgDestroyAllE(t, options, workingDir)\n\trequire.NoError(t, err)\n\treturn out\n}", "func (tracker *UsageTracker) CleanUp(cutoff time.Time) {\n\ttoDelete := make([]string, 0)\n\tfor key, usageRecord := range tracker.usage {\n\t\tif !usageRecord.usingTooMany {\n\t\t\tusageRecord.using = filterOutOld(usageRecord.using, cutoff)\n\t\t}\n\t\tif !usageRecord.usedByTooMany {\n\t\t\tusageRecord.usedBy = filterOutOld(usageRecord.usedBy, cutoff)\n\t\t}\n\t\tif !usageRecord.usingTooMany && !usageRecord.usedByTooMany && len(usageRecord.using) == 0 && len(usageRecord.usedBy) == 0 {\n\t\t\ttoDelete = append(toDelete, key)\n\t\t}\n\t}\n\tfor _, key := range toDelete {\n\t\tdelete(tracker.usage, key)\n\t}\n}", "func (c *CvpClient) CancelTempInventory() error {\n\tCancelInventoryURL := \"/inventory/add/cancelInventory.do\"\n\t_, err := c.Get(CancelInventoryURL)\n\treturn err\n}", "func CleanDirs() {\n\tcontents, err := ioutil.ReadDir(\"/var/tmp\")\n\tif err != nil {\n\t\tExitErr(fmt.Errorf(\"failed to access /var/tmp: %v\", err))\n\t}\n\tfor _, file := range contents {\n\t\tif !strings.Contains(file.Name(), \"invertpdf--\") {\n\t\t\tcontinue\n\t\t}\n\t\t_ = os.RemoveAll(fmt.Sprintf(\"/var/tmp/%s\", file.Name()))\n\t}\n}", "func (c *Client) DeleteAccountAccountTemplates(ids []int64) error {\n\treturn c.Delete(AccountAccountTemplateModel, ids)\n}", "func (_AccessIndexor *AccessIndexorTransactor) CleanUpAccessGroups(opts *bind.TransactOpts) (*types.Transaction, error) {\n\treturn _AccessIndexor.contract.Transact(opts, \"cleanUpAccessGroups\")\n}" ]
[ "0.5710542", "0.55091995", "0.54993355", "0.54334545", "0.5356257", "0.52591604", "0.52422273", "0.5241899", "0.52395606", "0.51616263", "0.4973173", "0.4940289", "0.48634106", "0.4859361", "0.48349518", "0.4789098", "0.47831112", "0.4775431", "0.47202703", "0.46839797", "0.4669629", "0.46578717", "0.4606641", "0.45872983", "0.45600587", "0.4560043", "0.45547274", "0.45454782", "0.45386526", "0.45355338", "0.45232773", "0.45040748", "0.44942552", "0.4483504", "0.44773474", "0.44545144", "0.44237036", "0.44110322", "0.43968448", "0.43571642", "0.43460813", "0.43454817", "0.43446583", "0.433522", "0.43350527", "0.43330473", "0.43310398", "0.43225795", "0.4321904", "0.43200764", "0.43161088", "0.43144682", "0.43081212", "0.43025312", "0.43000245", "0.42885372", "0.42882288", "0.42819527", "0.4280618", "0.4273715", "0.42694864", "0.42659253", "0.42657623", "0.42499506", "0.42452723", "0.42255214", "0.42123222", "0.4211695", "0.42061114", "0.4205198", "0.42013377", "0.42010552", "0.42005834", "0.42003345", "0.41979128", "0.41968527", "0.41966617", "0.41935286", "0.41932228", "0.41922516", "0.41922516", "0.41901132", "0.41875252", "0.4186577", "0.417993", "0.41789672", "0.41750377", "0.41733208", "0.41654047", "0.41623202", "0.41585568", "0.4151435", "0.41217598", "0.41199464", "0.4118159", "0.4116813", "0.4115927", "0.41118193", "0.4108024", "0.41043088" ]
0.7777315
0
Push creates a new scope level
func (s *scope) Push() { level := &scopeLevel{map[string]Variable{}, map[Variable]Value{}} s.levels = append(s.levels, level) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (w *Walker) pushScope(name string) (popFunc func()) {\n\tw.scope = append(w.scope, name)\n\treturn func() {\n\t\tif len(w.scope) == 0 {\n\t\t\tlog.Fatalf(\"attempt to leave scope %q with empty scope list\", name)\n\t\t}\n\t\tif w.scope[len(w.scope)-1] != name {\n\t\t\tlog.Fatalf(\"attempt to leave scope %q, but scope is currently %#v\", name, w.scope)\n\t\t}\n\t\tw.scope = w.scope[:len(w.scope)-1]\n\t}\n}", "func (st *scopeStack) push(name ID) {\n\tids := idScope{\n\t\tID: name,\n\t\tscope: scope{},\n\t}\n\tst.stack = append(st.stack, ids)\n}", "func push_level(p int32){\nstack= append(stack,cur_state)\ncur_state.name_field= p\ncur_state.repl_field= name_dir[p].equiv\ncur_state.byte_field= text_info[cur_state.repl_field].token\ncur_state.section_field= 0\n}", "func LevelPush( level Level) {\n logLevelStack = append(logLevelStack, level)\n logLevel = level\n}", "func (p *Proc) Push() {\n\tp.stk.save()\n}", "func (s *state) push(name string, value reflect.Value) {\n\ts.vars = append(s.vars, variable{name, value})\n}", "func (s *stack) push(n *Node) {\n\ts.ns = append(s.ns, n)\n}", "func (s *exprStack) push(expr Expression) {\n\ttrace_util_0.Count(_util_00000, 169)\n\ts.stack = append(s.stack, expr)\n}", "func newScope(parent *scope) scope {\n\treturn scope{objects: map[string]objectAndSource{}, parent: parent}\n}", "func execmScopeInsert(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Scope).Insert(args[1].(types.Object))\n\tp.Ret(2, ret)\n}", "func (i *incStack) Push(new string) {\n\tif path.IsAbs(new) {\n\t\ti.stack = append(i.stack, path.Dir(new))\n\t\treturn\n\t}\n\tlast := \"\"\n\tif len(i.stack) > 0 {\n\t\tlast = i.stack[len(i.stack)-1]\n\t}\n\ti.stack = append(i.stack, path.Dir(filepath.Join(last, new)))\n}", "func (tb *TreeBuilder) Push(node bufr.Node) {\n if debug.DEBUG {\n fmt.Println(\">>>>>>>>>>>>>> START PUSH NODE >>>>>>>>>>>>>>\")\n defer fmt.Println(\">>>>>>>>>>>>>> DONE PUSH NODE >>>>>>>>>>>>>>\")\n }\n if debug.DEBUG {\n fmt.Println(len(tb.stack), node)\n }\n tb.stack = append(tb.stack, tb.node)\n tb.node = node\n if debug.DEBUG {\n fmt.Println(len(tb.stack))\n }\n}", "func (r *renderer) push(context reflect.Value) {\n\tr.stack = append(r.stack, context)\n}", "func (s *Stack) Push(n *Tree) {\n\tif s.count >= len(s.nodes) {\n\t\tnodes := make([]*Tree, len(s.nodes)*2)\n\t\tcopy(nodes, s.nodes)\n\t\ts.nodes = nodes\n\t}\n\ts.nodes[s.count] = n\n\ts.count++\n}", "func (w *walk) push(s string) {\n\t*w = append(*w, s)\n}", "func execNewScope(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewScope(args[0].(*types.Scope), token.Pos(args[1].(int)), token.Pos(args[2].(int)), args[3].(string))\n\tp.Ret(4, ret)\n}", "func push(k *gostwriter.K) {\n\terr := k.Push()\n\tguard(err)\n}", "func (s *stack) push(el int) {\n\ts.items = append(s.items, el)\n}", "func (c *Context) Push(op operation.Operation) {\n\tc.operations = append(c.operations, op)\n}", "func (p *parser) pushV() {\n\tif cap(p.vstack) == len(p.vstack) {\n\t\t// create new empty slot in the stack\n\t\tp.vstack = append(p.vstack, nil)\n\t} else {\n\t\t// slice to 1 more\n\t\tp.vstack = p.vstack[:len(p.vstack)+1]\n\t}\n\n\t// get the last args set\n\tm := p.vstack[len(p.vstack)-1]\n\tif m != nil && len(m) == 0 {\n\t\t// empty map, all good\n\t\treturn\n\t}\n\n\tm = make(map[string]interface{})\n\tp.vstack[len(p.vstack)-1] = m\n}", "func (p *parser) pushV() {\n\tif cap(p.vstack) == len(p.vstack) {\n\t\t// create new empty slot in the stack\n\t\tp.vstack = append(p.vstack, nil)\n\t} else {\n\t\t// slice to 1 more\n\t\tp.vstack = p.vstack[:len(p.vstack)+1]\n\t}\n\n\t// get the last args set\n\tm := p.vstack[len(p.vstack)-1]\n\tif m != nil && len(m) == 0 {\n\t\t// empty map, all good\n\t\treturn\n\t}\n\n\tm = make(map[string]interface{})\n\tp.vstack[len(p.vstack)-1] = m\n}", "func (p *parser) pushV() {\n\tif cap(p.vstack) == len(p.vstack) {\n\t\t// create new empty slot in the stack\n\t\tp.vstack = append(p.vstack, nil)\n\t} else {\n\t\t// slice to 1 more\n\t\tp.vstack = p.vstack[:len(p.vstack)+1]\n\t}\n\n\t// get the last args set\n\tm := p.vstack[len(p.vstack)-1]\n\tif m != nil && len(m) == 0 {\n\t\t// empty map, all good\n\t\treturn\n\t}\n\n\tm = make(map[string]interface{})\n\tp.vstack[len(p.vstack)-1] = m\n}", "func (s *UndoStack) Push(elem UndoFn) {\n\ts.states = append(s.states, elem)\n}", "func (stack *Stack) Push(v int) {\n\tnewTop := &node{v, stack.top}\n\tstack.top = newTop\n\tstack.length++\n}", "func (s *stack) Push(elem []byte) error {\n\ts.stk = append(s.stk, elem)\n\treturn nil\n}", "func (p *parser) pushV() {\n\tif cap(p.vstack) == len(p.vstack) {\n\t\t// create new empty slot in the stack\n\t\tp.vstack = append(p.vstack, nil)\n\t} else {\n\t\t// slice to 1 more\n\t\tp.vstack = p.vstack[:len(p.vstack)+1]\n\t}\n\n\t// get the last args set\n\tm := p.vstack[len(p.vstack)-1]\n\tif m != nil && len(m) == 0 {\n\t\t// empty map, all good\n\t\treturn\n\t}\n\n\tm = make(map[string]any)\n\tp.vstack[len(p.vstack)-1] = m\n}", "func (p *parser) pushV() {\n\tif cap(p.vstack) == len(p.vstack) {\n\t\t// create new empty slot in the stack\n\t\tp.vstack = append(p.vstack, nil)\n\t} else {\n\t\t// slice to 1 more\n\t\tp.vstack = p.vstack[:len(p.vstack)+1]\n\t}\n\n\t// get the last args set\n\tm := p.vstack[len(p.vstack)-1]\n\tif m != nil && len(m) == 0 {\n\t\t// empty map, all good\n\t\treturn\n\t}\n\n\tm = make(map[string]any)\n\tp.vstack[len(p.vstack)-1] = m\n}", "func (st *stack) Push(d interface{}) {\n\tnewNode := &node{d, st.top}\n\tst.top = newNode\n\tst.length++\n}", "func (a *LocalActivations) PushNewWithCurrent() {\n\ta.PushNewWithParent(a.Current())\n}", "func (s *MyStack) Push(x int) {\n\ts.Q = append(s.Q, x)\n}", "func (s *stack) push(el string) {\n\ts.items = append(s.items, el)\n}", "func (this *Stack) Push(value string, time_stamp time.Time) {\n\tn := &node{value, this.top, time_stamp}\n\tthis.top = n\n\tthis.length++\n}", "func (s *Stack) push(val value) error {\n\t//\n\tif s.isFull() {\n\t\tfmt.Println(\"stack is full\")\n\t\treturn errors.New(\"cannot push into a full stack\")\n\t} else {\n\t\ts.values = append(s.values, val)\n\t\ts.top++\n\t\treturn nil\n\t}\n}", "func (p *reParser) push(re *reSyntax) *reSyntax {\n\tp.stack = append(p.stack, re)\n\treturn re\n}", "func (s *Stack) Push(data interface{}) {\r\n\ts.stk = append(s.stk, data)\r\n}", "func Test03Push(t *testing.T) {\n\tgomega.RegisterTestingT(t)\n\n\tprefixStack := getPrefixStack()\n\n\tgomega.Expect(len(prefixStack.Entries)).To(gomega.BeEquivalentTo(1))\n\tprefixStack.Push()\n\tgomega.Expect(len(prefixStack.Entries)).To(gomega.BeEquivalentTo(2))\n}", "func (cs *copyStack) push(t *Type) {\n\t*cs = append(*cs, t)\n}", "func (lc *LoggingContext) Push(name string) (error, bool) {\n\tif lc.curr == \"\" {\n\t\treturn errors.New(fmt.Sprintf(\"Cannot push context to \\\"%s\\\"; no loggers have been added\", name)), false\n\t}\n\tlc.guard.Lock()\n\tdefer lc.guard.Unlock()\n\tlogger := lc.logmap[name]\n\tif logger == nil {\n\t\treturn errors.New(fmt.Sprintf(\"Logger \\\"%s\\\" not found. Still using \\\"%s\\\"\", name, lc.curr)), true\n\t}\n\tlc.logstack.PushBack(lc.curr)\n\tlc.curr = name\n\tl.UseLogger(*logger)\n\treturn nil, true\n}", "func (stack *Stack) Push(stuff interface{}) {\n\t*stack = append(*stack, stuff)\n}", "func (st *Stack) Push(s string) {\n\tst.lines = append(st.lines, s)\n}", "func (this *Stack) Push(value interface{}) {\n\tn := &node{value, this.top}\n\tthis.top = n\n\tthis.length++\n}", "func (t *Tower) push(n int) {\n\tif len(*t) > 0 && (*t)[len(*t)-1] >= n {\n\t\tfmt.Fprintf(os.Stderr, \"%s: invalid state: pushing %d onto %v\\n\",\n\t\t\tpath.Base(os.Args[0]), n, *t)\n\t\tos.Exit(1)\n\t}\n\t*t = append(*t, n)\n}", "func (n *NamespacedMerkleTree) Push(namespacedData namespace.PrefixedData) error {\n\tnID, err := n.validateAndExtractNamespace(namespacedData)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update relevant \"caches\":\n\tn.leaves = append(n.leaves, namespacedData)\n\tn.updateNamespaceRanges()\n\tn.updateMinMaxID(nID)\n\tn.rawRoot = nil\n\treturn nil\n}", "func (s *SimpleStack) Push(val interface{}) (err error) {\n\tif s.isFull() {\n\t\terr = errors.New(\"stack is full\")\n\t\treturn\n\t}\n\ts.top++\n\ts.data[s.top] = val\n\treturn\n}", "func (c *Compiler) enterScope() {\n\tscope := Scope{\n\t\tinstructions: operation.Instruction{},\n\t\temitted: Emitted{},\n\t\tprevEmitted: Emitted{},\n\t}\n\tc.scopes = append(c.scopes, scope)\n\tc.currentScope++\n\tc.symbols = symbols.NewEnclosed(c.symbols)\n}", "func (stack *Stack) Push(s string) {\n\t*stack = append(*stack, s)\n}", "func (vm *VM) opPush(instr []uint16) int {\n\ta := vm.get(instr[0])\n\tvm.stack = append(vm.stack, a)\n\treturn 2\n}", "func (s *htmlState) push(tag string) {\n\ts.openTags = append(s.openTags, tag)\n}", "func (s *Stack) Push(v int) {\n\t*s = append(*s, v)\n}", "func (this *MyStack) Push(x int) {\n\tthis.l.PushBack(x)\n}", "func (this *MyStack) Push(x int) {\n\tthis.l.PushBack(x)\n}", "func (this *MyStack) Push(x int) {\n\tthis.val = append([]int{x},this.val...)\n}", "func (s *stackImpl) Push(ts ...T) {\n\ts.items = append(s.items, ts...)\n\ts.top += len(ts)\n}", "func (s *Stack) Push(value interface{}) {\n\ts.lock.Lock()\n\tdefer s.lock.Unlock()\n\tn := &node{value, s.top}\n\ts.top = n\n\ts.length++\n}", "func push(val int) {\r\n\tnode := &stack{val, nil, nil}\r\n\tBtree = Link(node, Btree)\r\n\tprint2D(Btree)\r\n}", "func (this *MyStack) Push(x int) {\n\tthis.v = append(this.v, x)\n}", "func (s *Stack) Push(v interface{}) {\n\ts.v = append(s.v, v)\n}", "func (stack *Stack) Push(val interface{}) error {\n\tif stack == nil {\n\t\treturn errors.New(\"the stack is nil\")\n\t}\n\t*stack = append(*stack, val)\n\treturn nil\n}", "func (this *MyStack) Push(x int) {\n\tthis.current.push(x)\n}", "func (ds *DrawStack) Push(a Stackable) {\n\tds.toPush = append(ds.toPush, a)\n\n}", "func (l *LexerEngine) PushMode(name string) {\n\tfor _, m := range l.def.Modes {\n\t\tif m.Name == name {\n\t\t\tl.modeStack = append(l.modeStack, l.mode)\n\t\t\tl.mode = m\n\t\t\treturn\n\t\t}\n\t}\n\tl.err = fmt.Errorf(\"LexerDef %q has no mode %q\", l.def.Name, name)\n}", "func (s *stack) Push(str string) {\n\t*s = append(*s, str)\n}", "func (s *RuneStack) Push(item rune) {\n\tif len(s.items) > s.Length {\n\t\ts.items[s.Length] = item\n\t} else {\n\t\ts.items = append(s.items, item)\n\t}\n\ts.Length++\n}", "func (s *stack) push(elem int) {\n\tif s.isFull() {\n\t\tfmt.Println(\"Stack Overflows!!!\")\n\t\treturn\n\t}\n\t*s = append(*s, elem)\n}", "func (q *SensorStack) Push(n *SensorReading) {\n\t*q = append(*q, n)\n}", "func (s *Stack) Push(value int) {\n\tn := &node{value, s.top}\n\ts.top = n\n\ts.length++\n}", "func Push(ctx ContextT) int32 {\n\treturn int32(C.yices_push(yctx(ctx)))\n}", "func (lex *Lexer) pushStateFn(fn stateFn) {\n\tlex.scope = append(lex.scope, fn)\n}", "func (s *Stack) Push(d DrawPather) {\n\t*s = append(*s, d)\n}", "func (s *stack) Push(v []byte) {\n\tif v == nil {\n\t\treturn\n\t}\n\n\t*s = append(*s, v)\n}", "func (this *MyStack) Push(x int) {\n this.Array = append(this.Array, x)\n}", "func (vm *VM) framePush(op opcode, args ...*cell) {\n\tvm.frames.push(op, vm.global.currentEnv, args...)\n}", "func (wp *workPool) push(r *remote.RepoT) {\n\toop := *wp\n\toop = append(oop, r)\n\t*wp = oop\n}", "func newScope(ast *parser.Thrift) *Scope {\n\treturn &Scope{\n\t\tast: ast,\n\t\timports: newImportManager(),\n\t\tglobals: namespace.NewNamespace(namespace.UnderscoreSuffix),\n\t\tnamespace: ast.GetNamespaceOrReferenceName(\"go\"),\n\t}\n}", "func (stack *Stack) Push(state int, sym lr.Symbol) *Stack {\n\tif sym == nil {\n\t\treturn stack\n\t}\n\t// create or find a node\n\t// - create: new and let node.prev be tos\n\t// - find: return existing one\n\t// update references / pathcnt\n\tif succ := stack.tos.findUplink(sym); succ != nil {\n\t\tT().Debugf(\"state already present: %v\", succ)\n\t\tstack.tos = succ // pushed state is already there, upchain\n\t} else {\n\t\tsucc := stack.root.findTOSofAnyStack(state, sym)\n\t\tif succ == nil { // not found in DSS\n\t\t\tsucc = stack.root.newNode(state, sym)\n\t\t\tT().Debugf(\"creating state: %v\", succ)\n\t\t\tsucc.pathcnt = stack.tos.pathcnt\n\t\t} else {\n\t\t\tT().Debugf(\"found state on other stack: %v\", succ)\n\t\t\tsucc.pathcnt++\n\t\t}\n\t\tsucc.prepend(stack.tos)\n\t\tstack.tos.append(succ)\n\t\tstack.tos = succ\n\t}\n\treturn stack\n}", "func (q *Stack) Push(val interface{}) {\n\tq.Items.Append(val)\n}", "func (stack *Stack) Push(value interface{}) {\n\tstack.list.PushBack(value)\n}", "func (this *MyStack) Push(x int) {\n\tthis.Ele = append(this.Ele, x)\n\tthis.Len++\n}", "func (s *layoutStack) push(layout geom.Layout) {\n\t// inBaseTypeCollection inherits from outer context.\n\tstackObj := layoutStackObj{\n\t\tlayout: layout,\n\t\tinBaseTypeCollection: s.topInBaseTypeCollection(),\n\t}\n\n\tswitch layout {\n\tcase geom.NoLayout:\n\t\tstackObj.layout = s.topLayout()\n\tcase geom.XYM, geom.XYZ, geom.XYZM:\n\t\tstackObj.inBaseTypeCollection = false\n\tdefault:\n\t\t// This should never happen.\n\t\tpanic(fmt.Sprintf(\"unknown geom.Layout %d\", layout))\n\t}\n\n\ts.data = append(s.data, stackObj)\n}", "func (s *Stack) Push(v string) {\n\ts.pool = append(s.pool, v)\n}", "func (s *StackStr) push(str string) {\n\ts.data[s.top] = str\n\ts.top++\n}", "func (s *MyStack_slice) Push_slice(x int) {\n\ts.slice = append(s.slice, x)\n}", "func pushStack(fromSel *Selection, nodes []*html.Node) *Selection {\n\tresult := &Selection{nodes, fromSel.document, fromSel}\n\treturn result\n}", "func (s *simpleStack) Push(v StackData) {\n\ts.s = append(s.s, v)\n}", "func (s *Stack) Push(value int) {\n\tn := &NodeStack{value}\n\ts.nodes = append(s.nodes, n)\n\ts.len++\n}", "func (lo *LuaObject) Push() {\n lo.L.RawGeti(lua.LUA_REGISTRYINDEX, lo.Ref)\n}", "func (p *Stack) Push(v interface{}) {\n\n\tp.data = append(p.data, v)\n}", "func(s *Stack) Push(i int){\n\n\ts.nums = append(s.nums, i)\n}", "func (pns *Nodes) Push(n *Node) (*Nodes, error) {\n\tns := append(*pns, *n)\n\tfmt.Printf(\"ns: %v\", ns)\n\tpns = &ns\n\treturn pns, nil\n}", "func (this *Stack) Push(x interface{}) {\n\tthis.stack = append(this.stack, x)\n}", "func (stack *Stack) Push(value interface{}) {\n\tstack.top = &Item { value, stack.top }\n\tstack.size++\n}", "func (s *Stack) Push(val interface{}) {\n\t*s = append(*s, val)\n}", "func (stack *Stack) Push(value interface{}) {\n\tstack.list.Add(nil, value)\n}", "func (s *Stack) Push(item float64) {\n\ts.Items = append(s.Items, item)\n\ts.Length++\n}", "func (s *Service) newPush(ctx context.Context, resID int) (err error) {\n\tif err = s.dao.ZAddPush(ctx, resID); err != nil {\n\t\tlog.Error(\"NewPush Redis for ResID: %d, Error: %v\", resID, err)\n\t}\n\treturn\n}", "func (s *Stack) Push(element int) {\n\t*s = append(*s, element)\n}", "func (r *Router) Push(opts ...NavigatorOpt) error {\n\n\tparams := make(url.Values, len(r.bindParamMap))\n\tfor k, v := range r.bindParamMap {\n\t\tparams[k] = v.BindParamRead()\n\t}\n\n\toutPath, outParams, err := r.bindRouteMPath.merge(params)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tq := outParams.Encode()\n\tpq := r.pathPrefix + outPath\n\tif len(q) > 0 {\n\t\tpq = pq + \"?\" + q\n\t}\n\n\tif navOpts(opts).has(NavReplace) {\n\t\tr.replacePathAndQuery(pq)\n\t} else {\n\t\tr.pushPathAndQuery(pq)\n\t}\n\n\treturn nil\n}", "func (this *MyStack) Push(x int) {\n\tthis.wareHouse.Push(x)\n}", "func (s *Stack) Push(e int) {\n\ts.container = append(s.container, e)\n\ts.Length++\n}", "func (s *nodeStack) push(n Node) {\n\ts.pop(n.Pos())\n\t*s = append((*s), n)\n}" ]
[ "0.72269505", "0.7141081", "0.67415935", "0.646811", "0.6021037", "0.59601367", "0.57661533", "0.5758549", "0.5740745", "0.57397866", "0.5709128", "0.5698204", "0.5684059", "0.5656681", "0.56090456", "0.5580778", "0.5573788", "0.55314535", "0.5492353", "0.54916126", "0.54916126", "0.54916126", "0.5469865", "0.5462435", "0.54615", "0.54584265", "0.54584265", "0.5445146", "0.54154044", "0.5400668", "0.53786343", "0.53733283", "0.53697824", "0.53583926", "0.53512037", "0.5343382", "0.532544", "0.5320803", "0.5318638", "0.53183097", "0.5316479", "0.53140676", "0.5313636", "0.53124607", "0.5300167", "0.527574", "0.52708954", "0.5265166", "0.5259776", "0.52524745", "0.52524745", "0.524929", "0.52467287", "0.5241854", "0.5235775", "0.52333593", "0.52306116", "0.5225279", "0.52145296", "0.52096736", "0.52096057", "0.52088696", "0.5193553", "0.51847863", "0.5183285", "0.5182943", "0.5175403", "0.51675916", "0.5167549", "0.51656437", "0.5158526", "0.5157368", "0.51559836", "0.5151882", "0.51517767", "0.51472574", "0.5142033", "0.5139647", "0.5139227", "0.51325256", "0.5129498", "0.5128281", "0.5127485", "0.51261836", "0.51216614", "0.5118939", "0.51168257", "0.5110602", "0.5110076", "0.5105367", "0.5099217", "0.50990707", "0.5095451", "0.5090656", "0.508528", "0.5081775", "0.50695944", "0.50640756", "0.50618315", "0.5059018" ]
0.8167801
0
Pop removes the top scope
func (s *scope) Pop() Node { if len(s.levels) == 1 { return initNode(nil) } if s.maxLen < s.len() { s.maxLen = s.len() } node := s.levels[len(s.levels)-1].init s.levels = s.levels[:len(s.levels)-1] return node }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (st *scopeStack) pop() {\n\tl := len(st.stack)\n\tif l == 1 {\n\t\tpanic(\"popped the standard library (pre-main) scope\")\n\t}\n\t// TODO OPT: Optimize for space, this will never free any underlying memory.\n\tst.stack = st.stack[:l-1]\n}", "func (s *stack) pop() {\n\ts.items = s.items[:len(s.items)-1]\n}", "func (s *state) pop(mark int) {\n\ts.vars = s.vars[0:mark]\n}", "func (p *Proc) Pop() {\n\tp.stk.load()\n}", "func (w *walk) pop() {\n\tif len(*w) > 0 {\n\t\t*w = (*w)[:len(*w)-1]\n\t}\n}", "func (cd *circularDependency) pop() {\n\t//log.Println(\"Removing:\", cd.Dependents[len(cd.Dependents)-1])\n\tcd.dependents = cd.dependents[:len(cd.dependents)-1]\n}", "func (st *stack) Pop() {\n\tif st.top == nil {\n\t\treturn\n\t}\n\n\tst.top = st.top.next\n\tst.length--\n}", "func(k *Stack) Pop(){\n\tl := len(k.nums)-1\n\n\tk.nums = k.nums[:l]\n\n\n}", "func (a *LocalActivations) Pop() {\n\tcount := len(a.activations)\n\tif count < 1 {\n\t\treturn\n\t}\n\ta.activations = a.activations[:count-1]\n}", "func (s *stack) pop() {\n\tif s.isEmpty() {\n\t\tfmt.Println(\"Stack Underflows\")\n\t\treturn\n\t}\n\t*s = (*s)[:len(*s)-1]\n}", "func (st *Stack) Pop() {\n\tif len(st.lines) <= 1 {\n\t\tst.lines = nil\n\t\treturn\n\t}\n\tst.lines = st.lines[:len(st.lines)-1]\n}", "func (tb *TreeBuilder) Pop() {\n if debug.DEBUG {\n fmt.Println(\"<<<<<<<<<<<<<<< START POP NODE <<<<<<<<<<<<<<<\")\n defer fmt.Println(\" <<<<<<<<<<<<<<< DONE POP NODE <<<<<<<<<<<<<<<\")\n }\n if debug.DEBUG {\n fmt.Println(len(tb.stack), tb.node)\n }\n tb.stack, tb.node = tb.stack[:len(tb.stack)-1], tb.stack[len(tb.stack)-1]\n if debug.DEBUG {\n fmt.Println(len(tb.stack))\n }\n}", "func (stack *PfxStack) Pop() {\n\tstack.Entries = stack.Entries[:len(stack.Entries)-1]\n\tif !stack.Entries[len(stack.Entries)-1].Last {\n\t\tstack.Entries[len(stack.Entries)-1].Preamble = stack.GetPreamble(stack.FirstDash)\n\t}\n}", "func (s *layoutStack) pop() geom.Layout {\n\ts.assertNotEmpty()\n\tif s.atTopLevel() {\n\t\tpanic(\"top level stack frame should never be popped\")\n\t}\n\tcurTopLayout := s.topLayout()\n\ts.data = s.data[:len(s.data)-1]\n\treturn curTopLayout\n}", "func (vm *VM) framePop() {\n\tf := vm.frames.pop()\n\tvm.global.op = f.op\n\tvm.global.currentEnv = f.env\n}", "func (s *stack) Pop() string {\n\tif len(*s) == 0 {\n\t\treturn \"\"\n\t}\n\n\tstr := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\treturn str\n}", "func (a *Ancestors) Pop() ast.Node {\n\tif len(*a) == 0 {\n\t\treturn nil\n\t}\n\tret := (*a)[len(*a)-1]\n\t*a = (*a)[:len(*a)-1]\n\treturn ret\n}", "func (cs *copyStack) pop() *Type {\n\tn := len(*cs)\n\tif n == 0 {\n\t\treturn nil\n\t}\n\n\tt := (*cs)[n-1]\n\t*cs = (*cs)[:n-1]\n\treturn t\n}", "func pop(a *Stack) {\n if a.head == 0 {\n fmt.Println(\"STACK EMPTY\")\n } else {a.con = a.con[:len(a.con)-1]\n\tfmt.Println(\"by reference function call\",a.con)\n\ta.head--\n }\n}", "func (l *list) Pop() {\n\tl.elements = l.elements[:len(l.elements)-1]\n}", "func (s *nodeStack) pop(pos token.Pos) (top Node) {\n\ti := len(*s)\n\tfor i > 0 && (*s)[i-1].End() <= pos {\n\t\ttop = (*s)[i-1]\n\t\ti--\n\t}\n\t*s = (*s)[0:i]\n\treturn top\n}", "func (i *incStack) Pop() {\n\tif len(i.stack) == 0 {\n\t\treturn\n\t}\n\ti.stack = i.stack[:len(i.stack)-1]\n}", "func (s *Stack) Pop() (interface{}, error) {\n\tif s.Empty() {\n\t\treturn nil, errors.New(\"can't get top of empty stack\")\n\t}\n\ttop, _ := s.Top()\n\ts.arr = s.arr[:s.Size()-1]\n\treturn top, nil\n}", "func (ss *StringStack) Pop() {\n\tss.stack = ss.stack[:len(ss.stack)-1]\n}", "func (r *renderer) pop() reflect.Value {\n\tif len(r.stack) == 0 {\n\t\treturn reflect.Value{}\n\t}\n\tctx := r.stack[len(r.stack)-1]\n\tr.stack = r.stack[:len(r.stack)-1]\n\treturn ctx\n}", "func (p *path) Pop() interface{} {\n\told := *p\n\tn := len(old)\n\tx := old[n-1]\n\t*p = old[0 : n-1]\n\treturn x\n}", "func (this *Stack) Pop() interface{} {\n\tsize := len(this.stack)\n\tres := this.stack[size-1]\n\tthis.stack = append([]interface{}{}, this.stack[0:size-1]...)\n\treturn res\n}", "func (s *IntStack) Pop() {\n\tlength := len(s.stack)\n\ts.stack = s.stack[:length - 1]\n}", "func (o *openList) Pop() interface{} {\n\topn := *o\n\tit := opn[len(opn)-1]\n\tit.pqindex = -1\n\t*o = opn[:len(opn)-1]\n\treturn it\n}", "func (s *Stack) Pop() (interface{}, error) {\n\tvar e *element = s.top\n\tif e == nil {\n\t\treturn 0, &StackError{msg: \"empty\"}\n\t}\n\ts.top = e.under\n\ts.count -= 1\n\treturn e.value, nil\n}", "func (s *outputStyleStack) PopCurrent() {\n\tif len(s.styles) > 0 {\n\t\ts.styles = s.styles[:len(s.styles)-1]\n\t}\n}", "func Test04Pop(t *testing.T) {\n\tgomega.RegisterTestingT(t)\n\n\tprefixStack := getPrefixStack()\n\tprefixStack.Push()\n\tprefixStack.Push()\n\n\tgomega.Expect(len(prefixStack.Entries)).To(gomega.BeEquivalentTo(3))\n\tprefixStack.Pop()\n\tgomega.Expect(len(prefixStack.Entries)).To(gomega.BeEquivalentTo(2))\n}", "func (s *exprStack) pop() Expression {\n\ttrace_util_0.Count(_util_00000, 163)\n\tif s.len() == 0 {\n\t\ttrace_util_0.Count(_util_00000, 165)\n\t\treturn nil\n\t}\n\ttrace_util_0.Count(_util_00000, 164)\n\tlastIdx := s.len() - 1\n\texpr := s.stack[lastIdx]\n\ts.stack = s.stack[:lastIdx]\n\treturn expr\n}", "func (s *Stack) Pop() interface{} {\r\n\tn := len(s.stk)\r\n\tvalue := s.stk[n-1]\r\n\ts.stk = s.stk[:n-1]\r\n\treturn value\r\n}", "func (sm *StackedMap) Pop() {\n\t// pop key revision\n\ttop := sm.mapStack.top().(*level)\n\tfor key := range top.kvs {\n\t\trevs := sm.keyRevisionMap[key]\n\t\trevs.pop()\n\t\tif len(*revs) == 0 {\n\t\t\tdelete(sm.keyRevisionMap, key)\n\t\t}\n\t}\n\tsm.mapStack.pop()\n}", "func (this *MyStack) Pop() int {\n\tfor this.current.Qsize() != 1 {\n\t\tthis.backup.push(this.current.pop())\n\t}\n\tres := this.current.pop()\n\tthis.current, this.backup = this.backup, this.current\n\n\treturn res\n}", "func (ds *DrawStack) Pop() {\n\tds.toPop++\n}", "func (s *Stack) Pop() {\n\tif s.Size > 0 {\n\t\ts.Tables = s.Tables[:s.Size-1]\n\t\ts.Size--\n\t} else {\n\t\tpanic(\"Popping over an empty stack of symbol tables\")\n\t\t// If you reached this line you are a magician\n\t}\n\tglog.Infof(\"Popping symbol table stack %v\\n\", s.Size)\n}", "func (s *SimpleStack) Pop() (val interface{}, err error) {\n\tif s.isEmpty() {\n\t\terr = errors.New(\"stack is empty\")\n\t\treturn\n\t}\n\tval = s.data[s.top]\n\ts.top--\n\treturn\n}", "func (s *StackTemplate) Pop() *interface{} {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tif last := len(*s) - 1; last < 0 {\n\t\treturn nil\n\t} else {\n\t\titem := (*s)[len(*s)-1]\n\t\treduced := (*s)[:last]\n\t\t*s = reduced\n\t\treturn &item\n\t}\n}", "func (stack *Stack) Pop() (interface{}, error) {\n\tif stack == nil {\n\t\treturn nil, errors.New(\"the stack is nil\")\n\t}\n\tl := len(*stack)\n\tif l == 0 {\n\t\treturn nil, errors.New(\"the stack len is 0\")\n\t}\n\tret := (*stack)[l-1]\n\t*stack = (*stack)[:l-1]\n\n\treturn ret, nil\n}", "func (t *Tree) cursorStackPop() {\n\tt.cursorStack = t.cursorStack[:len(t.cursorStack)-1]\n}", "func (c *canvasRenderer) Pop() {\n\tc.currentLayer = c.currentLayer.Previous()\n}", "func (set Set) Pop(ctx context.Context) (string, error) {\n\treq := newRequest(\"*2\\r\\n$4\\r\\nSPOP\\r\\n$\")\n\treq.addString(set.name)\n\treturn set.c.cmdString(ctx, req)\n}", "func (s *items) pop() (out Item) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (s *Stack) Pop() DrawPather {\n\tif s.Len() == 0 {\n\t\treturn nil\n\t}\n\ttmp := (*s)[s.Len()-1]\n\t*s = (*s)[:s.Len()-1]\n\treturn tmp\n}", "func (s *stack) pop() *Node {\n\tif s.empty() {\n\t\tpanic(\"invalid call to pop; empty stack\")\n\t}\n\tlength := len(s.ns)\n\tn := s.ns[length-1]\n\ts.ns = s.ns[:length-1]\n\treturn n\n}", "func (t *topK) Pop() interface{} {\n\tn := len(t.values)\n\tx := t.values[n-1]\n\tt.values = t.values[:n-1]\n\treturn x\n}", "func (p *parser) popV() {\n\t// if the map is not empty, clear it\n\tm := p.vstack[len(p.vstack)-1]\n\tif len(m) > 0 {\n\t\t// GC that map\n\t\tp.vstack[len(p.vstack)-1] = nil\n\t}\n\tp.vstack = p.vstack[:len(p.vstack)-1]\n}", "func (p *parser) popV() {\n\t// if the map is not empty, clear it\n\tm := p.vstack[len(p.vstack)-1]\n\tif len(m) > 0 {\n\t\t// GC that map\n\t\tp.vstack[len(p.vstack)-1] = nil\n\t}\n\tp.vstack = p.vstack[:len(p.vstack)-1]\n}", "func (p *parser) popV() {\n\t// if the map is not empty, clear it\n\tm := p.vstack[len(p.vstack)-1]\n\tif len(m) > 0 {\n\t\t// GC that map\n\t\tp.vstack[len(p.vstack)-1] = nil\n\t}\n\tp.vstack = p.vstack[:len(p.vstack)-1]\n}", "func (p *parser) popV() {\n\t// if the map is not empty, clear it\n\tm := p.vstack[len(p.vstack)-1]\n\tif len(m) > 0 {\n\t\t// GC that map\n\t\tp.vstack[len(p.vstack)-1] = nil\n\t}\n\tp.vstack = p.vstack[:len(p.vstack)-1]\n}", "func (p *parser) popV() {\n\t// if the map is not empty, clear it\n\tm := p.vstack[len(p.vstack)-1]\n\tif len(m) > 0 {\n\t\t// GC that map\n\t\tp.vstack[len(p.vstack)-1] = nil\n\t}\n\tp.vstack = p.vstack[:len(p.vstack)-1]\n}", "func op_POP(pc *uint64, in *interpreter, ctx *callCtx) uint64 {\n\tctx.stack.Pop()\n\treturn 0\n}", "func (s *stack) pop() int {\n\tl := len(s.items)\n\tremovedItem := s.items[l-1]\n\ts.items = s.items[:l-1]\n\treturn removedItem\n}", "func (p *PageStack) StackPopped(o, top model.Component) {\n\to.Stop()\n\tp.StackTop(top)\n}", "func (s *children) pop() (out *node) {\n\tindex := len(*s) - 1\n\tout = (*s)[index]\n\t(*s)[index] = nil\n\t*s = (*s)[:index]\n\treturn\n}", "func (s *Stack) Pop() {\n\ts.data = s.data[:len(s.data)-1]\n\t//fmt.Printf(\"popped stack size=%d\\n\", len(s.data))\n}", "func (this *MyStack) Pop() int {\n top := 0\n temp := []int{}\n length := len(this.Array)\n for i:=0; i<length; i++ {\n if len(this.Array) == 1 {\n top = this.Array[0]\n this.Array = temp\n break\n }\n temp = append(temp, this.Array[0])\n this.Array = this.Array[1:len(this.Array)]\n }\n return top\n}", "func (stack *Stack) Pop() string {\n\tret := (*stack)[len(*stack)-1]\n\t*stack = (*stack)[:len(*stack)-1]\n\treturn ret\n}", "func (stack *Item) Pop() (newstack *Item, top *Item) {\n\ttop = stack\n\tnewstack = stack.Next\n\treturn\n}", "func (s *orderedItems) Pop() interface{} {\n\told := *s\n\tn := len(old)\n\tx := old[n-1]\n\t*s = old[0 : n-1]\n\treturn x\n}", "func LevelPop() {\n len := len(logLevelStack)\n logLevel, logLevelStack = logLevelStack[len-1], logLevelStack[:len-1] \n}", "func (minSstack *MinStack) Pop() {\n\ttop := minSstack.Top()\n\tminSstack.stack = minSstack.stack[:len(minSstack.stack)-1]\n\n\tminsLen := len(minSstack.mins)\n\tif minsLen > 0 && minSstack.mins[minsLen-1] == top {\n\t\tminSstack.mins = minSstack.mins[:minsLen-1]\n\t}\n}", "func (es *eeStack) pop() (v interface{}, t eeType) {\r\n\tt = es.popType()\r\n\tv = t.pop(es)\r\n\treturn\r\n}", "func (s *Storage) RPop() *list.Element {\r\n\tele := s.Back()\r\n\tif ele != nil {\r\n\t\ts.Remove(ele)\r\n\t}\r\n\treturn ele\r\n}", "func (s *Stack) Pop() error {\n\tif len(s.a) == 0 {\n\t\treturn &EmptyError{}\n\t}\n\ts.a = s.a[:len(s.a)-1]\n\ts.Size = s.Size - 1\n\treturn nil\n}", "func (sa *StackArray) Pop() interface{} {\n\tif sa.isEmpty() {\n\t\tfmt.Println(\"The stack is empty\")\n\t\treturn nil\n\t}\n\n\titem := sa.ArrayStack[sa.Top]\n\tsa.Top--\n\n\treturn item\n}", "func (q *Stack) Pop() string {\n\ts := *q\n\tlast := s[len(s)-1]\n\t*q = s[:len(s)-1]\n\treturn last\n}", "func (s *MyStack) Pop() int {\n v := s.queue1[0]\n s.queue1 = s.queue1[1:]\n return v\n}", "func (stack *Stack) Pop() (stuff interface{}, err error) {\n\ttheStack := *stack\n\n\tif len(theStack) == 0 {\n\t\treturn nil, errors.New(\"Tried to pop an empty stack.\")\n\t}\n\n\t//get last element\n\tlast := theStack[len(theStack)-1]\n\t//reduce stack by 1\n\t*stack = theStack[:len(theStack)-1]\n\n\treturn last, nil\n}", "func (this *MyStack) Pop() int {\n\tres := this.v[len(this.v)-1]\n\tthis.v = this.v[:len(this.v)-1]\n\treturn res\n}", "func (p *TimerStack) Pop() {\n\tlastIndex := len(p.stack) - 1\n\tpopped := p.stack[lastIndex]\n\tp.stack = p.stack[:lastIndex]\n\telapsed := time.Since(popped.start)\n\tp.popEventHandler.PopEvent(popped.eventName, elapsed)\n}", "func (this *MyStack) Pop() int {\n\tx := this.Top()\n\tthis.q.PopFromFront()\n\treturn x\n}", "func Pop(ctx ContextT) int32 {\n\treturn int32(C.yices_pop(yctx(ctx)))\n}", "func (p Path) Pop() {\n\tif len(p.parts) > 0 {\n\t\tp.parts = p.parts[:len(p.parts)-1]\n\t}\n}", "func (this *MyStack) Pop() int {\n\tx := this.Queue[0]\n\tthis.Queue = this.Queue[1:]\n\treturn x\n}", "func (s *stack) Pop() []byte {\n\tif len(*s) == 0 {\n\t\treturn nil\n\t}\n\n\tv := (*s)[len(*s)-1]\n\t*s = (*s)[:len(*s)-1]\n\n\treturn v\n}", "func RemoveLastElemFromTop(c *gin.Context) { dequeueTop([]qMessage{}) }", "func (s *Stack) Pop() (interface{}, error) {\n\n\tif s.IsEmpty() {\n\t\treturn nil, fmt.Errorf(\"stack is empty\")\n\t}\n\treturn s.list.RemoveLast()\n}", "func (s *Stack) Pop() interface{} {\n\tif s.Last == nil {\n\t\treturn nil\n\t}\n\n\ttop := s.Peek()\n\ts.Last = s.Last.Next\n\n\ts.Length--\n\n\treturn top\n}", "func (h *minPath) Pop() interface{} {\n\told := *h\n\tn := len(old)\n\tx := old[n-1]\n\t*h = old[0 : n-1]\n\treturn x\n}", "func (s *Stack) Pop() (value interface{}) {\n\n if s.size > 0 {\n\n value, s.top = s.top.value, s.top.next\n\n s.size--\n\n return\n\n }\n\n return nil\n\n}", "func (s *Stack) Top() interface{} {\r\n\tn := len(s.stk)\r\n\treturn s.stk[n-1]\r\n}", "func (this *MyStack) Top() int {\n\tfor this.current.Qsize() != 1 {\n\t\tthis.backup.push(this.current.pop())\n\t}\n\tres := this.current.pop()\n\tthis.backup.push(res)\n\tthis.current, this.backup = this.backup, this.current\n\n\treturn res\n}", "func PopSub() {\n\toutput.EmitLn(\"SUB (SP)+,D0\")\n}", "func (sm *StackMax) Pop() (int, error) {\n\tif sm.Empty() {\n\t\treturn -1, ErrstackEmpty\n\t}\n\n\ttop, _ := sm.Top()\n\n\tsm.length--\n\tsm.container = sm.container[:sm.length]\n\tsm.maxer = sm.maxer[:sm.length]\n\treturn top, nil\n}", "func (s *Stack) Pop() (int, error) {\n\tif s.Empty() {\n\t\treturn -1, ErrstackEmpty\n\t} else {\n\t\ttop := s.container[s.Length-1]\n\t\ts.container = s.container[:s.Length-1]\n\t\ts.Length--\n\t\treturn top, nil\n\t}\n}", "func (lex *Lexer) popStateFn() stateFn {\n\tl := len(lex.scope)\n\tif l == 0 {\n\t\treturn nil\n\t}\n\tfn := lex.scope[l-1] //last scope\n\tlex.scope = lex.scope[:l-1] //pop it\n\treturn fn\n}", "func (q *Stack) Pop() interface{} {\n\treturn q.Items.Pop().Value\n}", "func (hat *HashedArrayTree) Pop() (interface{}, error) {\n\treturn hat.Remove(hat.size - 1)\n}", "func (s *Stack) Pop() interface{} {\n\tv := s.v[len(s.v)]\n\ts.v = s.v[:len(s.v)-1]\n\treturn v\n}", "func (s *Stack) Pop() {\n\tif s.head != nil {\n\t\ttemp := s.head.next\n\t\ts.head = temp\n\t\ts.Length--\n\t}\n}", "func Pop(context *endly.Context) *model.Process {\n\tvar processes = processes(context)\n\tvar process = processes.Pop()\n\tif process != nil && process.Source != nil {\n\t\tcontext.Source = process.Source\n\t}\n\treturn process\n}", "func (s *Slot) pop() Item {\n\titem := s.item\n\ts.item = Empty\n\treturn item\n}", "func (this *Stack) Pop() interface{} {\n\tif this.length == 0 {\n\t\treturn nil\n\t}\n\n\tn := this.top\n\tthis.top = n.prev\n\tthis.length--\n\treturn n.value\n}", "func Pop(ctx echo.Context) error {\n\n\treq := types.PopRequest{}\n\n\terr := ctx.Bind(&req)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tif !registration.IsAgentRegistered(req.Token) {\n\t\treturn ctx.JSON(403, types.ValidateResponse{Success: false, Message: \"Security Token Not Recognized\"})\n\t}\n\n\tmsg, err := GetFromQueue(req.Queue)\n\n\tdata := types.Message{}\n\n\tjson.Unmarshal(msg, &data)\n\n\tresp := types.PopResponse{Message: data.Message, Queue: req.Queue}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ctx.JSON(200, resp)\n}", "func (this *MyStack) Pop() int {\n\tfor this.l.Front().Next() != nil {\n\t\tthis.t.PushBack(this.l.Remove(this.l.Front()))\n\t}\n\ttop := this.l.Remove(this.l.Front())\n\tfor this.t.Front() != nil {\n\t\tthis.l.PushBack(this.t.Remove(this.t.Front()))\n\t}\n\treturn top.(int)\n}", "func (s *StackStr) pop() (string, error) {\n\tif s.top == 0 {\n\t\terr := fmt.Errorf(\"stack is empty\")\n\t\treturn \"\", err\n\t}\n\ts.top--\n\treturn s.data[s.top], nil\n}", "func (s *Stack) Pop() string {\n\tindex := len(*s) - 1\n\telement := (*s)[index]\n\t*s = (*s)[:index]\n\n\treturn element\n}" ]
[ "0.79989535", "0.7346639", "0.72030395", "0.7133182", "0.7129924", "0.7069357", "0.70120084", "0.70074743", "0.69683355", "0.6848808", "0.68228257", "0.68020207", "0.6734725", "0.66969514", "0.66828054", "0.6635206", "0.662392", "0.661473", "0.66137195", "0.65989554", "0.6593697", "0.659349", "0.6570823", "0.6563948", "0.65623426", "0.65298784", "0.6528325", "0.65258306", "0.6485048", "0.64702976", "0.64633644", "0.6462859", "0.64443296", "0.6435029", "0.6433184", "0.6418686", "0.6416352", "0.6414318", "0.6403225", "0.6392881", "0.63911355", "0.638353", "0.6382652", "0.6374648", "0.63667107", "0.6366197", "0.6365652", "0.63655645", "0.6349286", "0.6349286", "0.6349286", "0.6349286", "0.6349286", "0.6345583", "0.63437337", "0.63432264", "0.6333165", "0.6331978", "0.63179636", "0.63153577", "0.6308872", "0.63062465", "0.6300081", "0.6295305", "0.6292501", "0.62915546", "0.6280726", "0.6274608", "0.6270544", "0.6269545", "0.62651443", "0.62554926", "0.6254716", "0.62494", "0.62455744", "0.6236156", "0.6233129", "0.62296027", "0.62228745", "0.6221059", "0.62206984", "0.62108266", "0.62094957", "0.6207814", "0.6205822", "0.62056434", "0.62036985", "0.61988485", "0.6195494", "0.6189825", "0.6189556", "0.617803", "0.6177711", "0.6175993", "0.6171897", "0.6168836", "0.6166145", "0.61643726", "0.616285", "0.6162115" ]
0.7049225
6
len returns the number of variables that need to be allocated for the current stack of scopes.
func (s *scope) len() int { l := 0 for _, level := range s.levels { l += len(level.named) + len(level.init) } return l }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s *exprStack) len() int {\n\ttrace_util_0.Count(_util_00000, 170)\n\treturn len(s.stack)\n}", "func localswords() int32 {\n\treturn int32(stkptrsize / int64(Widthptr))\n}", "func (s *Stack) Len() int {\n\n return s.size\n\n}", "func (s *Stack) Len() int {\n\treturn s.n\n}", "func (s *DynamicStack) Len() int {\n\treturn len(s.data)\n}", "func (sr *Stackers) Length() int {\n\tvar l int\n\tsr.ro.Lock()\n\t{\n\t\tl = len(sr.stacks)\n\t\tsr.ro.Unlock()\n\t}\n\treturn l\n}", "func (s *stack) Len() int {\n\treturn s.length\n}", "func (s *Stack) Len() int {\n\ts.mutex.Lock()\n\tdefer s.mutex.Unlock()\n\treturn s.count\n}", "func (s Stack) Len() int {\r\n\treturn len(s.stk)\r\n}", "func (s *Stack) Len() int{\n\treturn s.size\n}", "func (q *Stack) Len() int { return q.data.Len() }", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (s *Stack) Len() int {\n\treturn s.size\n}", "func (stack Stack) Len() int {\n\treturn len(stack)\n}", "func (m *RPN) StackLen() int {\n\treturn len(m.stack)\n}", "func (q *Stack) Len() int {\n\tq.lock.Lock()\n\tdefer q.lock.Unlock()\n\treturn q.count\n}", "func (s *Stack) Len() int {\n\treturn s.Length\n}", "func (m *varMap) Len() int {\n\treturn len(m.vars)\n}", "func (ev EnvVariableList) Len() int {\n\treturn len(ev)\n}", "func (p RProc) NLocals() int {\n\tif MrbProcCFuncP(p) {\n\t\treturn 0\n\t}\n\treturn int(C._mrb_rproc_nlocals(p.p))\n}", "func (s *Stack) Len() int {\n\treturn s.length\n}", "func (s *Stack) Len() int {\n\treturn s.length\n}", "func (s *StackInt) Length() int {\nlength := len(s.s)\nreturn length\n}", "func (stack *Stack) Len() int {\n\treturn len(*stack)\n}", "func (s *Stack) Len() int {\n\ts.lock.RLock()\n\tdefer s.lock.RUnlock()\n\treturn len(s.data)\n}", "func (this *Stack) Len() int {\n\treturn this.length\n}", "func (this *Stack) Len() int {\n\treturn this.length\n}", "func (s *BlockingStack) Len() int {\n\treturn s.size\n}", "func (v Var) Len() (uint64, error) {\n\tdims, err := v.Dims()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn := uint64(1)\n\tfor _, d := range dims {\n\t\tlen, err := d.Len()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tn *= len\n\t}\n\treturn n, nil\n}", "func (e REnv) Len() int { return int(C._MRB_ENV_LEN(e.p)) }", "func (ss *SliceStack) Len() int {\n\treturn ss.backer.Len()\n}", "func (s *Stack) Len() int {\n\treturn len(*s)\n}", "func (ls *ListStack) Len() int {\n\tif ls.threadSafe {\n\t\tls.lock.Lock()\n\t\tdefer ls.lock.Unlock()\n\t\treturn ls.backer.Len()\n\t}\n\n\treturn ls.backer.Len()\n}", "func (pl *Payload) len() int {\n\treturn len(pl.CNIReports) + len(pl.CNSReports) + len(pl.DNCReports) + len(pl.NPMReports)\n}", "func (stack *ArrayStack) Len() int {\n\treturn stack.list.Len()\n}", "func (a *Arguments) Len() int {\n\treturn len(a.exprs)\n}", "func (stack *Stack) Len() int {\n\treturn stack.list.Len()\n}", "func (t *Trace) Len() int {\n\treturn t.n\n}", "func (v Var) LenDims() ([]uint64, error) {\n\tdims, err := v.Dims()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tls := make([]uint64, len(dims))\n\tfor i, d := range dims {\n\t\tls[i], err = d.Len()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ls, nil\n}", "func Len(scope common.Scope, args ...interface{}) interface{} {\n\tif s, ok := args[0].(string); ok {\n\t\treturn int64(len(s))\n\t}\n\treturn 0\n}", "func (e REnv) AdjustStackLength(nlocals int) {\n\tif e.p != nil {\n\t\tif int(C._MRB_ENV_LEN(e.p)) < nlocals {\n\t\t\tC._MRB_ENV_SET_LEN(e.p, C.mrb_int(nlocals))\n\t\t}\n\t}\n}", "func (vs *Variables) Count() int {\n\treturn len(vs.n)\n}", "func (f *Float64Stack) Len() int {\n\tf.mu.RLock()\n\tdefer f.mu.RUnlock()\n\treturn len(f.items)\n}", "func (s *stackImpl) Len() int {\n\treturn len(s.items)\n}", "func (confVars ConfigurationVariableSlice) Len() int {\n\treturn len(confVars)\n}", "func (confVars ConfigurationVariableSlice) Len() int {\n\treturn len(confVars)\n}", "func (st *stack) Size() int {\n\treturn st.length\n}", "func (h ReqHeap) Len() int { return len(h) }", "func (ss statements) Len() int {\n\treturn len(ss)\n}", "func (k keyDecls) Len() int {\n\treturn len(k)\n}", "func (que *QueueUsingStack) Length() int {\r\n\treturn que.stk1.Len() + que.stk2.Len()\r\n}", "func (p *Parameters) Len() int {\n\treturn len(p.names)\n}", "func (s *Stack) Length() uint64 {\n\treturn s.head - s.tail\n}", "func (ac *AuthContext) Len() int {\n\tl := 1\n\tif ac.Parent != nil {\n\t\tl += ac.Parent.Len()\n\t}\n\treturn l\n}", "func (h *Heap) Len() int { return len(h.slice) }", "func (p FunctionCallSlice) Len() int { return len(p) }", "func (k *K) Len() int {\n\tif k.Type < K0 || k.Type >= KFUNC {\n\t\treturn 1\n\t} else if k.Type >= K0 && k.Type <= KT {\n\t\treturn reflect.ValueOf(k.Data).Len()\n\t} else if k.Type == XD {\n\t\treturn k.Data.(Dict).Key.Len()\n\t} else if k.Type == XT {\n\t\treturn k.Data.(Table).Data[0].Len()\n\t} else {\n\t\treturn -1\n\t}\n}", "func (r WriteableResumeFrame) Len() int {\n\treturn core.FrameHeaderLen + _lenTokenLength + _lenFirstPos + _lenLastRecvPos + _lenVersion + len(r.token)\n}", "func (q *SensorStack) Len() int {\n\treturn len(*q)\n}", "func size(insn isa.Insn) uint {\n\tvar sz uint\n\tswitch insn.(type) {\n\tcase isa.Label, isa.Nop:\n\t\treturn 0\n\tcase isa.JumpType, isa.CheckBegin:\n\t\tsz += 4\n\tdefault:\n\t\tsz += 2\n\t}\n\n\t// handle instructions with extra args\n\tswitch insn.(type) {\n\tcase isa.MemoOpen, isa.MemoTreeOpen, isa.MemoTreeClose, isa.CaptureBegin, isa.CaptureLate,\n\t\tisa.CaptureFull, isa.TestChar, isa.TestCharNoChoice, isa.TestSet,\n\t\tisa.TestSetNoChoice, isa.TestAny, isa.Error, isa.CheckBegin, isa.CheckEnd:\n\t\tsz += 2\n\t}\n\n\treturn sz\n}", "func (st *Stack) Size() int {\n\treturn len(st.lines)\n}", "func (pp *Pingreq) Len() int {\n\treturn nakedLen()\n}", "func (f *Frame) LastLvarIndex() int {\n\treturn f.stack.Size()\n}", "func (a ASTNode) Len() int {\n\tif !a.IsArr() {\n\t\tpanic(ConfErr{a.pos, errors.New(\"Not an array\")})\n\t}\n\treturn len(a.val.(astArr))\n}", "func (vs variableSet) count() int {\n\tc := 0\n\tif vs[0] != nil {\n\t\tc++\n\t}\n\tif vs[1] != nil {\n\t\tc++\n\t}\n\tif vs[2] != nil {\n\t\tc++\n\t}\n\tif vs[3] != nil {\n\t\tc++\n\t}\n\treturn c\n}", "func (s *UndoStack) Len() int {\n\treturn len(s.states)\n}", "func (u *Roll) MaxLen() int {\n\tns := u.S.nodes\n\tmax := 0\n\tfor i := 1; i < len(ns); i++ {\n\t\tv := z.Var(i)\n\t\tn := len(u.dmap[v])\n\t\tif n > max {\n\t\t\tmax = n\n\t\t}\n\t}\n\treturn max\n}", "func LLEN() int {\n\treturn globalListCache.countKeys()\n}", "func (hm HashMap) Len(ctx context.Context) (int64, error) {\n\treq := newRequest(\"*2\\r\\n$4\\r\\nHLEN\\r\\n$\")\n\treq.addString(hm.name)\n\treturn hm.c.cmdInt(ctx, req)\n}", "func (idx *Tree) Len() (count int) {\n\tidx.Stop()\n\tcount = int(idx.liveObjects)\n\tfor _, a := range idx.allocators {\n\t\tcount += int(a.itemCounter)\n\t}\n\tidx.Start()\n\treturn\n}", "func (g *mapGen) genLen() {\n\tg.P(\"func (x *\", g.typeName, \") Len() int {\")\n\t// invalid map\n\tg.P(\"if x.m == nil {\")\n\tg.P(\"return 0\")\n\tg.P(\"}\")\n\t// valid map\n\tg.P(\"return len(*x.m)\")\n\tg.P(\"}\")\n\tg.P()\n}", "func (s *Stack[T]) Size() int {\n\treturn len(s.array)\n}", "func (s *Stack) Size() int {\n\treturn len(s.arr)\n}", "func (p *Packed2DGenericTypeBuilder) Len() int {\n\treturn p.tail\n}", "func (s *Stack) Size() int {\n\treturn len(*s)\n}", "func (p *Puzzle) Len() int {\r\n\treturn 4 + 4 + len(p.Random) + len(p.Padding)\r\n}", "func len(v Type) int32 {}", "func (ms *memoryStore) Len() int {\n\treturn len(ms.namespaces)\n}", "func (s *LinkedStack) Size() int { return s.count }", "func (args *Args) len() int {\n\treturn len(args.items)\n}", "func (fib *Fib) Len() int {\n\treturn fib.tree.CountEntries()\n}", "func (dist Beta) NumVars() int {\n\treturn 1\n}", "func (pool GenePool) Len() int {\n return len(pool)\n}", "func (s *Stack) Size() int {\n\treturn s.count\n}", "func (s *Stack) Size() int {\n\treturn len(s.data)\n}", "func (s *Stack) Size() int {\n\treturn len(s.data)\n}", "func (s *Stack) Size() int {\n\treturn len(s.data)\n}", "func (s *Stack) Size() int {\n\treturn len(s.data)\n}", "func (s *Pool) Len() int { return int(atomic.LoadUint32(&s.avail)) }", "func (tree *RedBlack[K, V]) Len() int {\n\treturn tree.size\n}", "func (f *Frame) Len() int64 {\n\treturn f.Nchars\n}", "func varCount(m string) map[string]int {\n\tcnt := map[string]int{}\n\tvarCount1(m, cnt)\n\treturn cnt\n}", "func (s *state) mark() int {\n\treturn len(s.vars)\n}", "func (p NodePools) Len() int { return len(p) }", "func (o openstacksByName) Len() int { return len(o) }", "func Len() int {\n\treturn len(box)\n}" ]
[ "0.7618989", "0.705599", "0.66435045", "0.6631414", "0.6630447", "0.66147894", "0.65583503", "0.6530065", "0.6522784", "0.65066147", "0.6447089", "0.6423462", "0.6423462", "0.6423462", "0.6423462", "0.6423462", "0.6423462", "0.6412941", "0.63858396", "0.63790137", "0.63477904", "0.63446164", "0.63118804", "0.63069624", "0.62975913", "0.62975913", "0.6250531", "0.6235204", "0.61862606", "0.61596733", "0.61596733", "0.61454123", "0.6123415", "0.6120585", "0.6073308", "0.60700566", "0.6014677", "0.59871954", "0.58665186", "0.586455", "0.58575606", "0.5856707", "0.5839347", "0.5828151", "0.5825989", "0.5802683", "0.57861197", "0.57800424", "0.5772635", "0.5772635", "0.574984", "0.5746451", "0.5745715", "0.5742852", "0.5709371", "0.56887776", "0.5686516", "0.5682156", "0.5651576", "0.56282914", "0.5623761", "0.5623274", "0.55608517", "0.55591446", "0.5553243", "0.55465615", "0.55356014", "0.5526508", "0.5511187", "0.5499708", "0.54988503", "0.5489544", "0.54881054", "0.54841775", "0.54836226", "0.5481935", "0.54799247", "0.54798144", "0.5477002", "0.5473287", "0.5469195", "0.54672617", "0.54606116", "0.54581815", "0.54558915", "0.54488534", "0.5435366", "0.54321784", "0.54292166", "0.54292166", "0.54292166", "0.54292166", "0.5427591", "0.54158866", "0.5411403", "0.5400052", "0.5395036", "0.53753227", "0.5363593", "0.53625983" ]
0.7403139
1
Lookup returns the Variable for the given name from the most specific possible scope. If the name cannot be found, it is inserted into the broadest scope and the new Variable is returned.
func (s *scope) Lookup(name string) Variable { l := len(s.levels) for i := l - 1; i >= 0; i-- { if v, ok := s.levels[i].named[name]; ok { return v } } v := Variable(s.maxLen) s.levels[0].named[name] = v s.maxLen++ return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (st *SymTab) Lookup(name ID) Type {\n\tfor i := len(st.scopes.stack) - 1; i >= 0; i-- {\n\t\tif t, ok := st.scopes.stack[i].scope[name]; ok {\n\t\t\treturn t\n\t\t}\n\t}\n\treturn nil\n}", "func (vars Variables) Lookup(n *scparse.VariableNode) (interface{}, bool) {\n\tv := vars.lookup(n)\n\tif !v.IsValid() {\n\t\treturn nil, false\n\t}\n\treturn v.Interface(), true\n}", "func Lookup(name string) (value interface{}, ok bool) {\n\tinitialize()\n\tlock.RLock()\n\tvalue, ok = notGlobals[name]\n\tlock.RUnlock()\n\treturn value, ok\n}", "func (g *Grammar) Lookup(name string) (out *Rule) {\n\trule, ok := g.rules[name]\n\tif !ok {\n\t\trule = &Rule{name, nil}\n\t\tg.rules[name] = rule\n\t}\n\treturn rule\n}", "func (scope *Scope) Get(identifier string) Variable {\n\tscope.initialize()\n\tvariable, contains := scope.variables[identifier]\n\tif !contains && scope.previous != nil {\n\t\treturn scope.previous.Get(identifier)\n\t}\n\treturn variable\n}", "func (s *Stack) Lookup(name string) (*gotypes.SymbolDef, symboltable.SymbolType, error) {\n\t// The top most item on the stack is the right most item in the simpleSlice\n\tfor i := s.Size - 1; i >= 0; i-- {\n\t\tdef, st, err := s.Tables[i].Lookup(name)\n\t\tif err == nil {\n\t\t\treturn def, st, nil\n\t\t}\n\t}\n\treturn nil, symboltable.SymbolType(\"\"), fmt.Errorf(\"Symbol %v not found\", name)\n}", "func VariableFind(vars []Variable, s string) *Variable {\n\tfor _, v := range vars {\n\t\tif v.Name == s {\n\t\t\treturn &v\n\t\t}\n\t}\n\treturn nil\n}", "func (s *callStack) lookUpVar(id ast.Identifier) *cachedThunk {\n\tfor i := len(s.stack) - 1; i >= 0; i-- {\n\t\tbind, present := s.stack[i].env.upValues[id]\n\t\tif present {\n\t\t\treturn bind\n\t\t}\n\t\tif s.stack[i].cleanEnv {\n\t\t\t// Nothing beyond the captured environment of the thunk / closure.\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (s *scope) lookup(name string) *objectAndSource {\n\tif o, found := s.objects[name]; found {\n\t\treturn &o\n\t}\n\tif s.parent == nil {\n\t\treturn nil\n\t}\n\treturn s.parent.lookup(name)\n}", "func (gen *Generator) NamedLookup(name string) ast.Node {\n\treturn NodeByName(gen.Nodes.Definition, name)\n}", "func (n *node) Lookup(ctx context.Context, name string) (fspkg.Node, error) {\n\te, ok := n.te.LookupChild(name)\n\tif !ok {\n\t\treturn nil, syscall.ENOENT\n\t}\n\treturn &node{n.fs, e}, nil\n}", "func (n Name) Lookup() string {\n\tlookup, _ := n.GetLookupAndType()\n\treturn lookup\n}", "func (state *State) FetchVariable(name string) (val *Value) {\n\tdefer func(){\n\t\tif x := recover(); x != nil {\n\t\t\tval = nil\n\t\t}\n\t}()\n\t\n\tparts := strings.Split(name, \":\")\n\tif len(parts) < 2 {\n\t\treturn nil\n\t}\n\tmod := state.FetchModule(parts[0])\n\tfor i := range parts[1:len(parts) - 1] {\n\t\tmod = mod.FetchModule(parts[i+1])\n\t}\n\tif mod == nil {\n\t\treturn nil\n\t}\n\tvalI := mod.vars.lookup(parts[len(parts) - 1])\n\treturn mod.vars.get(valI)\n}", "func Lookup(name string) Type {\n\tif t, ok := keywords[name]; ok {\n\t\treturn t\n\t}\n\treturn NAME\n}", "func (n *Node) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tlog.Println(\"Lookup\", name)\n\tnode, ok := n.fs.Nodes[name]\n\tif ok {\n\t\treturn node, nil\n\t}\n\treturn nil, fuse.ENOENT\n}", "func (f *FlagSet) Lookup(name string) *Flag {\n\treturn f.lookup(f.normalizeFlagName(name))\n}", "func (ndtt *Thread) Lookup(name ndn.Name) uint8 {\n\tnameP := ndni.NewPName(name)\n\tdefer nameP.Free()\n\treturn uint8(C.Ndtt_Lookup(ndtt.ptr(), (*C.PName)(nameP.Ptr())))\n}", "func (l *Loader) Lookup(name string, ver int) Sym {\n\tif ver >= sym.SymVerStatic || ver < 0 {\n\t\treturn l.extStaticSyms[nameVer{name, ver}]\n\t}\n\treturn l.symsByName[ver][name]\n}", "func Lookup(name string) string {\n\treturn index[name]\n}", "func (s *scope) Insert(name string) Variable {\n\tl := len(s.levels)\n\tv, ok := s.levels[l-1].named[name]\n\tif ok {\n\t\treturn v\n\t}\n\tv = Variable(s.len())\n\ts.levels[l-1].named[name] = v\n\ts.maxLen++\n\treturn v\n}", "func (ec *EvalCtx) ResolveVar(ns, name string) Variable {\n\tif ns == \"env\" {\n\t\treturn newEnvVariable(name)\n\t}\n\tif mod, ok := ec.modules[ns]; ok {\n\t\treturn mod[name]\n\t}\n\n\tmay := func(n string) bool {\n\t\treturn ns == \"\" || ns == n\n\t}\n\tif may(\"local\") {\n\t\tif v, ok := ec.local[name]; ok {\n\t\t\treturn v\n\t\t}\n\t}\n\tif may(\"up\") {\n\t\tif v, ok := ec.up[name]; ok {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func (ec *EvalCtx) ResolveVar(ns, name string) Variable {\n\tif ns == \"env\" {\n\t\tev := envVariable{name}\n\t\treturn ev\n\t}\n\tif mod, ok := ec.modules[ns]; ok {\n\t\treturn mod[name]\n\t}\n\n\tmay := func(n string) bool {\n\t\treturn ns == \"\" || ns == n\n\t}\n\tif may(\"local\") {\n\t\tif v, ok := ec.local[name]; ok {\n\t\t\treturn v\n\t\t}\n\t}\n\tif may(\"up\") {\n\t\tif v, ok := ec.up[name]; ok {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func (s *Scope) findUndeclared(name []byte) *Var {\n\tfor _, v := range s.Undeclared {\n\t\t// no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope\n\t\tif 0 < v.Uses && bytes.Equal(name, v.Data) {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func Lookup(ident string) Token {\n\tif tok, is_keyword := directives[ident]; is_keyword {\n\t\treturn tok\n\t}\n\treturn NotFound\n}", "func Lookup(name string) *Flag {\n\tf, ok := flags.formal[name];\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn f;\n}", "func (vm *VM) scopeResolve(variable string, result func(*Scope)) {\n\tworking := vm.Scope\n\tfor working != nil {\n\t\tif _, here := working.variables[variable]; here {\n\t\t\tresult(working)\n\t\t\treturn\n\t\t}\n\t\tworking = working.previous\n\t}\n}", "func (e *Env) Lookup() string {\n\tenvironment, isset := os.LookupEnv(e.env)\n\tif !isset {\n\t\treturn e.def\n\t}\n\treturn environment\n}", "func rcFindVar(p *TCompiler, code *TCode) (*value.Value, error) {\n\tname := p.Consts.Get(code.B).ToString()\n\tv, _ := p.sys.Scopes.Find(name)\n\tp.regSet(code.A, v)\n\tp.moveNext()\n\treturn v, nil\n}", "func (s *Scope) Declare(decl DeclType, name []byte) (*Var, bool) {\n\t// refer to new variable for previously undeclared symbols in the current and lower scopes\n\t// this happens in `{ a = 5; } var a` where both a's refer to the same variable\n\tcurScope := s\n\tif decl == VariableDecl || decl == FunctionDecl {\n\t\t// find function scope for var and function declarations\n\t\ts = s.Func\n\t}\n\n\tif v := s.findDeclared(name); v != nil {\n\t\t// variable already declared, might be an error or a duplicate declaration\n\t\tif (v.Decl == LexicalDecl || decl == LexicalDecl) && v.Decl != ExprDecl {\n\t\t\t// redeclaration of let, const, class on an already declared name is an error, except if the declared name is a function expression name\n\t\t\treturn nil, false\n\t\t}\n\t\tif v.Decl == ExprDecl {\n\t\t\tv.Decl = decl\n\t\t}\n\t\tv.Uses++\n\t\tif s != curScope {\n\t\t\tcurScope.Undeclared = append(curScope.Undeclared, v) // add variable declaration as used variable to the current scope\n\t\t}\n\t\treturn v, true\n\t}\n\n\tvar v *Var\n\t// reuse variable if previously used, as in: a;var a\n\tif decl != ArgumentDecl { // in case of function f(a=b,b), where the first b is different from the second\n\t\tfor i, uv := range s.Undeclared[s.NumArguments:] {\n\t\t\t// no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope\n\t\t\tif 0 < uv.Uses && bytes.Equal(name, uv.Data) {\n\t\t\t\tv = uv\n\t\t\t\ts.Undeclared = append(s.Undeclared[:int(s.NumArguments)+i], s.Undeclared[int(s.NumArguments)+i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif v == nil {\n\t\t// add variable to the context list and to the scope\n\t\tv = &Var{decl, name, nil, 0}\n\t} else {\n\t\tv.Decl = decl\n\t}\n\tv.Uses++\n\ts.Declared = append(s.Declared, v)\n\tif s != curScope {\n\t\tcurScope.Undeclared = append(curScope.Undeclared, v) // add variable declaration as used variable to the current scope\n\t}\n\treturn v, true\n}", "func (as *AllState) VarByName(varNm string) *Variable {\n\tfor _, vr := range as.Vars {\n\t\tif vr.Nm == varNm {\n\t\t\treturn vr\n\t\t}\n\t}\n\tnmspl := strings.Split(varNm, \".\")\n\tfor _, vr := range as.GlobalVars {\n\t\tspl := strings.Split(vr.Nm, \".\")\n\t\tif len(spl) == len(nmspl) && vr.Nm == varNm {\n\t\t\treturn vr\n\t\t}\n\t\tif len(nmspl) == 1 && len(spl) == 2 && spl[1] == varNm {\n\t\t\treturn vr\n\t\t}\n\t}\n\treturn nil\n}", "func Lookup(ident string) Token {\n\tif tok, ok := keywords[ident]; ok {\n\t\treturn tok\n\t}\n\treturn Identifier\n}", "func (r *Wrapper) Lookup(name string) (val any, ok bool) {\n\tfv := r.rv.FieldByName(name)\n\tif !fv.IsValid() {\n\t\treturn\n\t}\n\n\tif fv.CanInterface() {\n\t\treturn fv.Interface(), true\n\t}\n\treturn\n}", "func (n *Node) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tn.log.Lookup(ctx, name)\n\tlink, _, err := uio.ResolveUnixfsOnce(ctx, n.Ipfs.DAG, n.Nd, []string{name})\n\tswitch err {\n\tcase os.ErrNotExist, mdag.ErrLinkNotFound:\n\t\t// todo: make this error more versatile.\n\t\treturn nil, fuse.ENOENT\n\tdefault:\n\t\tn.log.Errorf(\"fuse lookup %q: %s\", name, err)\n\t\treturn nil, fuse.EIO\n\tcase nil:\n\t\t// noop\n\t}\n\n\tnd, err := n.Ipfs.DAG.Get(ctx, link.Cid)\n\tswitch err {\n\tcase ipld.ErrNotFound:\n\tdefault:\n\t\tn.log.Errorf(\"fuse lookup %q: %s\", name, err)\n\t\treturn nil, err\n\tcase nil:\n\t\t// noop\n\t}\n\n\treturn &Node{Ipfs: n.Ipfs, Nd: nd, log: n.log}, nil\n}", "func (f *Forward) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {\n\tif f == nil {\n\t\treturn nil, ErrNoForward\n\t}\n\n\treq := new(dns.Msg)\n\treq.SetQuestion(name, typ)\n\tstate.SizeAndDo(req)\n\n\tstate2 := request.Request{W: state.W, Req: req}\n\n\treturn f.Forward(state2)\n}", "func (s *varsScope) getScopeForVariable(varName string) *varsScope {\n\n\t_, ok := s.storage[varName]\n\n\tif ok {\n\t\treturn s\n\t} else if s.parent != nil {\n\t\treturn s.parent.(*varsScope).getScopeForVariable(varName)\n\t}\n\n\treturn nil\n}", "func (p *scopeParser) referenceVariable(name *tree.Token) *Variable {\n\tv := p.getLocalVar(name)\n\tif v != nil {\n\t\tp.addVariableName(v, name)\n\t} else {\n\t\tv = p.addGlobalVar(name)\n\t}\n\treturn v\n}", "func Lookup(name string) string {\n\treturn servers[name]\n}", "func lookup(s *types.Scope, name string) *types.Struct {\n\tif o := s.Lookup(name); o != nil {\n\t\tu := o.Type().Underlying()\n\t\tif s, ok := u.(*types.Struct); ok {\n\t\t\treturn s\n\t\t}\n\t}\n\tfor i := 0; i < s.NumChildren(); i++ {\n\t\ts := lookup(s.Child(i), name)\n\t\tif s != nil {\n\t\t\treturn s\n\t\t}\n\t}\n\treturn nil\n}", "func (p *EnvProvider) Lookup(key string) (string, error) {\n\tvalue, ok := os.LookupEnv(key)\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"Value not found in the environment\")\n\t}\n\n\treturn value, nil\n}", "func (d *gossipDiscoveryImpl) Lookup(PKIID common.PKIidType) *NetworkMember {\n\tif bytes.Equal(PKIID, d.self.PKIid) {\n\t\treturn &d.self\n\t}\n\td.lock.RLock()\n\tdefer d.lock.RUnlock()\n\treturn copyNetworkMember(d.id2Member[string(PKIID)])\n}", "func (r *SRegionDNS) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {\n\treturn r.Upstream.Lookup(state, name, typ)\n}", "func (r *Registry) Lookup(name string) *Object {\n\tr.Lock()\n\tdefer r.Unlock()\n\n\tif obj, ok := r.dataStores[name]; ok {\n\t\tif obj.Enabled {\n\t\t\treturn obj\n\t\t}\n\t}\n\treturn nil\n}", "func (app *registry) Fetch(name string) (computable.Value, error) {\n\tif val, ok := app.variables[name]; ok {\n\t\treturn val, nil\n\t}\n\n\tstr := fmt.Sprintf(\"the variable (name: %s) is not declared in the registry\", name)\n\treturn nil, errors.New(str)\n}", "func (s *Scope) findDeclared(name []byte) *Var {\n\tfor _, v := range s.Declared {\n\t\t// no need to evaluate v.Link as v.Data stays the same, and Link is always nil in Declared\n\t\tif bytes.Equal(name, v.Data) {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}", "func Get(name string) interface{} {\n\tlock.Lock()\n\tvar v, found = env.variables[name]\n\tlock.Unlock()\n\n\tif found {\n\t\tv.mutex.Lock()\n\t\tif v.cachedValue != nil {\n\t\t\tdefer v.mutex.Unlock()\n\t\t\treturn v.cachedValue.value\n\t\t}\n\t\tv.mutex.Unlock()\n\t}\n\n\tvar value interface{}\n\tif !found {\n\t\t// it's for an ad-hoc value, let's go through the default chain\n\t\tfor _, source := range env.settings.DefaultSources {\n\t\t\tvalue = source.Provider().Get(name, source.Config())\n\t\t\tif value != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// it's a variable\n\t\tfor _, s := range v.sources {\n\t\t\tsourceValue := s.source.Provider().Get(name, s.source.Config())\n\t\t\ts.cachedValue = &valuePlaceholder{value: sourceValue} // cache the given value to identify if there were changes in a refresh\n\t\t\tif value == nil && sourceValue != nil {\n\t\t\t\tvalue = sourceValue\n\t\t\t\tif v.converter != nil {\n\t\t\t\t\tvalue = v.converter(value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif value == nil {\n\t\t\tvalue = v.defaultValue\n\t\t}\n\t\tv.cachedValue = &valuePlaceholder{value: value}\n\t}\n\n\treturn value\n}", "func (naming *NamingService) Lookup(name string) (clientproxy.ClientProxy, error) {\n\tclientProxy, present := naming.Repository[name]\n\tif !present {\n\t\tvar nilClientProxy clientproxy.ClientProxy // cannot return nil for struct\n\t\treturn nilClientProxy, errors.New(name + \" not found.\")\n\t}\n\treturn clientProxy, nil\n}", "func (vs *Variables) Variable(vn Variablename) Variable {\n\tv, ok := vs.m[vn]\n\tif !ok {\n\t\tv = Variable(len(vs.n))\n\t\tvs.m[vn] = v\n\t\tvs.n = append(vs.n, vn)\n\t}\n\treturn v\n}", "func (registry *Registry) Lookup(handle string) *task.Task {\n\t// TODO: Refactor the interface here to explicitly add an `ok`\n\t// return value (in the style of reading a map[...]...)\n\t// to differentiate a present nil value return vs. a\n\t// not-present-at-all value.\n\tregistry.lock.RLock()\n\tdefer registry.lock.RUnlock()\n\n\tif t, exists := registry.db[handle]; exists {\n\t\treturn t\n\t}\n\n\treturn nil\n}", "func (s *Scope) Get(name string) interface{} {\n\tif _, ok := s.store[name]; ok {\n\t\treturn s.store[name]\n\t}\n\n\tif s.parent != nil {\n\t\treturn s.parent.Get(name)\n\t}\n\n\treturn nil\n}", "func Lookup(name string) (*Mempool, error) {\n\tcname := C.CString(name)\n\tmp := (*Mempool)(C.rte_mempool_lookup(cname))\n\tC.free(unsafe.Pointer(cname))\n\tif mp == nil {\n\t\treturn nil, err()\n\t}\n\treturn mp, nil\n}", "func (s *Syscalls) Lookup(v interface{}) *Syscall {\n\tif s == nil {\n\t\treturn nil\n\t}\n\n\tswitch v := v.(type) {\n\tcase string:\n\t\t// we always preface syscalls with sys_, if it is not\n\t\t// there, for convience, we add it.\n\t\tif !strings.HasPrefix(v, \"sys_\") {\n\t\t\tv = \"sys_\" + v\n\t\t}\n\n\t\treturn s.name[v]\n\tcase uint32:\n\t\treturn s.nr[int(v)]\n\tcase int:\n\t\treturn s.nr[v]\n\t}\n\n\treturn nil\n}", "func Lookup(name string) *Flag {\n\treturn CommandLine.Lookup(name)\n}", "func (a *LocalActivation) Find(name string) *Local {\n\n\tcurrent := a\n\n\tfor current != nil {\n\n\t\tif current.entries != nil {\n\t\t\tresult, ok := current.entries[name]\n\t\t\tif ok {\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\n\t\tcurrent = current.Parent\n\t}\n\n\treturn nil\n}", "func (a *LocalActivations) Find(name string) *Local {\n\tcurrent := a.Current()\n\tif current == nil {\n\t\treturn nil\n\t}\n\treturn current.Find(name)\n}", "func (r *UIRegistry) Lookup(name string) (webutil.DataSource, error) {\n\n\tr.rwmu.RLock()\n\tdefer r.rwmu.RUnlock()\n\n\tif ret, ok := r.reg[name]; ok {\n\t\treturn ret.DataSource, nil\n\t}\n\n\treturn nil, ErrNotFound\n}", "func (p *Photon) GetVariable(name string) *Variable {\n\th, i := p.HasVariable(name)\n\tif !h {\n\t\treturn nil\n\t}\n\treturn p.Variables[i]\n}", "func (s *ConcurrentStateMachine) Lookup(query interface{}) (interface{}, error) {\n\treturn s.sm.Lookup(query)\n}", "func (s *RegularStateMachine) Lookup(query interface{}) (interface{}, error) {\n\treturn s.sm.Lookup(query)\n}", "func Lookup(ident string) Token {\n\tif tok, is_keyword := keywords[ident]; is_keyword {\n\t\treturn tok\n\t}\n\treturn IDENT\n}", "func LookupIdent(ident string) TokenType {\n\tif tok, ok := keywords[ident]; ok {\n\t\treturn tok\n\t}\n\tif ident[0] == '$' {\n\t\treturn VAR\n\t}\n\n\treturn IDENT\n}", "func (a *evalActivation) ResolveName(name string) (any, bool) {\n\tv, found := a.vars[name]\n\tif !found {\n\t\treturn nil, false\n\t}\n\tswitch obj := v.(type) {\n\tcase func() ref.Val:\n\t\tif resolved, found := a.lazyVars[name]; found {\n\t\t\treturn resolved, true\n\t\t}\n\t\tlazy := obj()\n\t\ta.lazyVars[name] = lazy\n\t\treturn lazy, true\n\tcase func() any:\n\t\tif resolved, found := a.lazyVars[name]; found {\n\t\t\treturn resolved, true\n\t\t}\n\t\tlazy := obj()\n\t\ta.lazyVars[name] = lazy\n\t\treturn lazy, true\n\tdefault:\n\t\treturn obj, true\n\t}\n}", "func (rp *Ringpop) Lookup(key string) string {\n\tstartTime := time.Now()\n\n\tdest, ok := rp.ring.Lookup(key)\n\n\trp.emit(LookupEvent{key, time.Now().Sub(startTime)})\n\n\tif !ok {\n\t\trp.log.WithField(\"key\", key).Warn(\"could not find destination for key\")\n\t\treturn rp.WhoAmI()\n\t}\n\n\treturn dest\n}", "func (a Address) Lookup(k string) (any, error) {\n\tswitch k {\n\tcase \"port\":\n\t\tt, err := net.ResolveTCPAddr(\"tcp\", a.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t.Port, nil\n\tcase \"ip\":\n\t\tt, err := net.ResolveTCPAddr(\"tcp\", a.String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn t.IP.String(), nil\n\t}\n\treturn nil, ErrKeyNotFound{Key: k}\n}", "func (x *Index) Lookup(query string) (match *LookupResult, alt *AltWords, illegal bool) {\n\tss := strings.Split(query, \".\", 0);\n\n\t// check query syntax\n\tfor _, s := range ss {\n\t\tif !isIdentifier(s) {\n\t\t\tillegal = true;\n\t\t\treturn;\n\t\t}\n\t}\n\n\tswitch len(ss) {\n\tcase 1:\n\t\tmatch, alt = x.LookupWord(ss[0])\n\n\tcase 2:\n\t\tpakname := ss[0];\n\t\tmatch, alt = x.LookupWord(ss[1]);\n\t\tif match != nil {\n\t\t\t// found a match - filter by package name\n\t\t\tdecls := match.Decls.filter(pakname);\n\t\t\tothers := match.Others.filter(pakname);\n\t\t\tmatch = &LookupResult{decls, others};\n\t\t}\n\n\tdefault:\n\t\tillegal = true\n\t}\n\n\treturn;\n}", "func (k *Kubernetes) Lookup(ctx context.Context, state request.Request, name string, typ uint16) (*dns.Msg, error) {\n\treturn k.Upstream.Lookup(ctx, state, name, typ)\n}", "func (f *FlagSet) lookup(name NormalizedName) *Flag {\n\treturn f.formal[name]\n}", "func Lookup(ident string) Token {\n\tif tok, ok := keywords[strings.ToLower(ident)]; ok {\n\t\treturn tok\n\t}\n\treturn IDENT\n}", "func Lookup(ident string) Token {\n\tif tok, ok := keywords[strings.ToLower(ident)]; ok {\n\t\treturn tok\n\t}\n\treturn IDENT\n}", "func (r *Registry) Lookup(name string) (uint16, []string, error) {\n\n\tr.RLock()\n\tsvc, ok := r.byname[name]\n\tr.RUnlock()\n\n\tif !ok {\n\t\treturn 0, nil, fmt.Errorf(\"Name %q not found in the port registry\", name)\n\t}\n\n\treturn svc.port, svc.addr, nil\n}", "func (r *Resolver) Declare(name *Token) {\n\t// don't check global scope.\n\tif r.scopes.Empty() {\n\t\treturn\n\t}\n\n\tscope := r.scopes.Peek()\n\n\tif exists := scope[name.Lexeme]; exists == varDeclared || exists == varDefined {\n\t\tpanic(NewLoxError(name, \"variable redeclared.\"))\n\t}\n\n\tscope[name.Lexeme] = varDeclared\n}", "func (*UnresolvedName) Variable() {}", "func (dir HgmDir) Lookup(ctx context.Context, name string) (fs.Node, error) {\n\tlocalDirent := dir.localDir + name // dirs are ending with a slash -> just append the name\n\ta := fuse.Attr{}\n\td := HgmDir{hgmFs: dir.hgmFs, localDir: localDirent}\n\terr := d.Attr(ctx, &a)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif (a.Mode & os.ModeType) == os.ModeDir {\n\t\treturn HgmDir{hgmFs: dir.hgmFs, localDir: localDirent + \"/\"}, nil\n\t}\n\n\treturn &HgmFile{hgmFs: dir.hgmFs, localFile: localDirent, fileSize: a.Size}, nil\n}", "func (p *scopeParser) getLocalVar(name *tree.Token) *Variable {\n\tfor scope := p.currentScope; scope != nil; scope = scope.Parent {\n\t\t// Iterate in reverse order to handle shadowing correctly.\n\t\tfor i := len(scope.Variables) - 1; i >= 0; i-- {\n\t\t\tif scope.Variables[i].Name == string(name.Bytes) {\n\t\t\t\treturn scope.Variables[i]\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func (s *devNull) Lookup(key string) (interface{}, bool) {\n\treturn nil, false\n}", "func (app *frame) Fetch(name string) (computable.Value, error) {\n\tif app.isStopped {\n\t\treturn nil, nil\n\t}\n\n\tif val, ok := app.variables[name]; ok {\n\t\treturn val, nil\n\t}\n\n\tstr := fmt.Sprintf(\"the variable (name: %s) is not defined\", name)\n\treturn nil, errors.New(str)\n}", "func (p *variables) Var(name string) interface{} {\n\n\tif k, ok := p.symtbl[name]; ok {\n\t\treturn p.vars[k]\n\t}\n\treturn qlang.Undefined\n}", "func (r *ring) Lookup(\n\tkey string,\n) (HostInfo, error) {\n\taddr, found := r.ring().Lookup(key)\n\tif !found {\n\t\tselect {\n\t\tcase r.refreshChan <- &ChangedEvent{}:\n\t\tdefault:\n\t\t}\n\t\treturn HostInfo{}, ErrInsufficientHosts\n\t}\n\tr.members.RLock()\n\tdefer r.members.RUnlock()\n\thost, ok := r.members.keys[addr]\n\tif !ok {\n\t\treturn HostInfo{}, fmt.Errorf(\"host not found in member keys, host: %q\", addr)\n\t}\n\treturn host, nil\n}", "func (env *Environment) FindSymbol(name string, inherit bool) *Symbol {\n\tvar sym *Symbol\n\tvar ok bool\n\tfor env != nil {\n\t\tsym, ok = env.dict[name]\n\t\tif ok {\n\t\t\treturn sym\n\t\t}\n\t\tif inherit {\n\t\t\tenv = env.parent\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (local *Node) Lookup(key string) (nodes []RemoteNode, err error) {\n\t// TODO: students should implement this\n\treturn\n}", "func (e *Environment) Get(name token.Token, index int) (interface{}, error) {\n\tif index == -1 {\n\t\tv, prs := e.values[name.Lexeme]\n\t\tif prs {\n\t\t\tif v == needsInitialization {\n\t\t\t\treturn nil, runtimeerror.Make(name, fmt.Sprintf(\"Uninitialized variable access: '%s'\", name.Lexeme))\n\t\t\t}\n\t\t\treturn v, nil\n\t\t}\n\t\tif e.enclosing != nil {\n\t\t\treturn e.enclosing.Get(name, index)\n\t\t}\n\t\treturn nil, runtimeerror.Make(name, fmt.Sprintf(\"Undefined variable '%v'\", name.Lexeme))\n\t}\n\treturn e.indexedValues[index], nil\n}", "func (a *AddressBook) Lookup(addr string) string {\n\ta.mu.Lock()\n\tdefer a.mu.Unlock()\n\talias, ok := a.ledger[addr]\n\tif !ok {\n\t\tb, err := a.lookupMyTezosBaker(addr)\n\t\tif err != nil || b.BakerName == \"\" {\n\t\t\treturn addr\n\t\t}\n\t\ta.ledger[addr] = b.BakerName\n\t\talias = b.BakerName\n\t}\n\treturn alias\n}", "func (m *varMap) Get(s string) (Variable, bool) {\n\tv, ok := m.vars[s]\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn v, true\n}", "func FindScope(scope string) *Scope {\n\tlock.RLock()\n\tdefer lock.RUnlock()\n\n\ts := scopes[scope]\n\treturn s\n}", "func (server Server) Lookup(name string) interface{} {\n\tparams := make([]interface{}, 1)\n\tparams[0] = name\n\trequest := utils.Request{Op: \"Lookup\", Params: params}\n\tinvocation := utils.Invocation{Host: server.IP, Port: server.Port, Request: request}\n\treqstor := requestor.Requestor{}\n\t// getting the reply\n\treply := reqstor.Invoke(invocation).([]interface{})\n\tif reply[1] != nil {\n\t\terr := reply[1].(error)\n\t\tutils.PrintError(err, \"unable to lookup on naming proxy\")\n\t}\n\treplyMap := reply[0].(map[string]interface{})\n\tclientProxy := clientproxy.InitClientProxy(replyMap[\"Host\"].(string), int(replyMap[\"Port\"].(float64)), int(replyMap[\"ID\"].(float64)), replyMap[\"TypeName\"].(string))\n\n\t// get the result\n\tvar result interface{}\n\tswitch clientProxy.TypeName {\n\tcase \"Echo\":\n\t\tresult = EchoProxy{Host: clientProxy.Host, Port: clientProxy.Port, ID: clientProxy.ID}\n\tdefault:\n\t\tutils.PrintError(errors.New(\"type unrecognized\"), \"type of clientproxy: \" + clientProxy.TypeName)\n\t}\n\treturn result\n}", "func (chain *DataTypeChain) Lookup(lookup map[string]DataType) *DataTypeChain {\n\tif chain.strval != nil {\n\t\tkey := *chain.strval\n\t\tvar val *DataType\n\t\tif v, ok := lookup[key]; ok {\n\t\t\tval = &v\n\t\t} else if v, ok := lookup[strings.ToLower(key)]; ok {\n\t\t\tval = &v\n\t\t}\n\t\tif val != nil {\n\t\t\tchain.value = val\n\t\t\tchain.afterSetValue()\n\t\t}\n\t}\n\treturn chain\n}", "func (n *node) Lookup(ctx context.Context, req *fuse.LookupRequest, resp *fuse.LookupResponse) (fs.Node, error) {\n\tvar requested string = req.Name\n\tp, nm := n.Path(), n.Name()\n\tfp, _ := filepath.Abs(filepath.Join(p, \"/\", nm))\n\ttail := n.Tail()\n\tif len(tail) > 0 {\n\t\tfor _, nn := range tail {\n\t\t\tif nn.Aliased() {\n\t\t\t\tif exists, ad := nn.Find(requested, n, nn); exists {\n\t\t\t\t\tswitch ad.Is() {\n\t\t\t\t\tcase Directory:\n\t\t\t\t\t\tad.SetPath(fp)\n\t\t\t\t\t\treturn ad, nil\n\t\t\t\t\tcase File, Fileio:\n\t\t\t\t\t\taf := NewNodeFile(ad)\n\t\t\t\t\t\taf.InitializeFile(fp, n)\n\t\t\t\t\t\treturn af, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif nn.Name() == requested {\n\t\t\t\tswitch nn.Is() {\n\t\t\t\tcase Directory:\n\t\t\t\t\tnn.InitializeDir(fp, n)\n\t\t\t\t\treturn nn, nil\n\t\t\t\tcase File, Fileio, Socket:\n\t\t\t\t\tf := NewNodeFile(nn)\n\t\t\t\t\tf.InitializeFile(fp, n)\n\t\t\t\t\treturn f, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, fuse.ENOENT\n}", "func (p *Plugin) GetVariable(name string) (value string) {\n\tsymVal, err := p.plug.Lookup(name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn\n\t}\n\n\tvaluepointer, ok := symVal.(*string)\n\tif !ok {\n\t\tlog.Fatal(\"Could not cast value of variable \", name)\n\t}\n\n\treturn *valuepointer\n}", "func (d *litMapping) VariableOf(m z.Lit) Variable {\n\ti, ok := d.variables[m]\n\tif ok {\n\t\treturn i\n\t}\n\td.errs = append(d.errs, fmt.Errorf(\"no variable corresponding to %s\", m))\n\treturn zeroVariable{}\n}", "func (vm *ValueMap) LookupParent(name string) llvm.Value {\n\tif v, ok := vm.vmap[name]; ok {\n\t\treturn v\n\t}\n\treturn vm.parent.LookupParent(name)\n}", "func (s *subtasks) Lookup(ctx context.Context, dir *fs.Inode, p string) (*fs.Dirent, error) {\n\ttid, err := strconv.ParseUint(p, 10, 32)\n\tif err != nil {\n\t\treturn nil, syserror.ENOENT\n\t}\n\n\ttask := s.pidns.TaskWithID(kernel.ThreadID(tid))\n\tif task == nil {\n\t\treturn nil, syserror.ENOENT\n\t}\n\tif task.ThreadGroup() != s.t.ThreadGroup() {\n\t\treturn nil, syserror.ENOENT\n\t}\n\n\ttd := newTaskDir(task, dir.MountSource, s.pidns, false)\n\treturn fs.NewDirent(td, p), nil\n}", "func varLookup(context interface{}, cmd, variable string, vars map[string]string, results map[string]interface{}) (interface{}, error) {\n\n\t// {\"field\": \"#cmd:variable\"}\n\t// Before: {\"field\": \"#number:variable_name\"} \t\tAfter: {\"field\": 1234}\n\t// Before: {\"field\": \"#string:variable_name\"} \t\tAfter: {\"field\": \"value\"}\n\t// Before: {\"field\": \"#date:variable_name\"} \t\tAfter: {\"field\": time.Time}\n\t// Before: {\"field\": \"#objid:variable_name\"} \t\tAfter: {\"field\": mgo.ObjectId}\n\t// Before: {\"field\": \"#regex:/pattern/<options>\"} After: {\"field\": bson.RegEx}\n\t// Before: {\"field\": \"#since:3600\"} \t\t\t\tAfter: {\"field\": time.Time}\n\t// Before: {\"field\": \"#data.0:doc.station_id\"} \tAfter: {\"field\": \"23453\"}\n\n\t// If the variable does not exist, use the variable straight up.\n\tparam, exists := vars[variable]\n\tif !exists {\n\t\tparam = variable\n\t}\n\n\t// Do we have a command that is not known.\n\tif len(cmd) < 4 {\n\t\terr := fmt.Errorf(\"Unknown command %q\", cmd)\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd is proper length\")\n\t\treturn nil, err\n\t}\n\n\t// Let's perform the right action per command.\n\tswitch cmd[0:4] {\n\tcase \"numb\":\n\t\treturn number(context, param)\n\n\tcase \"stri\":\n\t\treturn param, nil\n\n\tcase \"date\":\n\t\treturn isoDate(context, param)\n\n\tcase \"obji\":\n\t\treturn objID(context, param)\n\n\tcase \"rege\":\n\t\treturn regExp(context, param)\n\n\tcase \"time\":\n\t\treturn adjTime(context, param)\n\n\tcase \"data\":\n\t\tif len(cmd) == 6 {\n\t\t\treturn dataLookup(context, cmd[5:6], param, results)\n\t\t}\n\n\t\terr := errors.New(\"Data command is missing the operator\")\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd is data\")\n\t\treturn nil, err\n\n\tdefault:\n\t\terr := fmt.Errorf(\"Unknown command %q\", cmd)\n\t\tlog.Error(context, \"varLookup\", err, \"Checking cmd in default case\")\n\t\treturn nil, err\n\t}\n}", "func (c *Context) LookupByName(zson string) (zng.Type, error) {\n\tc.mu.Lock()\n\tdefer c.mu.Unlock()\n\ttyp, ok := c.toType[zson]\n\tif ok {\n\t\treturn typ, nil\n\t}\n\tif typ := zng.LookupPrimitive(zson); typ != nil {\n\t\tc.toBytes[typ] = zcode.Bytes(zson)\n\t\tc.toType[zson] = typ\n\t\treturn typ, nil\n\t}\n\t// ParseType will re-enter the context and create and/or\n\t// return an existing type. Since it's re-entrant we can't\n\t// (and don't want to) hold the lock. There can be a race\n\t// here but it doesn't matter because there is only ever one\n\t// type that wins the day because of the incremental locking on\n\t// each component of a nested type.\n\tc.mu.Unlock()\n\ttyp, err := ParseType(c, zson)\n\tc.mu.Lock()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// ParseType will ensure the canonical zson is in the toType table,\n\t// but the zson argument here may be any conforming zson type string.\n\t// Since this string may appear repeatedly (e.g., type values\n\t// coming from an external system) we put an extra entry in the\n\t// lookup-table to cache it so we don't parse every instance\n\t// of a type string when it is not in canonical form.\n\tc.toType[zson] = typ\n\treturn typ, nil\n}", "func LookupShadow(name string) (*Shadow, error) {\n\tentries, err := LookupInShadow(S_NAME, name, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn entries[0], err\n}", "func execmScopeLookup(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Scope).Lookup(args[1].(string))\n\tp.Ret(2, ret)\n}", "func LoadVariable(name string) {\n\toutput.EmitLn(\"MOVE \" + name + \"(PC),D0\")\n}", "func (e *Environment) Get(s data.Symbol) *Environment {\n\tif _, ok := e.vars[s]; ok {\n\t\treturn e\n\t}\n\treturn e.outer.Get(s)\n}", "func (r *resolver) lookupNamed(s *scope, a ast.TemplatedName) (sem.Named, error) {\n\ttarget := s.lookup(a.Name)\n\tif target == nil {\n\t\treturn nil, fmt.Errorf(\"%v cannot resolve '%v'\", a.Source, a.Name)\n\t}\n\n\t// Something with the given name was found...\n\tvar params []sem.TemplateParam\n\tvar ty sem.ResolvableType\n\tswitch target := target.object.(type) {\n\tcase *sem.Type:\n\t\tty = target\n\t\tparams = target.TemplateParams\n\tcase *sem.TypeMatcher:\n\t\tty = target\n\t\tparams = target.TemplateParams\n\tcase sem.TemplateParam:\n\t\tif len(a.TemplateArgs) != 0 {\n\t\t\treturn nil, fmt.Errorf(\"%v '%v' template parameters do not accept template arguments\", a.Source, a.Name)\n\t\t}\n\t\treturn target.(sem.Named), nil\n\tcase sem.Named:\n\t\treturn target, nil\n\tdefault:\n\t\tpanic(fmt.Errorf(\"unknown resolved type %T\", target))\n\t}\n\t// ... and that something takes template parameters\n\t// Check the number of templated name template arguments match the number of\n\t// templated parameters for the target.\n\targs := a.TemplateArgs\n\tif len(params) != len(args) {\n\t\treturn nil, fmt.Errorf(\"%v '%v' requires %d template arguments, but %d were provided\", a.Source, a.Name, len(params), len(args))\n\t}\n\n\t// Check templated name template argument kinds match the parameter kinds\n\tfor i, ast := range args {\n\t\tparam := params[i]\n\t\targ, err := r.lookupNamed(s, args[i])\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := checkCompatible(arg, param); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v %w\", ast.Source, err)\n\t\t}\n\t}\n\treturn ty, nil\n}", "func Get(name string) interface{} {\n\tinitialize()\n\tlock.RLock()\n\tvalue := notGlobals[name]\n\tlock.RUnlock()\n\treturn value\n}", "func (e entry) lookup(name interface{}) (interface{}, bool) {\n\tif res, ok := e[name]; ok {\n\t\treturn res, true\n\t}\n\treturn nil, false\n}", "func (inst *hiddenInstance) Lookup(path ...string) Value {\n\treturn inst.value().Lookup(path...)\n}" ]
[ "0.7097113", "0.69739264", "0.69543236", "0.65873414", "0.6419657", "0.6348857", "0.6331056", "0.6252857", "0.6228425", "0.61692935", "0.61272496", "0.6119282", "0.60879004", "0.607217", "0.6057717", "0.60500133", "0.6026041", "0.5932639", "0.5892493", "0.5862601", "0.58510864", "0.58280957", "0.5787756", "0.57868826", "0.5772443", "0.57413465", "0.57259405", "0.57189745", "0.5711137", "0.56995255", "0.56983656", "0.5684904", "0.5676966", "0.56669444", "0.56545395", "0.56434256", "0.5633822", "0.5609366", "0.55757165", "0.5551733", "0.5542061", "0.5524674", "0.55196255", "0.5519326", "0.54878974", "0.54878294", "0.54863805", "0.54712176", "0.5467557", "0.5445181", "0.5444145", "0.5420616", "0.5407645", "0.54036134", "0.53988194", "0.53965884", "0.5381786", "0.53655666", "0.53564703", "0.5348794", "0.531612", "0.53135103", "0.5296227", "0.5278446", "0.5256883", "0.5234694", "0.523205", "0.523205", "0.5231659", "0.52295625", "0.5210178", "0.51921743", "0.51917946", "0.51876235", "0.5180926", "0.51769924", "0.51642025", "0.51371354", "0.51362896", "0.51302356", "0.5125271", "0.5117272", "0.5105046", "0.5075269", "0.507168", "0.5063157", "0.5061393", "0.50529534", "0.50422674", "0.504137", "0.503977", "0.50349337", "0.50333047", "0.50122154", "0.5010162", "0.5007299", "0.50048614", "0.50018907", "0.49973673", "0.4995483" ]
0.8384056
0
Insert creates a new Variable at the top scope and returns it. If the Variable already exists in that scope, the existing Variable is returned.
func (s *scope) Insert(name string) Variable { l := len(s.levels) v, ok := s.levels[l-1].named[name] if ok { return v } v = Variable(s.len()) s.levels[l-1].named[name] = v s.maxLen++ return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (app *frame) Insert(vr var_variable.Variable) error {\n\tif app.isStopped {\n\t\treturn nil\n\t}\n\n\tname := vr.Name()\n\tif _, ok := app.variables[name]; ok {\n\t\tstr := fmt.Sprintf(\"variable: the name variable (%s) is already defined\", name)\n\t\treturn errors.New(str)\n\t}\n\n\treturn app.save(vr)\n}", "func (app *registry) Insert(name string, val computable.Value) error {\n\tif _, ok := app.variables[name]; ok {\n\t\tstr := fmt.Sprintf(\"the variable (name: %s) is already declared in the registry\", name)\n\t\treturn errors.New(str)\n\t}\n\n\tapp.variables[name] = val\n\treturn nil\n}", "func (scope *Scope) Put(identifier string, variable Variable) {\n\tscope.initialize()\n\tscope.variables[identifier] = variable\n}", "func execmScopeInsert(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := args[0].(*types.Scope).Insert(args[1].(types.Object))\n\tp.Ret(2, ret)\n}", "func (g *GitToken) Insert() (int64, error) {\n\treturn Engine.Insert(g)\n}", "func (db Database) InsertPlacement() Placement {\n\tresult := Placement{ID: db.nextID()}\n\tdb.insert(result)\n\treturn result\n}", "func (t *Treap) Insert(value string) {\n\trand.Seed(time.Now().UnixNano())\n\tt.root = insert(t.root, value,\n\t\trand.Int63n(maxPriority-minPriority)+minPriority)\n}", "func (s *scope) Lookup(name string) Variable {\n\tl := len(s.levels)\n\tfor i := l - 1; i >= 0; i-- {\n\t\tif v, ok := s.levels[i].named[name]; ok {\n\t\t\treturn v\n\t\t}\n\t}\n\tv := Variable(s.maxLen)\n\ts.levels[0].named[name] = v\n\ts.maxLen++\n\treturn v\n}", "func (g *GlobalVar) FirstOrCreate() error {\n\t_, err := GetGlobalVar()\n\tif err == ErrRecordNotFound {\n\t\treturn DB.Create(g).Error\n\t}\n\treturn nil\n}", "func (t *Tree) Insert (value, data string) error {\n\tif t.Root == nil {\n\t\tt.Root = &Node{Value: value, Data: data}\n\t\treturn nil\n\t}\n\treturn t.Root.Insert(value, data)\t// this may throw error\n}", "func (r *RGASS) LocalInsert(tarID ID, pos int, str string, id ID) error {\n\ttarNode, ok := r.Model.Get(tarID)\n\n\tif !ok {\n\t\treturn errors.New(\"Node not found\")\n\t}\n\n\treturn r.doInsert(tarNode, pos, str, id)\n}", "func (m HMSketch) Insert(kvs map[string]string, value, count float64) HMSketch {\n\tm = m.insert(map[string]string{\"__global__\": \"__global__\"}, value, count)\n\tm = m.insert(kvs, value, count)\n\treturn m\n}", "func (bst *BST) Insert(val interface{}) *Node {\n\treturn InsertItem(bst, val)\n}", "func (scope *Scope) Get(identifier string) Variable {\n\tscope.initialize()\n\tvariable, contains := scope.variables[identifier]\n\tif !contains && scope.previous != nil {\n\t\treturn scope.previous.Get(identifier)\n\t}\n\treturn variable\n}", "func (t *TST) Insert(s string, val interface{}) bool {\n\tif !t.Find(s) {\n\t\tt.Size++\n\t}\n\treturn t.root.rinsert(s, val) != nil\n}", "func (s *Storage) Insert(ctx context.Context, ID string, g graph.Graph) error {\n\tif err := ctx.Err(); err != nil {\n\t\treturn err\n\t}\n\ts.mu.Lock()\n\ts.dataStorage.Insert(ID, g)\n\ts.dataStack.Push(ID)\n\ts.lgr.Infof(\"graph with ID %s was, stack length %d, storage length %d\", ID, s.dataStorage.Len(), s.dataStack.Len())\n\ts.mu.Unlock()\n\treturn nil\n}", "func (nfr *nfRules) Insert(rule *Rule) (uint32, error) {\n\treturn nfr.create(rule, operationInsert)\n}", "func (p *Project) Insert(session *xorm.Session) (int, error) {\n\taffected, err := session.Insert(p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn 0, err\n\t}\n\treturn int(affected), nil\n}", "func (s *scope) Push() {\n\tlevel := &scopeLevel{map[string]Variable{}, map[Variable]Value{}}\n\ts.levels = append(s.levels, level)\n}", "func (vs *Variables) Variable(vn Variablename) Variable {\n\tv, ok := vs.m[vn]\n\tif !ok {\n\t\tv = Variable(len(vs.n))\n\t\tvs.m[vn] = v\n\t\tvs.n = append(vs.n, vn)\n\t}\n\treturn v\n}", "func (t *Tree) Insert(key interface{}, value interface{}, issmaller Comparable) (new *TreeNode, err error) {\n\tif t == nil {\n\t\treturn nil, errors.Errorf(\"unable to insert into nil tree\")\n\t}\n\tt.lock.Lock()\n\tdefer t.lock.Unlock()\n\tt.root, new = t.root.insert(key, value, issmaller)\n\tt.Count++\n\treturn new, nil\n}", "func (standardLibrary *StandardLibrary) PushFixture() slimentity.SlimEntity {\n\tcurrentFixture := standardLibrary.GetFixture()\n\tnewFixture := standardLibrary.CloneSymbol(currentFixture)\n\tstandardLibrary.actors.Push(currentFixture)\n\treturn standardLibrary.objects.Set(scriptTableActorName, newFixture)\n}", "func (fo *stubFooService) Insert(ctx context.Context, s string) (res string, err error) {\n\tvalue := fmt.Sprintf(\"%s bar\", s)\n\tnid, _ := fo.idpNano.ID()\n\n\t_, err = fo.repo.Insert(ctx, model.Foo{ID: nid, Value: value})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn value, err\n}", "func (s *SnippetStore) Insert(title, content string, expires int) (int, error) {\n\treturn 2, nil\n}", "func (tree *Tree) Insert(value int) {\n\ttree.root, _ = tree.root.Insert(value)\n}", "func (f *FunctionTable) Insert(pDef *FuncDef) {\n\tf[strings.ToLower(pDef.Name)] = pDef\n}", "func (p *PriorityQueue) Insert(v interface{}, priority float64) {\n\t_, ok := p.lookup[v]\n\tif ok {\n\t\treturn\n\t}\n\n\tnewItem := &item{\n\t\tvalue: v,\n\t\tpriority: priority,\n\t}\n\theap.Push(p.itemHeap, newItem)\n\tp.lookup[v] = newItem\n}", "func (b *Block) Insert() error {\n\treturn b.storage.Insert(b)\n}", "func (t *T) Insert(s string, v interface{}) {\n\tt.root = insert(t.root, nil, s, t, v)\n}", "func (s *Scope) Declare(decl DeclType, name []byte) (*Var, bool) {\n\t// refer to new variable for previously undeclared symbols in the current and lower scopes\n\t// this happens in `{ a = 5; } var a` where both a's refer to the same variable\n\tcurScope := s\n\tif decl == VariableDecl || decl == FunctionDecl {\n\t\t// find function scope for var and function declarations\n\t\ts = s.Func\n\t}\n\n\tif v := s.findDeclared(name); v != nil {\n\t\t// variable already declared, might be an error or a duplicate declaration\n\t\tif (v.Decl == LexicalDecl || decl == LexicalDecl) && v.Decl != ExprDecl {\n\t\t\t// redeclaration of let, const, class on an already declared name is an error, except if the declared name is a function expression name\n\t\t\treturn nil, false\n\t\t}\n\t\tif v.Decl == ExprDecl {\n\t\t\tv.Decl = decl\n\t\t}\n\t\tv.Uses++\n\t\tif s != curScope {\n\t\t\tcurScope.Undeclared = append(curScope.Undeclared, v) // add variable declaration as used variable to the current scope\n\t\t}\n\t\treturn v, true\n\t}\n\n\tvar v *Var\n\t// reuse variable if previously used, as in: a;var a\n\tif decl != ArgumentDecl { // in case of function f(a=b,b), where the first b is different from the second\n\t\tfor i, uv := range s.Undeclared[s.NumArguments:] {\n\t\t\t// no need to evaluate v.Link as v.Data stays the same and Link is nil in the active scope\n\t\t\tif 0 < uv.Uses && bytes.Equal(name, uv.Data) {\n\t\t\t\tv = uv\n\t\t\t\ts.Undeclared = append(s.Undeclared[:int(s.NumArguments)+i], s.Undeclared[int(s.NumArguments)+i+1:]...)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tif v == nil {\n\t\t// add variable to the context list and to the scope\n\t\tv = &Var{decl, name, nil, 0}\n\t} else {\n\t\tv.Decl = decl\n\t}\n\tv.Uses++\n\ts.Declared = append(s.Declared, v)\n\tif s != curScope {\n\t\tcurScope.Undeclared = append(curScope.Undeclared, v) // add variable declaration as used variable to the current scope\n\t}\n\treturn v, true\n}", "func (s *Slab) Insert(val interface{}) int {\n\tkey := s.next\n\ts.insertAt(key, val)\n\treturn key\n}", "func (s *Action) Insert(c *cli.Context) error {\n\tctx := ctxutil.WithGlobalFlags(c)\n\techo := c.Bool(\"echo\")\n\tmultiline := c.Bool(\"multiline\")\n\tforce := c.Bool(\"force\")\n\tappending := c.Bool(\"append\")\n\n\targs, kvps := parseArgs(c)\n\tname := args.Get(0)\n\tkey := args.Get(1)\n\n\tif name == \"\" {\n\t\treturn exit.Error(exit.NoName, nil, \"Usage: %s insert name\", s.Name)\n\t}\n\n\treturn s.insert(ctx, c, name, key, echo, multiline, force, appending, kvps)\n}", "func (ds *KVStorage) Insert(ID string, g graph.Graph) {\n\tds.data[ID] = g\n}", "func (d Database) Insert(key string, value string) error {\n\tif d.connection == nil {\n\t\treturn errors.New(\"connection not initialized\")\n\t}\n\t_, err := d.connection.Set(d.ctx, key, value, 0).Result()\n\treturn err\n}", "func (c *Cuckoo) Insert(key Key, val Value) (ok bool) {\n\tok, _ = c.insert(key, val, c.StartLevel)\n\treturn\n}", "func (m RedisCache) Insert(key string, val *string, ttl int) {\n\terr := m.Rdb.Set(ctx, key, *val, time.Duration(ttl)*time.Minute).Err()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (t *Tree) Insert(v interface{}) {\n\tvar flags Flags\n\tif t.root, flags = t.root.insert(v, t.lessFunc); flags&FLAGS_IS_INSERTED != FLAGS_NONE {\n\t\tt.len++\n\t}\n}", "func (data *SimpleDbType) Insert(dbMgr *mgr.DBConn) error {\n\tdb := dbMgr.Open()\n\n\tsqlStatement := `INSERT INTO test_table (\"name\", \"number\") VALUES ($1, $2) RETURNING id`\n\tid := 0\n\terr := db.QueryRow(sqlStatement, data.Name, data.Number).Scan(&id)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Println(\"New record ID is:\", id)\n\tdbMgr.Close()\n\treturn err\n}", "func insertAudit(db gorp.SqlExecutor, pva *sdk.ProjectVariableAudit) error {\n\tdbProjVarAudit := dbProjectVariableAudit(*pva)\n\tif err := db.Insert(&dbProjVarAudit); err != nil {\n\t\treturn sdk.WrapError(err, \"Cannot insert audit for variable %d\", pva.VariableID)\n\t}\n\t*pva = sdk.ProjectVariableAudit(dbProjVarAudit)\n\treturn nil\n}", "func (m *store) Insert(w ukjent.Word) error {\n\tgot, err := m.get(w.Word)\n\tif err == nil {\n\t\treturn base.TranslationExists(got.Word, got.Translation)\n\t}\n\n\tdefer m.withWrite()()\n\tm.data[w.Word] = entry{w.Translation, w.Note}\n\treturn nil\n}", "func (pg *PGStorage) Insert(a *Address) error {\n\tvar err error\n\terr = pg.con.QueryRow(`\n\t\tINSERT INTO address(hash, income, outcome, ballance)\n\t\tvalues($1, $2, $3, $4)\n\t\tRETURNING ID`,\n\t\ta.Hash,\n\t\ta.Income,\n\t\ta.Outcome,\n\t\ta.Ballance).Scan(\n\t\t&a.ID)\n\treturn err\n}", "func (bst *BinarySearchTree) Insert(val int) error {\n\tbst.mu.Lock()\n\tdefer bst.mu.Unlock()\n\n\tinsert := NewNode(val)\n\tif bst.root == nil {\n\t\tbst.root = insert\n\t\treturn nil\n\t} else {\n\t\treturn traverseAndInsert(bst.root, insert)\n\t}\n}", "func (g *Graph) insertNode() *Node {\n\tn := &Node{\n\t\tID: atomic.AddUint64(&g.topNodeID, 1),\n\t\tcircularRelationship: g.circularRelationship,\n\t}\n\n\tg.Nodes[n.ID] = n\n\n\treturn n\n}", "func (s *InstanceBindData) Insert(ibd *internal.InstanceBindData) error {\n\tif ibd == nil {\n\t\treturn errors.New(\"entity may not be nil\")\n\t}\n\n\tif ibd.InstanceID.IsZero() {\n\t\treturn errors.New(\"instance id must be set\")\n\t}\n\n\topKey := s.key(ibd.InstanceID)\n\n\trespGet, err := s.kv.Get(context.TODO(), opKey)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while calling database on get\")\n\t}\n\tif respGet.Count > 0 {\n\t\treturn alreadyExistsError{}\n\t}\n\n\tdso, err := s.encodeDMToDSO(ibd)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif _, err := s.kv.Put(context.TODO(), opKey, dso); err != nil {\n\t\treturn errors.Wrap(err, \"while calling database on put\")\n\t}\n\n\treturn nil\n}", "func (t *BinarySearchTree) Insert(v interface{}) {\n\n}", "func (ref Ref) Insert(x *Term, pos int) Ref {\n\tswitch {\n\tcase pos == len(ref):\n\t\treturn ref.Append(x)\n\tcase pos > len(ref)+1:\n\t\tpanic(\"illegal index\")\n\t}\n\tcpy := make(Ref, len(ref)+1)\n\tcopy(cpy, ref[:pos])\n\tcpy[pos] = x\n\tcopy(cpy[pos+1:], ref[pos:])\n\treturn cpy\n}", "func Insert(writer http.ResponseWriter, request *http.Request) {\n\tvar sp SanPham\n\tsp.TenSanPham = request.FormValue(\"TenSanPham\")\n\tvar Gia int\n\tfmt.Sscanf(request.FormValue(\"Gia\"), \"%d\", &Gia)\n\tsp.Gia = Gia\n\n\tcreate(sp)\n\tvar listSP []SanPham\n\tlistSP = getAll()\n\ttemplate_html.ExecuteTemplate(writer, \"Home\", listSP)\n}", "func (self Accessor) Insert(expr ...interface{}) *InsertManager {\n\treturn Insertion(self.Relation()).Insert(expr...)\n}", "func (vars Variables) Lookup(n *scparse.VariableNode) (interface{}, bool) {\n\tv := vars.lookup(n)\n\tif !v.IsValid() {\n\t\treturn nil, false\n\t}\n\treturn v.Interface(), true\n}", "func (m *MongoStore) Insert(kitten Kitten) int {\n\ts := m.session.Clone()\n\tdefer s.Close()\n\tm.Lock()\n\ti := m.nextid()\n\tm.Unlock()\n\tkitten.Id = i\n\ts.DB(\"kittenserver\").C(\"kittens\").Insert(kitten)\n\treturn i\n}", "func (n *Node) Insert(value int) *Node {\n\tif n.leaves == nil {\n\t\tn.leaves = make([]*Node, 0)\n\t}\n\n\tnewNode := new(Node)\n\tnewNode.Value = value\n\tn.leaves = append(n.leaves, newNode)\n\n\treturn n\n}", "func (r *repository) Insert(rec *Record) (int, error) {\n\tq := \"INSERT INTO records (name) VALUES ($1) RETURNING id;\"\n\n\tvar id int\n\tif err := r.db.QueryRow(q, rec.name).Scan(&id); err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn id, nil\n}", "func (t *Tree) Insert(val int) {\n\tt.Root.insert(val)\n}", "func (tree *Tree) Insert(key int, value string) {\n\ttree.Root = tree.Root.insert(key, value)\n}", "func (this *Trie) Insert(word string) {\n for _,v := range word{\n if this.name[v-'a'] == nil{\n this.name[v-'a'] = new(Trie)\n fmt.Println(this.name)\n }\n this = this.name[v-'a']\n \n }\n \n this.isWord = true\n}", "func (tree *Tree) naiveInsert(value interface{}) *Node {\n\tvar inserted *Node\n\n\troot := tree.Root\n\tif root == nil {\n\t\tinserted = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority)}\n\t\ttree.Root = inserted\n\t}\n\n\tfor inserted == nil {\n\t\tif compare(value, root.Value) < 0 {\n\t\t\tif root.Left == nil {\n\t\t\t\troot.Left = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority), Parent: root}\n\t\t\t\tinserted = root.Left\n\t\t\t} else {\n\t\t\t\troot = root.Left\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Duplicate values placed on the right\n\t\t\tif root.Right == nil {\n\t\t\t\troot.Right = &Node{Value: value, Priority: tree.rnd.Intn(maxPriority), Parent: root}\n\t\t\t\tinserted = root.Right\n\t\t\t} else {\n\t\t\t\troot = root.Right\n\t\t\t}\n\t\t}\n\t}\n\treturn inserted\n}", "func (s *SkipList) Insert(key Comparable) bool {\n\t_, created, _ := s.findOrCreate(key, true)\n\treturn created\n}", "func (v *Value) insert(params ...interface{}) (interface{}, error) {\n\tif len(params) != 2 {\n\t\treturn nil, newParamLenErr(len(params), 2)\n\t}\n\n\tvar (\n\t\tok bool\n\t\tkey string\n\t\tvalue string\n\t)\n\n\tkey, ok = params[0].(string)\n\tif !ok {\n\t\treturn nil, newParamTypeErr(params[0], key)\n\t}\n\n\tvalue, ok = params[1].(string)\n\tif !ok {\n\t\treturn nil, newParamTypeErr(params[1], value)\n\t}\n\n\t(*v)[key] = value\n\treturn key, nil\n}", "func (session *Session) Insert(beans ...interface{}) (int64, error) {\n\treturn HookInsert(func() (int64, error) {\n\t\treturn session.Session.Insert(beans...)\n\t})\n}", "func (n *Node) InsertVal(req KVPair, done *bool) error {\n\t*done = false\n\tn.Data.lock.Lock()\n\tn.Data.Map[req.Key] = req.Val\n\tn.Data.lock.Unlock()\n\n\t_ = n.FixSuc()\n\tclient, err := rpc.Dial(\"tcp\", n.GetWorkingSuc().IP)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = client.Call(\"NetNode.PutValBackup\", req, done)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = client.Close()\n\tif err != nil {\n\t\treturn err\n\t}\n\t*done = true\n\treturn nil\n}", "func (ct *CompositeTree) Insert(item interface{}) (err error) {\n\ttreeIndex := atomic.AddUint32(&ct.insertCount, 1) % uint32(len(ct.trees))\n\treturn ct.trees[treeIndex].Insert(item)\n}", "func (st *SymTab) Add(name ID, t Type) bool {\n\t_, sc := st.scopes.top()\n\tif _, ok := (*sc)[name]; ok {\n\t\treturn false\n\t}\n\n\t(*sc)[name] = t\n\treturn true\n}", "func (st *SetTranslation) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif st._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by sequence\n\tconst sqlstr = `INSERT INTO set_translations (` +\n\t\t`language, setCode, translation` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`) RETURNING id`\n\n\t// run query\n\tXOLog(sqlstr, st.Language, st.Setcode, st.Translation)\n\terr = db.QueryRow(sqlstr, st.Language, st.Setcode, st.Translation).Scan(&st.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tst._exists = true\n\n\treturn nil\n}", "func (s *stack) Push(value interface{}) interface{} {\n\ttop := &node{\n\t\tvalue: value,\n\t\tprev: s.top,\n\t}\n\ts.top = top\n\ts.length += 1\n\ts.calcMin(value, false)\n\treturn s.top.value\n}", "func (self *Ring) Insert(key int, val string, consistency int) {\n\n\targs := data.NewDataStore(key, val)\n\tresult := self.callSuccessorRPC(key, \"Ring.SendData\", args, consistency)\n\n\tif result.Member != nil && result.Success != 1 {\n\t\tself.updateMember(result.Member)\n\t\tself.Insert(key, val, consistency)\n\t} else {\n\t\ttimeout := 3\n\t\ti := 0\n\t\t//Found New Member\n\t\tfmt.Println(result.Success)\n\t\tfor result.Success == -2 && i < timeout {\n\t\t\ti++\n\t\t\tresult = self.callSuccessorRPC(key, \"Ring.SendData\", args, consistency)\n\n\t\t}\n\t}\n\n}", "func (r attestationRepo) Insert(attestation *NewAttestation) (string, error) {\n\tconst Query = `\n\t\tINSERT INTO attestation (\n\t\t\tclaimant_id,\n\t\t\tattestor_id,\n\t\t\tclaim\n\t\t) VALUES (\n\t\t\t$1,\n\t\t\t$2,\n\t\t\t$3\n\t\t)\n\t\tRETURNING id;`\n\tvar id string\n\terr := r.dao.QueryRow(\n\t\tQuery,\n\t\tattestation.ClaimantID,\n\t\tattestation.AttestorID,\n\t\tattestation.Claim,\n\t).Scan(&id)\n\tif err != nil {\n\t\treturn \"\", errors.Wrapf(err, \"failed to insert attestation\")\n\t}\n\treturn id, nil\n}", "func (t *Territory) Insert(ctx context.Context, db DB) error {\n\tswitch {\n\tcase t._exists: // already exists\n\t\treturn logerror(&ErrInsertFailed{ErrAlreadyExists})\n\tcase t._deleted: // deleted\n\t\treturn logerror(&ErrInsertFailed{ErrMarkedForDeletion})\n\t}\n\t// insert (manual)\n\tconst sqlstr = `INSERT INTO territories (` +\n\t\t`territory_id, territory_description, region_id` +\n\t\t`) VALUES (` +\n\t\t`$1, $2, $3` +\n\t\t`)`\n\t// run\n\tlogf(sqlstr, t.TerritoryID, t.TerritoryDescription, t.RegionID)\n\tif _, err := db.ExecContext(ctx, sqlstr, t.TerritoryID, t.TerritoryDescription, t.RegionID); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set exists\n\tt._exists = true\n\treturn nil\n}", "func (s Set) Insert(x interface{}) Set {\n\treturn Set{s.Tree.Insert(x)}\n}", "func (s *Stack) Push(value []byte) (*Item, error) {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\t// Check if stack is closed.\n\tif !s.isOpen {\n\t\treturn nil, ErrDBClosed\n\t}\n\n\t// Create new Item.\n\titem := &Item{\n\t\tID: s.head + 1,\n\t\tKey: idToKey(s.head + 1),\n\t\tValue: value,\n\t}\n\n\t// Add it to the stack.\n\tif err := s.db.Update(func(txn *badger.Txn) error {\n\t\terr := txn.Set(item.Key, item.Value)\n\t\treturn err\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Increment head position.\n\ts.head++\n\n\treturn item, nil\n}", "func (s *State) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif s._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by sequence\n\tconst sqlstr = `INSERT INTO public.state (` +\n\t\t`\"namespace\", \"context_id\", \"created_at\", \"state\", \"data\", \"event\", \"processing_error\"` +\n\t\t`) VALUES (` +\n\t\t`$1, $2, $3, $4, $5, $6, $7` +\n\t\t`) RETURNING \"id\"`\n\n\t// run query\n\tXOLog(sqlstr, s.Namespace, s.ContextID, s.CreatedAt, s.State, s.Data, s.Event, s.ProcessingError)\n\terr = db.QueryRow(sqlstr, s.Namespace, s.ContextID, s.CreatedAt, s.State, s.Data, s.Event, s.ProcessingError).Scan(&s.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\ts._exists = true\n\n\treturn nil\n}", "func (t *Indexed) Insert(index, value int) {\n\tnewNode := NewNodeWithValue(index, value)\n\tl, r := t.split(t.root, index-1)\n\txl, xr := t.split(r, index)\n\tif xl == nil {\n\t\tt.size++\n\t}\n\tl = t.merge(l, newNode)\n\tt.root = t.merge(l, xr)\n}", "func (rbst *RBSTAbelGroup) Insert(root *Node, pos int, node *Node) *Node {\r\n\tn := rbst.Size(root)\r\n\tif pos < 0 {\r\n\t\tpos += n\r\n\t}\r\n\tif pos < 0 {\r\n\t\tpos = 0\r\n\t}\r\n\tif pos > n {\r\n\t\tpos = n\r\n\t}\r\n\tleft, right := rbst.SplitByRank(root, pos)\r\n\treturn rbst.Merge(left, rbst.Merge(node, right))\r\n}", "func (b *Bstree) Insert(v int) *Bstree {\n\tif b.Root == nil {\n\t\tb.Root = &node{value: v, depth: 0}\n\t\treturn b\n\t}\n\tb.Root.insert(v)\n\treturn b\n}", "func (treeNode *TreeNode) Insert(son1 *TreeNode, son2 *TreeNode) *TreeNode {\n\tvar root *TreeNode\n\tvar item Item\n\n\titem.Symbol = 0\n\titem.Weight = son1.Value.Weight + son2.Value.Weight\n\troot, _ = root.New(item)\n\n\t//This condition may be avoided if the heap is well managed.\n\tif son1.Value.Weight < son2.Value.Weight {\n\t\troot.Left = son1\n\t\troot.Right = son2\n\t} else {\n\t\troot.Left = son2\n\t\troot.Right = son1\n\t}\n\n\treturn root\n}", "func (t *Top) Add(o api.Object) {\n\tif _, ok := t.objects[o.UID().String()]; !ok {\n\t\tt.objects[o.UID().String()] = o\n\n\t\tif t.index[o.Namespace()] == nil {\n\t\t\tt.index[o.Namespace()] = make(map[string]map[string]api.Object)\n\t\t}\n\n\t\tif t.index[o.Namespace()][o.Kind()] == nil {\n\t\t\tt.index[o.Namespace()][o.Kind()] = make(map[string]api.Object)\n\t\t}\n\n\t\tt.index[o.Namespace()][o.Kind()][o.Name()] = o\n\t}\n}", "func (b *Bag) Insert(val rune) {\n\tb.data[val]++\n}", "func (tree *BST) Insert(value int) {\n\tnewNode := &Node{value: value}\n\n\t// just in case root is not defined\n\tif tree.rootNode == nil {\n\t\ttree.rootNode = newNode\n\t\treturn\n\t}\n\n\t// keep track of current position in the tree\n\tcurrentNode := tree.rootNode\n\n\tfor {\n\t\tif value > currentNode.value {\n\t\t\t// if right leaf node is not defined then add the new node and stop\n\t\t\t// the traversing\n\t\t\tif currentNode.right == nil {\n\t\t\t\tcurrentNode.right = newNode\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// otherwise continue traversing the right leaf nodes\n\t\t\tcurrentNode = currentNode.right\n\t\t} else if value < currentNode.value {\n\t\t\t// again if left leaf node is not defined then add the new node and stop\n\t\t\t// the traversing\n\t\t\tif currentNode.left == nil {\n\t\t\t\tcurrentNode.left = newNode\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// otherwise continue traversing the left leaf nodes\n\t\t\tcurrentNode = currentNode.left\n\t\t} else {\n\t\t\t// if we land here that means that value has already been added to\n\t\t\t// the tree. Stop the travese\n\t\t\treturn\n\t\t}\n\t}\n}", "func (s *callStack) lookUpVar(id ast.Identifier) *cachedThunk {\n\tfor i := len(s.stack) - 1; i >= 0; i-- {\n\t\tbind, present := s.stack[i].env.upValues[id]\n\t\tif present {\n\t\t\treturn bind\n\t\t}\n\t\tif s.stack[i].cleanEnv {\n\t\t\t// Nothing beyond the captured environment of the thunk / closure.\n\t\t\tbreak\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Tree) Insert(rr dns.RR) {\n\tvar d int\n\tt.Root, d = t.Root.insert(rr)\n\tt.Count += d\n\tt.Root.Color = Black\n}", "func (vm *ValueMap) Insert(name string, value llvm.Value) {\n\tvm.vmap[name] = value\n}", "func (m *memory) Insert(q Quote) (Quote, error) {\n\tif q.ID != \"\" {\n\t\treturn Quote{}, fmt.Errorf(\"ID of quote should not be set: %s\", q.ID)\n\t}\n\tid := randomID(8)\n\n\tq.ID = id\n\tm.quotes[q.ID] = q\n\n\treturn q, nil\n}", "func (ds Dataset) AddVar(name string, t Type, dims []Dim) (v Var, err error) {\n\tcname := C.CString(name)\n\tdefer C.free(unsafe.Pointer(cname))\n\tvar varid C.int\n\tvar dimPtr *C.int\n\tif len(dims) > 0 {\n\t\tdimids := make([]C.int, len(dims))\n\t\tfor i, d := range dims {\n\t\t\tdimids[i] = d.id\n\t\t}\n\t\tdimPtr = &dimids[0]\n\t}\n\terr = newError(C.nc_def_var(C.int(ds), cname, C.nc_type(t),\n\t\tC.int(len(dims)), dimPtr, &varid))\n\tv = Var{ds, varid}\n\treturn\n}", "func (p *Personal) Insert(ctx context.Context, document *PersonalData) (interface{}, error) {\n\ti, err := p.DB.Insert(ctx, document)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not insert personal data\")\n\t}\n\treturn i, nil\n}", "func (b *Build) Insert() error {\n\treturn db.Insert(Collection, b)\n}", "func (o *<%= classedName %>) Insert() error {\n\tif _, err := orm.NewOrm().Insert(o); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (t *chaining) Insert(key string, val interface{}) {\n\tif t.loadFactor() > t.maxLoad {\n\t\tt.tableDouble()\n\t}\n\thash := t.hash(key)\n\tif t.values[hash] == nil {\n\t\tt.values[hash] = list.New()\n\t}\n\tt.values[hash].Insert(&pair{key, val})\n\tt.len++\n}", "func (v *TreeStore) Insert(parent *TreeIter, position int) *TreeIter {\n\tvar ti C.GtkTreeIter\n\tvar cParent *C.GtkTreeIter\n\tif parent != nil {\n\t\tcParent = parent.native()\n\t}\n\tC.gtk_tree_store_insert(v.native(), &ti, cParent, C.gint(position))\n\titer := &TreeIter{ti}\n\treturn iter\n}", "func (w *Window) Insert(e interface{}) {\n\tw.insertAt(time.Now(), e)\n}", "func (m *DBMem) Insert(data Person) {\n m.Lock()\n defer m.Unlock()\n\n\tid := len(m.data)\n m.data[id] = data\n m.history.Append(\"INSERT\", id, data)\n}", "func (d *Dtrie) Insert(key, value interface{}) *Dtrie {\n\troot := insert(d.root, &entry{d.hasher(key), key, value})\n\treturn &Dtrie{root, d.hasher}\n}", "func (bst *StringBinarySearchTree) Insert(key int, value string) {\n\tbst.lock.Lock()\n\tdefer bst.lock.Unlock()\n\tn := &Node{key, value, nil, nil}\n\tif bst.root == nil {\n\t\tbst.root = n\n\t} else {\n\t\tinsertNode(bst.root, n)\n\t}\n}", "func (builder QueryBuilder) Variable(queryBuilder QueryBuilder) QueryBuilder {\n\tbuilder.variables = append(builder.variables, queryBuilder)\n\treturn builder\n}", "func (fh *FibonacciHeap) Insert(item heap.Item) heap.Item {\n\tn := &node{item: item, isMarked: false}\n\n\tfh.insertRoot(n)\n\treturn item\n}", "func (ps *PlayerStore) Insert(ctx context.Context, player store.Player) (*store.Player, error) {\n\tquery := `\n INSERT INTO players(roster_id,first_name,last_name,alias,status)\n VALUES($1,$2,$3,$4,$5)\n RETURNING *\n `\n\tdb := ps.db.GetDB()\n\tctx, cancel := ps.db.RequestContext(ctx)\n\tdefer cancel()\n\n\tvar p store.Player\n\terr := db.QueryRowContext(ctx, query,\n\t\tplayer.RosterID,\n\t\tplayer.FirstName,\n\t\tplayer.LastName,\n\t\tplayer.Alias,\n\t\tplayer.Status).\n\t\tScan(\n\t\t\t&p.PlayerID,\n\t\t\t&p.RosterID,\n\t\t\t&p.FirstName,\n\t\t\t&p.LastName,\n\t\t\t&p.Alias,\n\t\t\t&p.Status)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &p, nil\n}", "func (this *Trie) Insert(word string) {\n\thead := this\n\tfor e := range word {\n\t\tif head.data[word[e]-'a'] == nil {\n\t\t\thead.data[word[e]-'a'] = &Trie{}\n\t\t}\n\t\thead = head.data[word[e]-'a']\n\t}\n\thead.now = true\n}", "func StoreVariable(name string) {\n\toutput.EmitLn(\"LEA \" + name + \"(PC),A0\")\n\toutput.EmitLn(\"MOVE D0,(A0)\")\n}", "func (ds *DjangoSession) Insert(ctx context.Context, db DB) error {\n\tswitch {\n\tcase ds._exists: // already exists\n\t\treturn logerror(&ErrInsertFailed{ErrAlreadyExists})\n\tcase ds._deleted: // deleted\n\t\treturn logerror(&ErrInsertFailed{ErrMarkedForDeletion})\n\t}\n\t// insert (manual)\n\tconst sqlstr = `INSERT INTO django.django_session (` +\n\t\t`session_key, session_data, expire_date` +\n\t\t`) VALUES (` +\n\t\t`:1, :2, :3` +\n\t\t`)`\n\t// run\n\tlogf(sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate)\n\tif _, err := db.ExecContext(ctx, sqlstr, ds.SessionKey, ds.SessionData, ds.ExpireDate); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set exists\n\tds._exists = true\n\treturn nil\n}", "func insert(val int, root *Node) (*Node) {\n if root == nil {\n return newNode(val)\n }\n\n if val <= (*root).val {\n (*root).left = insert(val, (*root).left)\n } else {\n (*root).right = insert(val, (*root).right)\n }\n\n return root\n}", "func (s *Storer) Create(ctx context.Context, scope scopes.Scope) error {\n\tquery := createSQL(ctx, toPostgres(scope))\n\tqueryStr, err := query.PostgreSQLString()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error generating insert SQL: %w\", err)\n\t}\n\t_, err = s.db.Exec(queryStr, query.Args()...)\n\tvar pqErr *pq.Error\n\tif errors.As(err, &pqErr) && pqErr.Constraint == \"scopes_pkey\" {\n\t\treturn scopes.ErrScopeAlreadyExists\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting scope: %w\", err)\n\t}\n\treturn nil\n}", "func (s *BasePlSqlParserListener) EnterVariable_declaration(ctx *Variable_declarationContext) {}" ]
[ "0.6903358", "0.65885115", "0.568562", "0.552916", "0.5494221", "0.5308372", "0.5281387", "0.52769846", "0.52433", "0.52386993", "0.52241087", "0.52225804", "0.51992154", "0.51872796", "0.51260006", "0.5123828", "0.5115646", "0.51118416", "0.5083295", "0.50671625", "0.49985147", "0.49832657", "0.49697727", "0.49688023", "0.4967568", "0.49620295", "0.49273732", "0.49175736", "0.49166054", "0.49028692", "0.48905343", "0.4880615", "0.48726296", "0.4867785", "0.48672226", "0.48649776", "0.48275265", "0.48237342", "0.48223937", "0.48207393", "0.48114014", "0.47963688", "0.47935095", "0.4783527", "0.47717208", "0.47712624", "0.47710088", "0.476879", "0.47662252", "0.4762008", "0.4750125", "0.4747253", "0.4744923", "0.4743259", "0.4735462", "0.47341403", "0.4728025", "0.4724748", "0.47207156", "0.4718405", "0.47164968", "0.47099108", "0.47031096", "0.46897426", "0.46810862", "0.46782866", "0.46761832", "0.4674272", "0.46722722", "0.4670633", "0.46689188", "0.4667419", "0.46630344", "0.46601504", "0.46529704", "0.46518826", "0.46482256", "0.46450722", "0.4640858", "0.46333334", "0.46322435", "0.46304268", "0.462903", "0.46255443", "0.46248385", "0.46242929", "0.4621932", "0.46186042", "0.4612787", "0.46096438", "0.4603022", "0.46001643", "0.45981893", "0.45972243", "0.45947203", "0.45945275", "0.45942098", "0.45928138", "0.45922616", "0.459186" ]
0.7800074
0
Anonymous creates a new anonymous Variable at the top scope and returns it. This is useful for Nodes that might Render more than once and want to store state between Renders.
func (s *scope) Anonymous(init Value) Variable { v := Variable(s.len()) level := s.levels[len(s.levels)-1] level.init[v] = init s.maxLen++ return v }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createAVariableNode(name string) *parse.VariableNode {\n\tvarNode := &parse.VariableNode{\n\t\tNodeType: parse.NodeVariable,\n\t\tIdent: []string{name},\n\t}\n\treturn varNode\n}", "func NewVariable() *Variable {\n\tnextVariableIDMu.Lock()\n\tid := nextVariableID\n\tnextVariableID++\n\tnextVariableIDMu.Unlock()\n\treturn &Variable{ID: id}\n}", "func New(w driver.Watcher) *Variable {\n\treturn &Variable{watcher: w}\n}", "func (UnqualifiedStar) Variable() {}", "func (e *Environment) GetAnonymous() Namespace {\n\troot := e.GetRoot()\n\treturn chain(root, &anonymous{\n\t\tNamespace: e.New(AnonymousDomain),\n\t})\n}", "func New(v interface{}) (x *TVar) {\n\tx = &TVar{}\n\tx.value.Store(v)\n\treturn x\n}", "func AutoVar(v *ssa.Value) (*Node, int64)", "func anonymous(vars []*types.Var, prefix string, typed bool) string {\n\tif len(vars) == 0 {\n\t\treturn \"\"\n\t}\n\tvar buf strings.Builder\n\tfor i, v := range vars {\n\t\tif i != 0 {\n\t\t\tbuf.WriteString(\", \")\n\t\t}\n\t\tif !typed {\n\t\t\tbuf.WriteString(fmt.Sprintf(\"%s%d\", prefix, i))\n\t\t\tcontinue\n\t\t}\n\t\tname := v.Name()\n\t\tif name == \"\" {\n\t\t\tname = fmt.Sprintf(\"%s%d\", prefix, i)\n\t\t}\n\t\tbuf.WriteString(fmt.Sprintf(\"%s %s\", name, path.Base(v.Type().String())))\n\t}\n\treturn buf.String()\n}", "func (a Anonymous) ID() string { return \"anonymous\" }", "func (vs *Variables) Variable(vn Variablename) Variable {\n\tv, ok := vs.m[vn]\n\tif !ok {\n\t\tv = Variable(len(vs.n))\n\t\tvs.m[vn] = v\n\t\tvs.n = append(vs.n, vn)\n\t}\n\treturn v\n}", "func NewAnonymousFile() *AnonymousFile {\n\treturn &AnonymousFile{contents: make([]byte, 0)}\n}", "func (v Variable) Evaluate() Expression {\n\treturn v\n}", "func (obj *alpha) Variable() string {\n\treturn obj.variable\n}", "func newVar(v interface{}) (*interface{}, error) {\n\tx := interface{}(v)\n\treturn &x, nil\n}", "func anonymousFunc() {\n\tvar f func() = func() {\n\t\tfmt.Println(\"Hello Go!\")\n\t}\n\tg := func() {\n\t\tfmt.Println(\"Hello Go!\")\n\t}\n\tf()\n\tg()\n}", "func (t *Variable) Root() Type {\n\tt.instanceMu.Lock()\n\tdefer t.instanceMu.Unlock()\n\tif t.Instance == nil {\n\t\treturn t\n\t}\n\tr := t.Instance.Root()\n\tt.Instance = r\n\treturn r\n}", "func Var(attrs []htmlgo.Attribute, children ...HTML) HTML {\n\treturn &htmlgo.Tree{Tag: \"var\", Attributes: attrs, Children: children}\n}", "func (*UnresolvedName) Variable() {}", "func anonymous(){\n\td1 := struct {\n\t\tname string\n\t\tage int\n\t}{\n\t\tname: \"Bob\",\n\t\tage: 20,\n\t}\n\n\n\tfmt.Println(d1, d1.name, d1.age)\n}", "func NoVars() interpreter.Activation {\n\treturn interpreter.EmptyActivation()\n}", "func NewImmediate() *Immediate {\n\ti := &Immediate{}\n\ti.handler.Store(sentinelOnSnapshot)\n\n\treturn i\n}", "func New() *Node {\n\treturn &Node{}\n}", "func newVar(w driver.Watcher) *Variable {\n\tctx, cancel := context.WithCancel(context.Background())\n\tchanged := make(chan struct{})\n\tv := &Variable{\n\t\tdw: w,\n\t\tprovider: oc.ProviderName(w),\n\t\tbackgroundCancel: cancel,\n\t\tbackgroundDone: make(chan struct{}),\n\t\thaveGoodCh: make(chan struct{}),\n\t\tchanged: changed,\n\t\tlastWatch: changed,\n\t\tlastErr: gcerr.Newf(gcerr.FailedPrecondition, nil, \"no value yet\"),\n\t}\n\tgo v.background(ctx)\n\treturn v\n}", "func Variable(rootQueryFn *FilterFn) QueryBuilder {\n\tquery := Query(rootQueryFn)\n\tquery.rootEdge.IsVariable = true\n\treturn query\n}", "func Var(props *VarProps, children ...Element) *VarElem {\n\trProps := &_VarProps{\n\t\tBasicHTMLElement: newBasicHTMLElement(),\n\t}\n\n\tif props != nil {\n\t\tprops.assign(rProps)\n\t}\n\n\treturn &VarElem{\n\t\tElement: createElement(\"var\", rProps, children...),\n\t}\n}", "func New() *Evaluator {\n\teval := &Evaluator{\n\t\tCtxt: lexer.Context{Line: 1, Col: 1, Ctxt: \"\"},\n\t\tloopcount: 0,\n\t}\n\treturn eval\n}", "func NewStateVariable() *StateVariable {\n\treturn &StateVariable{}\n}", "func execNewVar(_ int, p *gop.Context) {\n\targs := p.GetArgs(4)\n\tret := types.NewVar(token.Pos(args[0].(int)), args[1].(*types.Package), args[2].(string), args[3].(types.Type))\n\tp.Ret(4, ret)\n}", "func NewVar(val interface{}) *Var {\n\treturn &Var{val: val}\n}", "func Var_(children ...HTML) HTML {\n return Var(nil, children...)\n}", "func (obj *declaration) Variable() string {\n\treturn obj.name\n}", "func Immediate(value interface{}) *Value {\n\treturn NewValue(func() interface{} { return value })\n}", "func New(root *ssa.Function) *Graph {\n\tg := &Graph{Nodes: make(map[*ssa.Function]*Node)}\n\tg.Root = g.CreateNode(root)\n\treturn g\n}", "func New(d *Dispatcher) *Identity {\n\td.Lock()\n\tdefer d.Unlock()\n\tstate := randToken()\n\ti := &Identity{\n\t\tstate: state,\n\t}\n\td.identities[state] = i\n\treturn i\n}", "func MakeVariableFromCallback(set func(Value), get func() Value) Variable {\n\treturn &cbVariable{set, get}\n}", "func (builder QueryBuilder) Variable(queryBuilder QueryBuilder) QueryBuilder {\n\tbuilder.variables = append(builder.variables, queryBuilder)\n\treturn builder\n}", "func NewVariable(tau TypeT) TermT {\n\treturn TermT(C.yices_new_variable(C.type_t(tau)))\n}", "func newVarDeclaration(variable *Param) *Instruction {\n\treturn &Instruction{\n\t\tType: VarDeclarationInst,\n\t\tName: variable.Name,\n\t\tVariable: variable,\n\t}\n}", "func (a *AllColumnsSelector) Variable() {}", "func New(value ValueInterface) *Node {\n\treturn &Node{Value: value}\n}", "func CreateBuiltinVar() *functions.BuiltinFunction {\n\treturn functions.NewBuiltinFunction(Var, 1, false)\n}", "func New(name string) *Tree {\n\treturn &Tree{name: name, root: &Node{}, mtx: &sync.RWMutex{}}\n}", "func newChunkExprVarFunc(name string, params *chunk, chained *chunk, reporter errorLocationReporter) *chunk {\n\tr := newChunk(CHUNK_EXPR_VARFUNC, reporter)\n\tr.m[\"name\"] = name\n\tr.m[\"params\"] = params\n\tr.m[\"chained\"] = chained\n\treturn r\n}", "func (obj *register) Variable() string {\n\treturn obj.variable\n}", "func (*Base) Var(p ASTPass, node *ast.Var, ctx Context) {\n}", "func lexVariable(l *lexer) stateFn {\n\tif l.atTerminator() { // Nothing interesting follows -> \"$\".\n\t\tl.emit(itemVariable)\n\t\treturn lexInsideAction\n\t}\n\treturn lexFieldOrVariable(l, itemVariable)\n}", "func (c *ColumnItem) Variable() {}", "func NewVar(name string) Var {\n\treturn Var{Name: name}\n}", "func (v Variable) Accept(interpreter *Interpreter) Object {\n\treturn interpreter.visitVariable(v)\n}", "func NewVariable(managementDirPath, dataDirectoryName, projectName, goPath, goRootPath string) *Variable {\n\tv := &Variable{\n\t\tManagementDirectoryPath: managementDirPath,\n\t\tDataDirectoryName: dataDirectoryName,\n\t\tProjectName: projectName,\n\t\tGoPath: goPath,\n\t\tGoRootPath: goRootPath}\n\n\treturn v\n}", "func New() Tree {\n\treturn &Node{Value: \".\"}\n}", "func NewVar(name string) Var {\n\treturn Var{\n\t\tname: name,\n\t}\n}", "func NewVar(name string, typ Type) *Var {\n\treturn &Var{object: object{scope: nil, name: name, typ: typ}}\n}", "func AnonymousStruct() {\n\t//Biasanya dideklarasikan diluar ataupun didalam func\n\ttype orang struct {\n\t\tnama string\n\t}\n\n\t// struct ini nyaris sama seperti variabel dan tidak mempunya nama struct\n\t// hanya digunakan didalam func saja\n\tvar As1 = struct {\n\t\torang\n\t\tnegara string\n\t}{}\n\n\tAs1.nama = \"olgi\"\n\tAs1.negara = \"indonesia\"\n\n\tfmt.Println(\"Nama\\t = \", As1.nama)\n\tfmt.Println(\"Nama\\t = \", As1.negara)\n}", "func NewVarFromObject(t token.Token, value Block) *VarLiteral {\n\treturn &VarLiteral{\n\t\tToken: t,\n\t\tTypeOf: NewVarType(NewObjectType()),\n\t\tValue: value,\n\t}\n}", "func New() *Tree {\n\treturn &Tree{root: &node{}}\n}", "func createNewEmptyNode() Node {\n\tnextNewId--\n\treturn Node{\n\t\tId: nextNewId,\n\t\tVisible: true,\n\t\tTimestamp: time.Now().Format(\"2006-01-02T15:04:05Z\"),\n\t\tVersion: \"1\",\n\t}\n}", "func (s *BasePlSqlParserListener) EnterAnonymous_block(ctx *Anonymous_blockContext) {}", "func (c *Client) Anonymous(userId string) *Client {\n\tanonymous := *c\n\tanonymous.userHeader = \"user-id\"\n\tanonymous.user = userId\n\treturn &anonymous\n}", "func NewVariableBackend(b *APIBackend) *VariableBackend {\n\treturn &VariableBackend{\n\t\tHTTPErrorHandler: b.HTTPErrorHandler,\n\t\tLogger: b.Logger.With(zap.String(\"handler\", \"variable\")),\n\t\tVariableService: b.VariableService,\n\t\tLabelService: b.LabelService,\n\t}\n}", "func (p *Package) Var(name string) (g *Global) {\n\tg, _ = p.Members[name].(*Global)\n\treturn\n}", "func (p *parser) function() Node {\n\tident := p.expect(TokenIdent)\n\tp.expect(TokenLParen)\n\targs := p.parameters()\n\tp.expect(TokenRParen)\n\n\tn := newFunc(ident.pos, ident.val, args)\n\treturn n\n}", "func (rec *RawEventCreate) SetAnonymous(b bool) *RawEventCreate {\n\trec.mutation.SetAnonymous(b)\n\treturn rec\n}", "func MakeRoVariableFromCallback(get func() Value) Variable {\n\treturn roCbVariable(get)\n}", "func NewJS() *JS {\n\treturn &JS{js.Global}\n}", "func newNode[T any]() *node[T] {\n\treturn &node[T]{mu: chanmutex.NewLocked()}\n}", "func StarExpr() VarName { return singletonStarName }", "func newVariable(name, paramType string) *Param {\n\treturn &Param{\n\t\tParameterKind: variable,\n\t\tName: name,\n\t\tParameterType: paramType,\n\t}\n}", "func EnableAnonymous() {\n\tanonFlag = true\n}", "func New() *Node {\n\treturn &Node{\n\t\tparent: nil,\n\t\tchildren: map[option]*Node{},\n\t}\n}", "func (g *Graph) Identity(x Node) Node {\n\treturn g.NewOperator(fn.NewIdentity(x), x)\n}", "func (s *SparkCoreAdaptor) Variable(name string) (result string, err error) {\n\turl := fmt.Sprintf(\"%v/%s?access_token=%s\", s.deviceURL(), name, s.AccessToken)\n\tresp, err := s.requestToSpark(\"GET\", url, nil)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\tval := resp[\"result\"]\n\tswitch val.(type) {\n\tcase bool:\n\t\tresult = strconv.FormatBool(val.(bool))\n\tcase float64:\n\t\tresult = strconv.FormatFloat(val.(float64), 'f', -1, 64)\n\tcase string:\n\t\tresult = val.(string)\n\t}\n\n\treturn\n}", "func NewVariableReference(name string, typ Type) Expression {\n\treturn &variableReference{\n\t\tname: name,\n\t\ttyp: typ,\n\t}\n}", "func NewVariables() *Variables {\n\treturn &Variables{\n\t\tm: make(map[Variablename]Variable),\n\t}\n}", "func (p *Expression) Name() string {\n\treturn p.variable\n}", "func NewIdle() *Idle {\n\treturn &Idle{}\n}", "func NewNode(id uint64) *Node { return &Node{Id: id} }", "func NewAnonymousUser(key string) ldcontext.Context {\n\treturn ldcontext.NewBuilder(key).Anonymous(true).Build()\n}", "func (tr *transform) newExpression(iVar interface{}) *expression {\n\tvar id string\n\n\tif iVar != nil {\n\t\tswitch tVar := iVar.(type) {\n\t\tcase *ast.Ident:\n\t\t\tid = tVar.Name\n\t\tcase string:\n\t\t\tid = tVar\n\t\t}\n\t}\n\n\treturn &expression{\n\t\ttr,\n\t\tnew(bytes.Buffer),\n\t\tid,\n\t\t\"\",\n\t\t\"\",\n\t\t\"\",\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tfalse,\n\t\tmake([]string, 0),\n\t\tmake([]string, 0),\n\t}\n}", "func (p *parser) vr() Node {\n\tp.expect(TokenVar)\n\tident := p.expect(TokenIdent)\n\treturn newIdent(ident.pos, ident.val)\n}", "func (x ReturnStmt) New() Ast { return ReturnStmt{&ast.ReturnStmt{}} }", "func NewState() *State {\n\tglobals := newModule()\n\t\n\t// Provide a self reference for use when declaring global script variables.\n\tglobals.modules.add(\"global\", globals)\n\t\n\treturn &State{\n\t\tglobal: globals,\n\t\tOutput: os.Stdout,\n\t}\n}", "func StoreVariable(name string) {\n\toutput.EmitLn(\"LEA \" + name + \"(PC),A0\")\n\toutput.EmitLn(\"MOVE D0,(A0)\")\n}", "func (c Class) InstanceVariable(name string) Ivar {\n\treturn class_getInstanceVariable(c, name)\n}", "func (thisListener *GruleV3ParserListener) EnterVariable(ctx *grulev3.VariableContext) {\n\tif thisListener.StopParse {\n\n\t\treturn\n\t}\n\tvari := ast.NewVariable()\n\tif ctx.SIMPLENAME() != nil && len(ctx.SIMPLENAME().GetText()) > 0 {\n\t\tvari.Name = ctx.SIMPLENAME().GetText()\n\t}\n\tif ctx.MemberVariable() != nil && len(ctx.MemberVariable().GetText()) > 0 {\n\t\tvari.Name = ctx.MemberVariable().GetText()[1:]\n\t}\n\tvari.GrlText = ctx.GetText()\n\tthisListener.Stack.Push(vari)\n}", "func (sv *StateVariable) Visit(ctx *parser.StateVariableDeclarationContext) {\n\tsv.Start = ctx.GetStart()\n\tsv.Stop = ctx.GetStop()\n\n\ttypeName := NewTypeName()\n\ttypeName.Visit(ctx.TypeName().(*parser.TypeNameContext))\n\n\tsv.TypeName = typeName\n\tsv.Public = ctx.PublicKeyword(0) != nil\n\tsv.Internal = ctx.InternalKeyword(0) != nil\n\tsv.Private = ctx.PrivateKeyword(0) != nil\n\tsv.Constant = ctx.ConstantKeyword(0) != nil\n\n\tsv.Identifier = ctx.Identifier().GetText()\n\n\tif ctx.Expression() != nil {\n\t\texpr := NewExpression()\n\t\texpr.Visit(ctx.Expression().(*parser.ExpressionContext))\n\t}\n}", "func (s *BaserpnListener) EnterVariable(ctx *VariableContext) {}", "func New(cacheNodeidentityInfo bool) (nodeidentity.Identifier, error) {\n\tclient, err := newClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &nodeIdentifier{\n\t\tvmssGetter: client,\n\t\tcache: expirationcache.NewTTLStore(stringKeyFunc, cacheTTL),\n\t\tcacheEnabled: cacheNodeidentityInfo,\n\t}, nil\n}", "func newNode() *node {\n\treturn &node{\n\t\tvalue: nil,\n\t\tchildren: map[string]*node{},\n\t}\n}", "func (s *BasearithmeticListener) EnterVariable(ctx *VariableContext) {}", "func NewValue() *Value { return &Value{} }", "func (o *JS) New(args []interface{}) Object {\n\treturn &JS{o.object.New(args...)}\n}", "func (s *BasejossListener) EnterVariable(ctx *VariableContext) {}", "func New() *Tree {\n\treturn &Tree{}\n}", "func expvars() {\n\n\t// Add goroutine counts to the variable set.\n\tgr := expvar.NewInt(\"goroutines\")\n\tgo func() {\n\t\tfor range time.Tick(time.Millisecond * 250) {\n\t\t\tgr.Set(int64(runtime.NumGoroutine()))\n\t\t}\n\t}()\n}", "func New(data int) *Node {\n\treturn new(Node).Init(data)\n}", "func NewVars() Vars {\n\treturn Vars{}\n}", "func NewJsEvalModule(bot *common.Bot) *JsEval {\n jsEval := &JsEval {\n bot: bot,\n vm: otto.New(),\n }\n return jsEval\n}", "func New(req *http.Request) *View {\n\tv := &View{}\n\tv.Vars = make(map[string]interface{})\n\tv.Vars[\"AuthLevel\"] = \"anon\"\n\n\tv.BaseURI = viewInfo.BaseURI\n\tv.Extension = viewInfo.Extension\n\tv.Folder = viewInfo.Folder\n\tv.Name = viewInfo.Name\n\n\t// Make sure BaseURI is available in the templates\n\tv.Vars[\"BaseURI\"] = v.BaseURI\n\n\t// This is required for the view to access the request\n\tv.request = req\n\n\t// Get session\n\tsess := session.Instance(v.request)\n\n\t// Set the AuthLevel to auth if the user is logged in\n\tif sess.Values[\"id\"] != nil {\n\t\tv.Vars[\"AuthLevel\"] = \"auth\"\n\t}\n\n\treturn v\n}", "func NewIdent(name string) *Ident { return &Ident{token.NoPos, name} }" ]
[ "0.57917655", "0.5623713", "0.545665", "0.5301749", "0.5280797", "0.5251604", "0.5242554", "0.5211543", "0.5188995", "0.51001465", "0.50814116", "0.50725365", "0.50594354", "0.5057586", "0.5052261", "0.5039523", "0.50193906", "0.49322316", "0.48742843", "0.48686838", "0.4867679", "0.48540932", "0.48431385", "0.48278302", "0.48243222", "0.48168305", "0.4802384", "0.47937545", "0.4788721", "0.4769271", "0.47585875", "0.47535324", "0.47525215", "0.4745379", "0.4729511", "0.47289893", "0.47235072", "0.4719381", "0.47061786", "0.46876016", "0.46739846", "0.46649918", "0.46439305", "0.46295193", "0.4623162", "0.46021903", "0.4585519", "0.45817354", "0.4575566", "0.45669663", "0.45636111", "0.45569044", "0.4546055", "0.4545164", "0.45403472", "0.45360708", "0.45293108", "0.45207858", "0.45181468", "0.451684", "0.45158744", "0.4510792", "0.45105222", "0.45047498", "0.44915402", "0.44875953", "0.44867995", "0.44809136", "0.44731662", "0.44680887", "0.44565728", "0.4456009", "0.445487", "0.44525412", "0.44262993", "0.44249603", "0.44132692", "0.44091123", "0.44010785", "0.43981776", "0.43969396", "0.4391736", "0.4378283", "0.4370628", "0.43688145", "0.43427846", "0.43426642", "0.43316132", "0.4298167", "0.42903376", "0.4288478", "0.42856902", "0.4264663", "0.42628467", "0.4246977", "0.4246243", "0.42458132", "0.42446637", "0.42347732", "0.42298383" ]
0.7202289
0
NewKubeHTTP creates http client to kubeapi service.
func NewKubeHTTP(u *url.URL) Kube { log := logrus.WithField("component", "kube_client") client := resty.New(). SetHostURL(u.String()). SetLogger(log.WriterLevel(logrus.DebugLevel)). SetDebug(true). SetError(cherry.Err{}). SetHeader("Content-Type", "application/json"). SetHeader("Accept", "application/json") client.JSONMarshal = jsoniter.Marshal client.JSONUnmarshal = jsoniter.Unmarshal return kube{ client: client, log: cherrylog.NewLogrusAdapter(log), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newKubeClient(kubeConfig, apiServerURL string, requestTimeout time.Duration) (kubernetes.Interface, managednodeClientset.Interface, apiextensionClientset.Interface, error) {\n\tglog.Infof(\"Instantiating new Kubernetes client\")\n\n\tconfig, err := getRestConfig(kubeConfig, apiServerURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tconfig.Timeout = requestTimeout * time.Second\n\n\tconfig.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn instrumented_http.NewTransport(rt, &instrumented_http.Callbacks{\n\t\t\tPathProcessor: func(path string) string {\n\t\t\t\tparts := strings.Split(path, \"/\")\n\t\t\t\treturn parts[len(parts)-1]\n\t\t\t},\n\t\t})\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tnodeManagerClientset, err := managednodeClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nil, nil, err\n\t}\n\n\tapiExtensionClient, err := apiextensionClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nodeManagerClientset, nil, err\n\t}\n\n\tglog.Infof(\"Created Kubernetes client %s\", config.Host)\n\n\treturn client, nodeManagerClientset, apiExtensionClient, err\n}", "func NewHTTP(key client.ObjectKey) *HTTP {\n\treturn &HTTP{\n\t\tKey: key,\n\n\t\tOwnerConfigMap: corev1obj.NewConfigMap(key),\n\t\tService: corev1obj.NewService(key),\n\t\tPod: corev1obj.NewPod(key),\n\t}\n}", "func New(t time.Duration, inCluster bool) (*KubeAPI, error) {\n\tvar api KubeAPI\n\tapi.Timeout = t\n\tapi.InCluster = inCluster\n\tvar err error\n\n\tif api.InCluster {\n\t\tapi.Config, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn &api, err\n\t\t}\n\t} else {\n\t\tkubeconfig := filepath.Join(homeDir(), \".kube\", \"config\")\n\t\tapi.Config, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\n\tapi.Client, err = kubernetes.NewForConfig(api.Config)\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\treturn &api, nil\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func NewClient(host, token, nodeName string, insecure, UseAPIOnCacheIssues bool) (*Client, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif host != \"\" && token != \"\" {\n\t\tconfig = &rest.Config{\n\t\t\tHost: host,\n\t\t\tBearerToken: token,\n\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\tInsecure: insecure,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{Clientset: client, nodeName: nodeName, useAPIOnCacheIssues: UseAPIOnCacheIssues}, nil\n}", "func NewHTTP(config HTTPConfig, defaultWP WriteParams) (*httpClient, error) {\n\t// validate required parameters:\n\tif len(config.URL) == 0 {\n\t\treturn nil, fmt.Errorf(\"config.URL is required to create an HTTP client\")\n\t}\n\tif len(defaultWP.Database) == 0 {\n\t\treturn nil, fmt.Errorf(\"A default database is required to create an HTTP client\")\n\t}\n\n\t// set defaults:\n\tif config.Timeout == 0 {\n\t\tconfig.Timeout = defaultRequestTimeout\n\t}\n\tif config.MaxIdleConnsPerHost == 0 {\n\t\tconfig.MaxIdleConnsPerHost = defaultMaxIdleConnsPerHost\n\t}\n\t// parse URL:\n\tu, err := url.Parse(config.URL)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing config.URL: %s\", err)\n\t}\n\tif u.Scheme != \"http\" && u.Scheme != \"https\" {\n\t\treturn nil, fmt.Errorf(\"config.URL scheme must be http(s), got %s\", u.Scheme)\n\t}\n\n\tvar transport http.Transport\n\tif len(config.HTTPProxy) > 0 {\n\t\tproxyURL, err := url.Parse(config.HTTPProxy)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error parsing config.HTTPProxy: %s\", err)\n\t\t}\n\n\t\ttransport = http.Transport{\n\t\t\tProxy: http.ProxyURL(proxyURL),\n\t\t\tMaxIdleConnsPerHost: config.MaxIdleConnsPerHost,\n\t\t}\n\t} else {\n\t\ttransport = http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tMaxIdleConnsPerHost: config.MaxIdleConnsPerHost,\n\t\t}\n\t}\n\n\treturn &httpClient{\n\t\twriteURL: writeURL(u, defaultWP),\n\t\tconfig: config,\n\t\turl: u,\n\t\tclient: &http.Client{\n\t\t\tTimeout: config.Timeout,\n\t\t\tTransport: &transport,\n\t\t},\n\t}, nil\n}", "func newHTTPClient(count int) *client {\n\treturn &client{\n\t\tcli: &http.Client{\n\t\t\tTimeout: time.Second * 5,\n\t\t},\n\t\tworkers: count,\n\t\t//can be different size\n\t\terrChan: make(chan error, count),\n\t\tseen: make(map[int]struct{}),\n\t\tpath: \"http://host.docker.internal:9010/objects/\",\n\t}\n}", "func NewHTTP(token, api string) (*API, error) {\n\treturn &API{\n\t\tToken: token,\n\t\tAPI: api,\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDial: (&net.Dialer{\n\t\t\t\t\tTimeout: time.Duration(Timeout) * time.Second,\n\t\t\t\t}).Dial,\n\t\t\t\tTLSHandshakeTimeout: time.Duration(Timeout) * time.Second,\n\t\t\t},\n\t\t\tTimeout: time.Second * time.Duration(Timeout),\n\t\t},\n\t}, nil\n}", "func NewHTTPClient(instance string, otTracer stdopentracing.Tracer, zipkinTracer *stdzipkin.Tracer, logger log.Logger) (service.AddsvcService, error) { // Quickly sanitize the instance string.\n\tif !strings.HasPrefix(instance, \"http\") {\n\t\tinstance = \"http://\" + instance\n\t}\n\tu, err := url.Parse(instance)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// We construct a single ratelimiter middleware, to limit the total outgoing\n\t// QPS from this client to all methods on the remote instance. We also\n\t// construct per-endpoint circuitbreaker middlewares to demonstrate how\n\t// that's done, although they could easily be combined into a single breaker\n\t// for the entire remote instance, too.\n\tlimiter := ratelimit.NewErroringLimiter(rate.NewLimiter(rate.Every(time.Second), 100))\n\n\t// Zipkin HTTP Client Trace can either be instantiated per endpoint with a\n\t// provided operation name or a global tracing client can be instantiated\n\t// without an operation name and fed to each Go kit endpoint as ClientOption.\n\t// In the latter case, the operation name will be the endpoint's http method.\n\tzipkinClient := zipkin.HTTPClientTrace(zipkinTracer)\n\n\t// global client middlewares\n\toptions := []httptransport.ClientOption{\n\t\tzipkinClient,\n\t}\n\n\te := endpoints.Endpoints{}\n\n\t// Each individual endpoint is an http/transport.Client (which implements\n\t// endpoint.Endpoint) that gets wrapped with various middlewares. If you\n\t// made your own client library, you'd do this work there, so your server\n\t// could rely on a consistent set of client behavior.\n\t// The Sum endpoint is the same thing, with slightly different\n\t// middlewares to demonstrate how to specialize per-endpoint.\n\tvar sumEndpoint endpoint.Endpoint\n\t{\n\t\tsumEndpoint = httptransport.NewClient(\n\t\t\t\"POST\",\n\t\t\tcopyURL(u, \"/sum\"),\n\t\t\tencodeHTTPSumRequest,\n\t\t\tdecodeHTTPSumResponse,\n\t\t\tappend(options, httptransport.ClientBefore(opentracing.ContextToHTTP(otTracer, logger)))...,\n\t\t).Endpoint()\n\t\tsumEndpoint = opentracing.TraceClient(otTracer, \"Sum\")(sumEndpoint)\n\t\tsumEndpoint = zipkin.TraceEndpoint(zipkinTracer, \"Sum\")(sumEndpoint)\n\t\tsumEndpoint = limiter(sumEndpoint)\n\t\tsumEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{\n\t\t\tName: \"Sum\",\n\t\t\tTimeout: 30 * time.Second,\n\t\t}))(sumEndpoint)\n\t\te.SumEndpoint = sumEndpoint\n\t}\n\n\t// The Concat endpoint is the same thing, with slightly different\n\t// middlewares to demonstrate how to specialize per-endpoint.\n\tvar concatEndpoint endpoint.Endpoint\n\t{\n\t\tconcatEndpoint = httptransport.NewClient(\n\t\t\t\"POST\",\n\t\t\tcopyURL(u, \"/concat\"),\n\t\t\tencodeHTTPConcatRequest,\n\t\t\tdecodeHTTPConcatResponse,\n\t\t\tappend(options, httptransport.ClientBefore(opentracing.ContextToHTTP(otTracer, logger)))...,\n\t\t).Endpoint()\n\t\tconcatEndpoint = opentracing.TraceClient(otTracer, \"Concat\")(concatEndpoint)\n\t\tconcatEndpoint = zipkin.TraceEndpoint(zipkinTracer, \"Concat\")(concatEndpoint)\n\t\tconcatEndpoint = limiter(concatEndpoint)\n\t\tconcatEndpoint = circuitbreaker.Gobreaker(gobreaker.NewCircuitBreaker(gobreaker.Settings{\n\t\t\tName: \"Concat\",\n\t\t\tTimeout: 30 * time.Second,\n\t\t}))(concatEndpoint)\n\t\te.ConcatEndpoint = concatEndpoint\n\t}\n\n\t// Returning the endpoint.Set as a service.Service relies on the\n\t// endpoint.Set implementing the Service methods. That's just a simple bit\n\t// of glue code.\n\treturn e, nil\n}", "func newAPIClient(opts *ClientOpts) (*APIClient, error) {\n\tconfig := &rest.Config{\n\t\tHost: opts.URL,\n\t\tUsername: opts.Username,\n\t\tPassword: opts.Password,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t\tBearerToken: opts.BearerToken,\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &APIClient{\n\t\tclientSet: client,\n\t}, nil\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func NewHTTPClient(url string, backend Backend) (*HTTPClient, error) {\n b := backend\n if b == nil {\n b = newDefaultBackend()\n }\n return &HTTPClient{url: url, backend: b}, nil\n}", "func New(client *http.Client, maxBytes int64, metricsName string, authorizer Authorizer, gatherKubeConfig *rest.Config) *Client {\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tif maxBytes == 0 {\n\t\tmaxBytes = 10 * 1024 * 1024\n\t}\n\treturn &Client{\n\t\tclient: client,\n\t\tmaxBytes: maxBytes,\n\t\tmetricsName: metricsName,\n\t\tauthorizer: authorizer,\n\t\tgatherKubeConfig: gatherKubeConfig,\n\t}\n}", "func NewHTTPClient(apiEndpoint string, pageSize int64, setAuth func(r *http.Request)) *APIClient {\n\treturn &APIClient{\n\t\tconn: connector.NewHTTPConnector(apiEndpoint, pageSize, setAuth),\n\t}\n}", "func NewWithHTTP(transport *http.Transport) *KodderClient {\n\tcli := &http.Client{Transport: transport}\n\treturn &KodderClient{\n\t\tWorkerLog: defaultWorkerLog,\n\t\tHTTPDo: cli.Do,\n\t}\n}", "func NewHTTP(cfg config.Config) *HTTP {\n\tclient := &http.Client{\n\t\tTimeout: cfg.Timeout,\n\t}\n\treturn &HTTP{\n\t\tclient: client,\n\t\tconfig: cfg,\n\t}\n}", "func NewHTTPClient() *http.Client {\n\n\ttr := &http.Transport{\n\t\t//TLSClientConfig: &tls.Config{\n\t\t//\tInsecureSkipVerify: conf.InsecureSkipVerify,\n\t\t//},\n\t\tMaxIdleConnsPerHost: DefaultMaxIdleConnsPerHost,\n\t\tProxy: http.ProxyFromEnvironment,\n\t\tDial: (&net.Dialer{\n\t\t\tTimeout: DefaultTimeout,\n\t\t\tKeepAlive: DefaultKeepAlive,\n\t\t}).Dial,\n\t\tTLSHandshakeTimeout: DefaultTimeout,\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: DefaultTimeout,\n\t\tTransport: tr,\n\t}\n}", "func NewHTTPClient(formats strfmt.Registry) *V3 {\n\treturn NewHTTPClientWithConfig(formats, nil)\n}", "func NewHTTPClient() *HTTPClient {\n\treturn &HTTPClient{\n\t\tClient: http.DefaultClient,\n\t\tCacheDir: viper.GetString(\"http_cache_dir\"),\n\t}\n}", "func newCloudlyckeClient() *http.Client {\n\treturn &http.Client{}\n}", "func newKubeClient() kubernetes.Interface {\n\tvar kubeconfig string\n\tif _, err := os.Stat(clientcmd.RecommendedHomeFile); err == nil {\n\t\tkubeconfig = clientcmd.RecommendedHomeFile\n\t}\n\tlog.Debugf(\"use config file %s\", kubeconfig)\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"build config failed: %v\", err)\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize kubernetes client failed: %v\", err)\n\t}\n\tlog.Infof(\"Connected to cluster at %s\", config.Host)\n\n\treturn client\n}", "func (rpc *RpcClient) newHTTPClient() (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: 5 * time.Second,\n\t\t\t\tKeepAlive: 5 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t},\n\t}\n\treturn &client, nil\n}", "func NewHTTPClient(rawURL string) (Client, error) {\n\tURL, err := url.Parse(rawURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &HTTPClient{\n\t\tComponent: Component{Name: \"http-config-client-\" + URL.Host},\n\t\tURL: rawURL,\n\t}, nil\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func NewHTTPClient(uri string) HTTPClient {\n\treturn HTTPClient{\n\t\tBackendURI: uri,\n\t\tclient: &http.Client{},\n\t}\n}", "func doKubeRequest(ctx context.Context, r *http.Request) (*http.Response, error) {\n\tif kubeHTTP == nil {\n\t\tpanic(\"not in kubernetes\")\n\t}\n\n\tr.URL.Scheme = \"https\"\n\tr.URL.Host = kubeHost\n\tr.Header.Set(\"Authorization\", \"Bearer \"+kubeToken)\n\tr.Header.Set(\"Accept\", \"application/json\")\n\n\tresp, err := kubeHTTP.RoundTrip(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {\n\t\treturn resp, fmt.Errorf(\"got non-200/201 status code %d\", resp.StatusCode)\n\t}\n\treturn resp, nil\n}", "func NewHTTPClient(client *http.Client) *DockerHubClient {\n\tif client == nil {\n\t\tclient = http.DefaultClient\n\t}\n\n\tapiVersion := os.Getenv(dockerHubAPIVersion)\n\tif apiVersion == \"\" {\n\t\tapiVersion = defaultAPIVersion\n\t}\n\n\thubURLAddr := os.Getenv(dockerHubURL)\n\tif hubURLAddr == \"\" {\n\t\thubURLAddr = defaultHubURL\n\t}\n\thubURL, err := url.Parse(hubURLAddr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc := &DockerHubClient{\n\t\tClient: client,\n\t\tUserAgent: \"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:15.0) Gecko/20100101 Firefox/15.0.1\",\n\t\tAPIVersion: apiVersion,\n\t\tHubURL: hubURL,\n\t}\n\n\treturn c\n}", "func NewHTTP(base mb.BaseMetricSet) (*HTTP, error) {\n\tconfig := defaultConfig()\n\tif err := base.Module().UnpackConfig(&config); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newHTTPFromConfig(config, base.Name(), base.HostData())\n}", "func newClient(certFile, keyFile string) (*http.Client, error) {\n\tcaCert, err := ioutil.ReadFile(\"/etc/insights-client/cert-api.access.redhat.com.pem\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaCertPool, err := x509.SystemCertPool()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcaCertPool.AppendCertsFromPEM(caCert)\n\n\tcert, err := tls.LoadX509KeyPair(certFile, keyFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttlsConfig := tls.Config{\n\t\tRootCAs: caCertPool,\n\t\tCertificates: []tls.Certificate{cert},\n\t\tMaxVersion: tls.VersionTLS12, // cloud.redhat.com appears to exhibit this openssl bug https://github.com/openssl/openssl/issues/9767\n\t}\n\n\ttlsConfig.BuildNameToCertificate()\n\ttransport := http.Transport{\n\t\tTLSClientConfig: &tlsConfig,\n\t}\n\tclient := http.Client{\n\t\tTransport: &transport,\n\t}\n\treturn &client, nil\n}", "func NewHTTP(port uint16, pachClientFactory func(ctx context.Context) *client.APIClient) *HTTP {\n\tmux := http.NewServeMux()\n\thandler := &Server{\n\t\tpachClientFactory: pachClientFactory,\n\t}\n\tmux.Handle(\"/archive/\", CSRFWrapper(handler))\n\tmux.Handle(\"/healthz\", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"healthy\\n\")) //nolint:errcheck\n\t}))\n\treturn &HTTP{\n\t\tmux: mux,\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", port),\n\t\t\tHandler: mux,\n\t\t},\n\t}\n}", "func createHTTPClient() *http.Client {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\tMaxIdleConnsPerHost: 1,\n\t\tDisableKeepAlives: true,\n\t}\n\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tTimeout: time.Second * 60,\n\t}\n}", "func NewHTTPClient(serverEndpoint string, ticket *obtainer.Client) (*HTTPClient, error) {\n\n\tendpointUrl, err := url.Parse(serverEndpoint)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error parsing endpoint: %s\", err)\n\t}\n\n\treturn &HTTPClient{\n\t\tserverEndpoint: endpointUrl,\n\t\tticket: ticket,\n\t}, nil\n}", "func newHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTimeout: defaultTimeout,\n\t}\n\treturn client\n}", "func NewHTTPClient(skipVerify bool, certPath string) (*http.Client, error) {\n\ttlsConfig := &tls.Config{\n\t\tInsecureSkipVerify: skipVerify,\n\t}\n\n\tif !skipVerify && certPath != \"\" {\n\t\tcert, err := os.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcertPool, err := x509.SystemCertPool()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"WARN: unable to get system cert pool: %v\\n\", err)\n\t\t\tcertPool = x509.NewCertPool()\n\t\t}\n\t\tcertPool.AppendCertsFromPEM(cert)\n\t\ttlsConfig.RootCAs = certPool\n\t}\n\n\treturn &http.Client{\n\t\tTimeout: 2 * time.Minute,\n\t\tTransport: &http.Transport{\n\t\t\tIdleConnTimeout: 2 * time.Minute,\n\t\t\tResponseHeaderTimeout: 2 * time.Minute,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t}}, nil\n}", "func NewHTTP() *HTTP {\n\treturn HTTPPool.Get().(*HTTP)\n}", "func (rpc *RpcClient) newHTTPClient() (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\tif rpc.Cfg.OptionConfig.Proxy != \"\" {\n\t\tproxy := &socks.Proxy{\n\t\t\tAddr: rpc.Cfg.OptionConfig.Proxy,\n\t\t\tUsername: rpc.Cfg.OptionConfig.ProxyUser,\n\t\t\tPassword: rpc.Cfg.OptionConfig.ProxyPass,\n\t\t}\n\t\tdial = func(network, addr string) (net.Conn, error) {\n\t\t\tc, err := proxy.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\tif !rpc.Cfg.SoloConfig.NoTLS && rpc.Cfg.SoloConfig.RPCCert != \"\" {\n\t\tpem, err := ioutil.ReadFile(rpc.Cfg.SoloConfig.RPCCert)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tpool := x509.NewCertPool()\n\t\tpool.AppendCertsFromPEM(pem)\n\t\ttlsConfig = &tls.Config{\n\t\t\tRootCAs: pool,\n\t\t\tInsecureSkipVerify: rpc.Cfg.SoloConfig.NoTLS,\n\t\t}\n\t} else {\n\t\ttlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: rpc.Cfg.SoloConfig.NoTLS,\n\t\t}\n\t}\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: time.Duration(rpc.Cfg.OptionConfig.Timeout) * time.Second,\n\t\t\t\tKeepAlive: time.Duration(rpc.Cfg.OptionConfig.Timeout) * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\t\t},\n\t}\n\treturn &client, nil\n}", "func createKubeClient() (kubernetes.Interface, error) {\n\tif mockedController {\n\t\treturn fake.NewSimpleClientset(), nil\n\t}\n\tkubeconfig, ok := os.LookupEnv(EnvLiqoKConfig)\n\tif !ok || kubeconfig == \"\" {\n\t\treturn nil, errors.New(\"no kubeconfig provided\")\n\t}\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(cfg)\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{}\n\tif insecure {\n\t\thttp.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}\n\t}\n\treturn client\n}", "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func newHTTPClient(cfg *OutboundCommConfig) (*http.Client, error) {\n\tvar err error\n\tvar caCertPool tlsCertPool.CertPool\n\tif cfg.CACertsPaths != \"\" {\n\t\tcaCertPool, err = tlsCertPool.NewCertPool(false)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"Failed to create new Cert Pool\")\n\t\t}\n\n\t\tcaCertsPaths := strings.Split(cfg.CACertsPaths, \",\")\n\t\tvar caCerts []string\n\t\tfor _, path := range caCertsPaths {\n\t\t\tif path == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// Create a pool with server certificates\n\t\t\tcaCert, e := ioutil.ReadFile(filepath.Clean(path))\n\t\t\tif e != nil {\n\t\t\t\treturn nil, errors.Wrap(e, \"Failed Reading server certificate\")\n\t\t\t}\n\t\t\tcaCerts = append(caCerts, string(caCert))\n\t\t}\n\n\t\tcaCertPool.Add(tlsCertPool.DecodeCerts(caCerts)...)\n\t} else {\n\t\tcaCertPool, err = tlsCertPool.NewCertPool(true)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// update the config's caCertPool\n\tcfg.caCertPool = caCertPool\n\n\ttlsConfig, err := buildNewCertPool(cfg.caCertPool)\n\tif err != nil {\n\t\tlog.Printf(\"HTTP Transport - Failed to build/get Cert Pool: %s\", err)\n\t\treturn nil, err\n\t}\n\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t\tTimeout: cfg.Timeout,\n\t}, nil\n}", "func newHTTPClient(\n\tapiKey string,\n\tdebug bool,\n\tomitRetry bool,\n\ttimeout time.Duration,\n\ttransport http.RoundTripper,\n) httpC {\n\tif transport == nil {\n\t\ttransport = http.DefaultTransport\n\t}\n\treturn &gcmHTTP{\n\t\tGCMURL: httpAddress,\n\t\tapiKey: apiKey,\n\t\thttpClient: &http.Client{\n\t\t\tTransport: transport,\n\t\t\tTimeout: timeout,\n\t\t},\n\t\tdebug: debug,\n\t\tomitRetry: omitRetry,\n\t}\n}", "func NewClient(address string) (KubeClient, error) {\n\t// create tls client\n\tcacertFile := \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\n\tcapem, err := ioutil.ReadFile(cacertFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcacert := x509.NewCertPool()\n\tif !cacert.AppendCertsFromPEM(capem) {\n\t\treturn nil, fmt.Errorf(\"unable to load certificate authority\")\n\t}\n\tconfig := &tls.Config{RootCAs: cacert}\n\ttransport := &http.Transport{TLSClientConfig: config}\n\n\t// read token\n\tclient := &http.Client{Transport: transport}\n\ttokenFile := \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\ttoken, err := ioutil.ReadFile(tokenFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &realKubeClient{client, address, string(token)}, nil\n}", "func newKubeClientConfig() (*client.Config, error) {\n\tvar (\n\t\tconfig *client.Config\n\t\terr error\n\t\tapiServerURL string\n\t)\n\t// If the user specified --kube-apiserver-url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tapiServerURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif apiServerURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube-apiserver-url was provided.\n\t\tconfig = &client.Config{\n\t\t\tHost: apiServerURL,\n\t\t\tVersion: \"v1\",\n\t\t}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube-apiserver-url and --kubecfg-file\n\t\t// 2) just --kubecfg-file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &clientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = apiServerURL // might be \"\", but that is OK\n\t\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tglog.Infof(\"Using %s for kubernetes API server\", config.Host)\n\tglog.Infof(\"Using kubernetes API version %s\", config.Version)\n\n\treturn config, nil\n}", "func NewHTTP(config Config) (Type, error) {\n\tvar jsonRoot, json *gabs.Container\n\tvar pathPrefix string\n\n\tjsonRoot = gabs.New()\n\tif len(config.HTTP.Prefix) > 0 {\n\t\tpathPrefix = config.HTTP.Prefix + \".\"\n\t\tjson, _ = jsonRoot.ObjectP(config.HTTP.Prefix)\n\t} else {\n\t\tjson = jsonRoot\n\t}\n\n\tt := &HTTP{\n\t\tconfig: config.HTTP,\n\t\tjsonRoot: jsonRoot,\n\t\tjson: json,\n\t\tflatMetrics: map[string]int64{},\n\t\tpathPrefix: pathPrefix,\n\t\ttimestamp: time.Now(),\n\t}\n\n\tgo func() {\n\t\tmux := http.NewServeMux()\n\t\tmux.HandleFunc(config.HTTP.Path, t.JSONHandler())\n\n\t\thttp.ListenAndServe(config.HTTP.Address, mux)\n\t}()\n\n\treturn t, nil\n}", "func NewKubeclient(log *logrus.Entry, config *v1.Config, pluginConfig *api.PluginConfig) (Kubeclient, error) {\n\trestconfig, err := managedcluster.RestConfigFromV1Config(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcli, err := kubernetes.NewForConfig(restconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubeclient{\n\t\tpluginConfig: *pluginConfig,\n\t\tlog: log,\n\t\tclient: cli,\n\t}, nil\n\n}", "func NewHTTPClient(options ...Opt) *HTTP {\n\tc := &HTTP{\n\t\tHTTPClient: &http.Client{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(c)\n\t}\n\n\tif c.latestManifestURLFmt == \"\" {\n\t\tc.latestManifestURLFmt = defaultLatestManifestURLFmt\n\t}\n\n\tif c.manifestURLFmt == \"\" {\n\t\tc.manifestURLFmt = defaultManifestURLFmt\n\t}\n\n\treturn c\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: 15,\n\t\t},\n\t\tTimeout: time.Duration(10) * time.Second,\n\t}\n\n\treturn client\n}", "func NewClient(host string, path string, timeout time.Duration) *Client {\n\tlog.Debug(\"Creating a new instance of the Mesos plugin HTTP client\")\n\treturn &Client{\n\t\thttpClient: &http.Client{Timeout: timeout},\n\t\thost: host,\n\t\tpath: path,\n\t}\n}", "func CreateHTTPClient(roundTripper func(*http.Request) (*http.Response, error)) *http.Client {\n\treturn &http.Client{\n\t\tTransport: roundTripperFunc(roundTripper),\n\t}\n}", "func NewHTTPClient(slog slog.Logger, filer sio.Filer) (clt Client, err error) {\n\thttpClt := &HTTPClient{logger: slog}\n\thttpClt.client = httpClt\n\thttpClt.filer = filer\n\treturn httpClt.client, nil\n}", "func NewHTTPClient(formats strfmt.Registry) *DivvyCloudV2 {\n\treturn NewHTTPClientWithConfig(formats, nil)\n}", "func New(CABundleFile, CABundleDir string, httpTimeout time.Duration) (*http.Client, error) {\n\treturn _new(CABundleFile, CABundleDir, httpTimeout, \"\")\n}", "func New(url string, httpClient *http.Client, customHeaders http.Header) *Client {\n\tif httpClient == nil {\n\t\thttpClient = &http.Client{\n\t\t\tTimeout: defaultHTTPTimeout,\n\t\t}\n\t}\n\n\treturn &Client{\n\t\turl: url,\n\t\thttpClient: httpClient,\n\t\tcustomHeaders: customHeaders,\n\t}\n}", "func NewHTTPClient(url, endpoint string, timeout time.Duration) *HTTPClient {\n\treturn &HTTPClient{\n\t\turl: url,\n\t\thttpClient: &http.Client{Timeout: timeout},\n\t\tendPoint: endpoint,\n\t}\n}", "func NewHTTPClient(conn net.Conn, opt *codec.Option) (*Client, error) {\n\t_, _ = io.WriteString(conn, fmt.Sprintf(\"CONNECT %s HTTP/1.0\\n\\n\", defaultHandlePath))\n\n\tres, err := http.ReadResponse(bufio.NewReader(conn), &http.Request{Method: \"CONNECT\"})\n\tif err == nil && res.Status == \"200 Connected to Gingle RPC\" {\n\t\treturn NewRPCClient(conn, opt)\n\t}\n\n\tif err == nil {\n\t\terr = fmt.Errorf(\"client: failed to new http client, err: unexpected http response\")\n\t}\n\treturn nil, err\n}", "func newHTTPClient() *http.Client {\n\treturn &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tProxy: http.ProxyFromEnvironment,\n\t\t\tDialContext: (&net.Dialer{\n\t\t\t\tTimeout: timeout,\n\t\t\t\tKeepAlive: 30 * time.Second,\n\t\t\t\tDualStack: true,\n\t\t\t}).DialContext,\n\n\t\t\tTLSHandshakeTimeout: timeout,\n\t\t\tResponseHeaderTimeout: timeout,\n\t\t\tExpectContinueTimeout: 1 * time.Second,\n\t\t\tMaxIdleConns: 5,\n\t\t\tIdleConnTimeout: 90 * time.Second,\n\t\t},\n\t}\n}", "func NewHTTPClient(formats strfmt.Registry) *CiliumHealthAPI {\n\treturn NewHTTPClientWithConfig(formats, nil)\n}", "func newHTTPHandler(c ServiceController, k8sStorage ServiceStorage) *httpHandler {\n\treturn &httpHandler{\n\t\tcontroller: c,\n\t\tk8sStorage: k8sStorage,\n\t}\n}", "func CreateHTTPSClient(handler http.Handler) (*http.Client, string, func()) {\n\n\tserver := httptest.NewTLSServer(handler)\n\n\tcert, err := x509.ParseCertificate(server.TLS.Certificates[0].Certificate[0])\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Could not parse certificate\")\n\t}\n\n\tcertpool := x509.NewCertPool()\n\tcertpool.AddCert(cert)\n\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDialContext: func(_ context.Context, network, _ string) (net.Conn, error) {\n\t\t\t\treturn net.Dial(network, server.Listener.Addr().String())\n\t\t\t},\n\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\tRootCAs: certpool,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn client, server.URL, server.Close\n}", "func createHTTPClient() *http.Client {\n\tclient := &http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tMaxIdleConnsPerHost: MaxIdleConnections,\n\t\t},\n\t\tTimeout: time.Duration(RequestTimeout) * time.Second,\n\t}\n\n\treturn client\n}", "func NewHTTPClient(timeout time.Duration) *http.Client {\n\treturn &http.Client{\n\t\tTimeout: timeout,\n\t}\n}", "func New(kubeconfig, opImage string) (*Framework, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"build config from flags failed\")\n\t}\n\n\tcli, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating new kube-client failed\")\n\t}\n\n\thttpc := cli.CoreV1().RESTClient().(*rest.RESTClient).Client\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating http-client failed\")\n\t}\n\n\tmaegusClientV1, err := maegusclient.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating v1 maegus client failed\")\n\t}\n\n\tapiextensionsClientV1, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating v1 apiextensions client failed\")\n\t}\n\n\tf := &Framework{\n\t\tMasterHost: config.Host,\n\t\tMaegusClientV1: maegusClientV1,\n\t\tApiextensionsClientV1: apiextensionsClientV1,\n\t\tKubeClient: cli,\n\t\tHTTPClient: httpc,\n\t\tDefaultTimeout: time.Minute,\n\t}\n\n\treturn f, nil\n}", "func ConfigureHTTP(h *HTTP) *HTTP {\n\tselector := map[string]string{\n\t\t\"app.kubernetes.io/name\": \"tunnel.http\",\n\t\t\"app.kubernetes.io/instance\": h.Key.Name,\n\t}\n\n\th.Service.Object.Spec = corev1.ServiceSpec{\n\t\tType: corev1.ServiceTypeClusterIP,\n\t\tPorts: []corev1.ServicePort{\n\t\t\t{\n\t\t\t\tName: \"proxy-http\",\n\t\t\t\tTargetPort: intstr.FromString(\"proxy-http\"),\n\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\tPort: 80,\n\t\t\t},\n\t\t},\n\t\tSelector: selector,\n\t}\n\n\th.Pod.Object.ObjectMeta.Labels = selector\n\th.Pod.Object.Spec = corev1.PodSpec{\n\t\tContainers: []corev1.Container{\n\t\t\t{\n\t\t\t\tName: \"tunnel\",\n\t\t\t\tImage: HTTPImage,\n\t\t\t\tArgs: []string{\n\t\t\t\t\t\"server\",\n\t\t\t\t\t\"--port\", \"8000\",\n\t\t\t\t\t\"--control-port\", \"8080\",\n\t\t\t\t},\n\t\t\t\tPorts: []corev1.ContainerPort{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"proxy-http\",\n\t\t\t\t\t\tContainerPort: 8000,\n\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"tunnel\",\n\t\t\t\t\t\tContainerPort: 8080,\n\t\t\t\t\t\tProtocol: corev1.ProtocolTCP,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tLivenessProbe: &corev1.Probe{\n\t\t\t\t\tHandler: corev1.Handler{\n\t\t\t\t\t\tTCPSocket: &corev1.TCPSocketAction{\n\t\t\t\t\t\t\tPort: intstr.FromString(\"tunnel\"),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\treturn h\n}", "func NewClient() *Client {\n\tvar client Client\n\ttr := &http.Transport{\n\t\tDisableCompression: true,\n\t\tProxy: http.ProxyFromEnvironment,\n\t}\n\n\tclient.client = &http.Client{Transport: tr}\n\tclient.UserAgent = fmt.Sprintf(\"KUTTL/%s\", strings.TrimPrefix(version.Get().GitVersion, \"v\"))\n\treturn &client\n}", "func NewHttpClient(endpoint, token string) (client *HttpClient) {\n\treturn newHttpClient(endpoint, token, false)\n}", "func NewHTTPClient() *http.Client {\n\ttr := &http.Transport{\n\t\tTLSClientConfig: &tls.Config{\n\t\t\tInsecureSkipVerify: true, //nolint:gosec // Needs to be enabled in suites. Not used in production.\n\t\t},\n\t}\n\n\treturn &http.Client{\n\t\tTransport: tr,\n\t\tCheckRedirect: func(req *http.Request, via []*http.Request) error {\n\t\t\treturn http.ErrUseLastResponse\n\t\t},\n\t}\n}", "func newHTTPClient(cfg *Config) (*http.Client, error) {\n\t// Configure proxy if needed.\n\tvar dial func(network, addr string) (net.Conn, error)\n\tif cfg.Proxy != \"\" {\n\t\tproxy := &socks.Proxy{\n\t\t\tAddr: cfg.Proxy,\n\t\t\tUsername: cfg.ProxyUser,\n\t\t\tPassword: cfg.ProxyPass,\n\t\t}\n\t\tdial = func(network, addr string) (net.Conn, error) {\n\t\t\tc, err := proxy.Dial(network, addr)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn c, nil\n\t\t}\n\t}\n\n\t// Configure TLS if needed.\n\tvar tlsConfig *tls.Config\n\tif !cfg.NoTLS {\n\t\ttlsConfig = &tls.Config{\n\t\t\tInsecureSkipVerify: cfg.TLSSkipVerify,\n\t\t}\n\t\tif !cfg.TLSSkipVerify && cfg.RPCCert != \"\" {\n\t\t\tpem, err := ioutil.ReadFile(cfg.RPCCert)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tpool := x509.NewCertPool()\n\t\t\tif ok := pool.AppendCertsFromPEM(pem); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"invalid certificate file: %v\",\n\t\t\t\t\tcfg.RPCCert)\n\t\t\t}\n\t\t\ttlsConfig.RootCAs = pool\n\t\t}\n\t}\n\n\ttimeout, _ := time.ParseDuration(\"30s\")\n\n\t// Create and return the new HTTP client potentially configured with a\n\t// proxy and TLS.\n\tclient := http.Client{\n\t\tTransport: &http.Transport{\n\t\t\tDial: dial,\n\t\t\tTLSClientConfig: tlsConfig,\n\t\t},\n\t\tTimeout: timeout,\n\t}\n\treturn &client, nil\n}", "func NewHTTPClient(proxyNetwork, proxyAddress string, serviceNetwork, service string) http.Client {\n\tproxyClient := Client{proxyNetwork: proxyNetwork, proxyAddress: proxyAddress, serviceNetwork: serviceNetwork, service: service}\n\ttrans := &http.Transport{\n\t\tDial: proxyClient.proxyDial,\n\t\tDisableKeepAlives: false,\n\t}\n\treturn http.Client{Transport: trans}\n}", "func NewHTTPClient(cfgFile string) (*HTTPClient, error) {\n\tcfg, err := config.LoadConfig(cfgFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewHTTPClientFromConfig(cfg)\n}", "func NewClient(mac *Mac, transport http.RoundTripper) *http.Client {\n\n\tt := NewTransport(mac, transport)\n\treturn &http.Client{Transport: t}\n}", "func NewClient(prefix string, apiVersion string, version string,\n\ttoken TokenHolder, t http.RoundTripper) *Client {\n\n\trt := &registryRoundTripper{\n\t\tDefaultRequestDoer: DefaultRequestDoer{\n\t\t\tClient: &http.Client{\n\t\t\t\tTransport: t,\n\t\t\t\tTimeout: time.Minute,\n\t\t\t},\n\t\t\tHost: prefix,\n\t\t},\n\n\t\tapiVersion: apiVersion,\n\t\tversion: version,\n\t\tholder: token,\n\t}\n\n\treturn NewClientWithRoundTripper(rt)\n}", "func NewHTTPClient(formats strfmt.Registry) *JusticePlatformService {\n\treturn NewHTTPClientWithConfig(formats, nil)\n}", "func NewHTTPClient() (*HTTPClient, error) {\n\tresp, err := http.Get(\"https://raw.githubusercontent.com/cvandeplas/pystemon/master/user-agents.txt\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer resp.Body.Close()\n\tb, err := ioutil.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create the client and attach a cookie jar\n\tclient := &http.Client{}\n\tclient.Jar, _ = cookiejar.New(nil)\n\n\t// Splits the user-agents into a slice and returns an HTTPClient with a random\n\t// user-agent on the header\n\tua := strings.Split(string(b), \"\\n\")\n\trand.Seed(time.Now().UnixNano())\n\treturn &HTTPClient{\n\t\tClient: client,\n\t\tUserAgent: ua[rand.Intn(len(ua))],\n\t}, nil\n}", "func NewKubeClient(kubeCfgFile string) (*k8sclient.Clientset, error) {\n\n\tconfig, err := BuildConfig(kubeCfgFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//TODO refactor & log errors\n\treturn k8sclient.NewForConfig(config)\n}", "func (c *Command) HTTPClient() (*api.Client, error) {\n\tif !c.hasClientHTTP() && !c.hasServerHTTP() {\n\t\tpanic(\"no http flags defined\")\n\t}\n\tif !c.flagSet.Parsed() {\n\t\tpanic(\"flags have not been parsed\")\n\t}\n\n\tconfig := api.DefaultConfig()\n\tc.httpAddr.Merge(&config.Address)\n\tc.token.Merge(&config.Token)\n\tc.caFile.Merge(&config.TLSConfig.CAFile)\n\tc.caPath.Merge(&config.TLSConfig.CAPath)\n\tc.certFile.Merge(&config.TLSConfig.CertFile)\n\tc.keyFile.Merge(&config.TLSConfig.KeyFile)\n\tc.tlsServerName.Merge(&config.TLSConfig.Address)\n\tc.datacenter.Merge(&config.Datacenter)\n\treturn api.NewClient(config)\n}", "func NewHTTPSClient(cert string) (*http.Client, error) {\n\tcas := x509.NewCertPool()\n\tpemData, err := ioutil.ReadFile(filepath.Join(cert, \"ca.pem\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//add to pool and configrue tls\n\tcas.AppendCertsFromPEM(pemData)\n\n\t//load pair\n\tpair, err := tls.LoadX509KeyPair(filepath.Join(cert, \"cert.pem\"), filepath.Join(cert, \"key.pem\"))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//create new tls config with the created ca and pair\n\tconf := &tls.Config{\n\t\tRootCAs: cas,\n\t\tCertificates: []tls.Certificate{pair},\n\t}\n\n\t//create our own transport\n\ttr := &http.Transport{\n\t\tTLSClientConfig: conf,\n\t}\n\n\treturn &http.Client{Transport: tr}, nil\n}", "func newTestClient(fn RoundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func newTestClient(fn roundTripFunc) *http.Client {\n\treturn &http.Client{\n\t\tTransport: fn,\n\t}\n}", "func NewClient(baseURL string, apiKey string) Client {\n\treturn &httpClient{\n\t\tapiKey: apiKey,\n\t\tbaseURL: baseURL,\n\t\tinst: &http.Client{},\n\t}\n}", "func GetHTTPClient() *http.Client {\n tlsConfig := &tls.Config {\n InsecureSkipVerify: true, //for this test, ignore ssl certificate\n }\n\n tr := &http.Transport{TLSClientConfig: tlsConfig}\n client := &http.Client{Transport: tr}\n\n return client\n}", "func (c *clientProxy) createK8sClient() (kubernetes.Interface, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif c.kubeconfig == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", c.kubeconfig)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func NewRequestHTTP(order string, url string, values io.Reader)(resp *http.Response, err error){\n req, err := http.NewRequest(order, url, values)\n if err != nil {\n logs.Error(\"Error Executing HTTP new request\")\n }\n tr := &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, DisableKeepAlives: true,}\n client := &http.Client{Transport: tr}\n resp, err = client.Do(req)\n if err != nil {\n logs.Error(\"Error Retrieving response from client HTTP new request\")\n }\n return resp, err\n}", "func NewHTTPClient(transport http.RoundTripper, ts TokenSource) (*HTTPClient, error) {\n\tif ts == nil {\n\t\treturn nil, errors.New(\"gcp: no credentials available\")\n\t}\n\treturn &HTTPClient{\n\t\tClient: http.Client{\n\t\t\tTransport: &oauth2.Transport{\n\t\t\t\tBase: transport,\n\t\t\t\tSource: ts,\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func NewClient(pkg, auth string, timeout time.Duration) *Client {\n\theader := http.Header{}\n\theader.Set(\"Content-Type\", \"application/x-www-form-urlencoded\")\n\theader.Set(\"Authorization\", AuthPrefix+auth)\n\t// transport := &http.Transport{\n\t// \tProxy: func(_ *http.Request) (*url.URL, error) {\n\t// \t\treturn url.Parse(\"http://10.28.10.11:80\")\n\t// \t},\n\t// \tDialContext: (&net.Dialer{\n\t// \t\tTimeout: 30 * time.Second,\n\t// \t\tKeepAlive: 30 * time.Second,\n\t// \t\tDualStack: true,\n\t// \t}).DialContext,\n\t// \tMaxIdleConns: 100,\n\t// \tIdleConnTimeout: 90 * time.Second,\n\t// \tExpectContinueTimeout: 1 * time.Second,\n\t// }\n\treturn &Client{\n\t\tHeader: header,\n\t\tHTTPClient: &http.Client{Timeout: timeout},\n\t\t// HTTPClient: &http.Client{Timeout: timeout, Transport: transport},\n\t\tPackage: pkg,\n\t\tStats: prom.HTTPClient,\n\t}\n}", "func NewHTTPClient(ctx context.Context, clientSecretKeyFile []byte, tokenFilepath string) (*http.Client, error) {\n\tconfig, err := google.ConfigFromJSON(clientSecretKeyFile, builderAPIScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttokenCacheFilename := \"\"\n\tif tokenFilepath == \"\" {\n\t\ttokenCacheFilename, err = tokenCacheFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\ttokenCacheFilename = tokenFilepath\n\t}\n\tif !exists(tokenCacheFilename) {\n\t\tlog.Infoln(\"Could not locate OAuth2 token\")\n\t\treturn nil, errors.New(`command requires authentication. try to run \"gactions login\" first`)\n\t}\n\ttok, err := tokenFromFile(tokenCacheFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config.Client(ctx, tok), nil\n}", "func newAPI(cfg *ClientConfig, options ...ClientOption) *Client {\n\tclient := &Client{\n\t\tConfig: cfg,\n\t\thttpClient: &http.Client{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(client)\n\t}\n\n\treturn client\n}", "func GetHTTPClient() *http.Client {\r\n tlsConfig := &tls.Config {\r\n InsecureSkipVerify: true, //for this test, ignore ssl certificate\r\n }\r\n\r\n tr := &http.Transport{TLSClientConfig: tlsConfig}\r\n client := &http.Client{Transport: tr}\r\n\r\n return client\r\n}", "func NewClient(masterURL, kubeconfig string) (*kubernetes.Clientset, error) {\n\tvar config *rest.Config\n\tvar err error\n\tconfig, err = rest.InClusterConfig()\n\tif err != nil {\n\t\tzap.S().Info(\"could not perform incluster config. falling back to KUBECONFIG\")\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(masterURL, kubeconfig)\n\t}\n\tif err != nil {\n\t\tzap.S().Error(\"could not authenticate to cluster\\n\")\n\t\treturn nil, err\n\t}\n\n\treturn kubernetes.NewForConfig(config)\n}", "func CreateHTTPClient(requestURL string) (*Client, error) {\n\t_, err := url.ParseRequestURI(requestURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{\n\t\tHTTPClient: &http.Client{\n\t\t\tTimeout: time.Duration(requestTimeout) * time.Second,\n\t\t},\n\t\tbaseURL: requestURL,\n\t}, nil\n}", "func NewClient(kubeConfig *rest.Config) (client.Client, error) {\n\thttpClient, err := rest.HTTPClientFor(kubeConfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create http client: %v\", err)\n\t}\n\tmapper, err := apiutil.NewDiscoveryRESTMapper(kubeConfig, httpClient)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to discover api rest mapper: %v\", err)\n\t}\n\tkubeClient, err := client.New(kubeConfig, client.Options{\n\t\tScheme: scheme,\n\t\tMapper: mapper,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create kube client: %v\", err)\n\t}\n\treturn kubeClient, nil\n}", "func NewWithHTTP(url string, httpClient *http.Client) *Client {\n\treturn &Client{\n\t\tURL: url,\n\t\tHTTP: httpClient,\n\t}\n}", "func NewClient(meta *metadata.Client, acc string) *http.Client {\n\treturn &http.Client{\n\t\tTransport: newRoundTripper(meta, acc),\n\t}\n}", "func NewClient(config *latest.Config, kubeClient kubectl.Client, tillerNamespace string, log log.Logger) (types.Client, error) {\n\tif tillerNamespace == \"\" {\n\t\ttillerNamespace = kubeClient.Namespace()\n\t}\n\n\treturn &client{\n\t\tconfig: config,\n\n\t\tkubeClient: kubeClient,\n\t\ttillerNamespace: tillerNamespace,\n\n\t\texec: command.Command,\n\t\textract: extract.NewExtractor(),\n\t\thttpGet: http.Get,\n\n\t\tlog: log,\n\t}, nil\n}", "func NewKubeComponent() (api.Component, error) {\n\treturn &kubeComponent{}, nil\n}", "func NewHTTPClient(formats strfmt.Registry) *Jiskefet {\n\treturn NewHTTPClientWithConfig(formats, nil)\n}", "func NewClient(credentials NTLMCredentials, baseURL url.URL, stampID string) *Client {\n\thttpClient := http.Client{\n\t\tTransport: &httpntlm.NtlmTransport{\n\t\t\tTLSClientConfig: &tls.Config{InsecureSkipVerify: true},\n\t\t\tDomain: credentials.Domain,\n\t\t\tUser: credentials.Username,\n\t\t\tPassword: credentials.Password,\n\t\t},\n\t}\n\tclient := Client{baseURL: baseURL, client: httpClient, stampID: stampID}\n\tclient.Clouds = CloudService{\n\t\tgetting.NewCloudService(&httpClient, baseURL.String()+\"/Clouds\", stampID),\n\t}\n\tclient.VirtualHardDisks = VirtualHardDiskService{\n\t\tgetting.NewVirtualHardDiskService(&httpClient, baseURL.String()+\"/VirtualHardDisks\", stampID),\n\t}\n\tclient.VirtualMachines = VirtualMachineService{\n\t\tcreating.NewVirtualMachineService(&httpClient, baseURL.String()+\"/VirtualMachines\", stampID),\n\t\tdeleting.NewGenericDeleterService(&httpClient, baseURL.String()+\"/VirtualMachines\", stampID),\n\t\tgetting.NewVirtualMachineService(&httpClient, baseURL.String()+\"/VirtualMachines\", stampID),\n\t\tupdating.NewVirtualMachineService(&httpClient, baseURL.String()+\"/VirtualMachines\", stampID),\n\t}\n\tclient.VirtualDiskDrives = VirtualDiskDriveService{\n\t\tcreating.NewVirtualDiskDriveService(&httpClient, baseURL.String()+\"/VirtualDiskDrives\", stampID),\n\t\tdeleting.NewGenericDeleterService(&httpClient, baseURL.String()+\"/VirtualDiskDrives\", stampID),\n\t\tgetting.NewVirtualDiskDriveService(&httpClient, baseURL.String()+\"/VirtualDiskDrives\", stampID),\n\t}\n\tclient.Jobs = JobService{\n\t\tgetting.NewJobService(&httpClient, baseURL.String()+\"/Jobs\", stampID),\n\t\tupdating.NewJobService(&httpClient, baseURL.String()+\"/Jobs\", stampID),\n\t}\n\tclient.VMTemplates = VMTemplateService{\n\t\tgetting.NewVMTemplateService(&httpClient, baseURL.String()+\"/VMTemplates\", stampID),\n\t}\n\treturn &client\n}", "func NewClient(kubeconfig []byte) (Client, error) {\n\tc, err := NewClientset(kubeconfig)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed creating kubernetes clientset: %w\", err)\n\t}\n\n\treturn &client{c}, nil\n}", "func DefaultHTTPClientFactory(cc *cli.Context) (*http.Client, error) {\n\tif cc == nil {\n\t\tlogrus.Panic(\"cli context has not been set\")\n\t}\n\tvar c http.Client\n\tcookieJar, _ := cookiejar.New(nil)\n\n\tif cc.GlobalIsSet(\"apiSession\") {\n\t\tvar cookies []*http.Cookie\n\t\tcookie := &http.Cookie{\n\t\t\tName: \"SESSION\",\n\t\t\tValue: cc.GlobalString(\"apiSession\"),\n\t\t}\n\t\tcookies = append(cookies, cookie)\n\t\tu, _ := url.Parse(os.Getenv(\"SPINNAKER_API\"))\n\t\tcookieJar.SetCookies(u, cookies)\n\t}\n\n\tc = http.Client{\n\t\tTimeout: time.Duration(cc.GlobalInt(\"clientTimeout\")) * time.Second,\n\t\tJar: cookieJar,\n\t}\n\n\tvar certPath string\n\tvar keyPath string\n\n\n\tif cc.GlobalIsSet(\"certPath\") {\n\t\tcertPath = cc.GlobalString(\"certPath\")\n\t} else if os.Getenv(\"SPINNAKER_CLIENT_CERT\") != \"\" {\n\t\tcertPath = os.Getenv(\"SPINNAKER_CLIENT_CERT\")\n\t} else {\n\t\tcertPath = \"\"\n\t}\n\tif cc.GlobalIsSet(\"keyPath\") {\n\t\tkeyPath = cc.GlobalString(\"keyPath\")\n\t} else if os.Getenv(\"SPINNAKER_CLIENT_KEY\") != \"\" {\n\t\tkeyPath = os.Getenv(\"SPINNAKER_CLIENT_KEY\")\n\t} else {\n\t\tkeyPath = \"\"\n\t}\n\tif cc.GlobalIsSet(\"iapToken\") {\n\t\tiapToken = cc.GlobalString(\"iapToken\")\n\t} else if os.Getenv(\"SPINNAKER_IAP_TOKEN\") != \"\" {\n\t\tiapToken = os.Getenv(\"SPINNAKER_IAP_TOKEN\")\n\t} else {\n\t\tiapToken = \"\"\n\t}\n\tc.Transport = &http.Transport{\n\t\tTLSClientConfig: &tls.Config{},\n\t}\n\n\tif certPath != \"\" && keyPath != \"\" {\n\t\tlogrus.Debug(\"Configuring TLS with pem cert/key pair\")\n\t\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"loading x509 keypair\")\n\t\t}\n\n\t\tclientCA, err := ioutil.ReadFile(certPath)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"loading client CA\")\n\t\t}\n\n\t\tclientCertPool := x509.NewCertPool()\n\t\tclientCertPool.AppendCertsFromPEM(clientCA)\n\n\t\tc.Transport.(*http.Transport).TLSClientConfig.MinVersion = tls.VersionTLS12\n\t\tc.Transport.(*http.Transport).TLSClientConfig.PreferServerCipherSuites = true\n\t\tc.Transport.(*http.Transport).TLSClientConfig.Certificates = []tls.Certificate{cert}\n\t\tc.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true\n\t}\n\n\tif cc.GlobalIsSet(\"insecure\") {\n\t\tc.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true\n\t}\n\n\treturn &c, nil\n}", "func NewHTTPClientAPI(client http.Client, endpoint, from, accessKeyID, secretAccessKey string) *Option {\n\tSetDefaultHTTPClient(client)\n\n\treturn NewAPI(endpoint, from, accessKeyID, secretAccessKey)\n}", "func CreateK8sApiserverClient(configFile string) (*KubernetesAPIServer, error) {\n klog.Info(\"[INFO] Creating API Client\", configFile)\n api := &KubernetesAPIServer{}\n\tif (configFile != \"\") {\n config, err = clientcmd.BuildConfigFromFlags(\"\", configFile)\n if err != nil {\n klog.Error(\"[ERROR] Did not find valid kube config info\")\n\t\t\treturn nil, err\n }\n\t}else {\n \tconfig, err = clientcmd.BuildConfigFromFlags(\"\", \"\")\n \tif err != nil {\n \tklog.Error(\"[WARNING] Citrix Node Controller Failed to create a Client\")\n\t\t\treturn nil, err\n \t}\n\t}\n\n client, err := kubernetes.NewForConfig(config)\n if err != nil {\n klog.Error(\"[ERROR] Failed to establish connection\")\n klog.Fatal(err)\n }\n klog.Info(\"[INFO] Kubernetes Client is created\")\n api.Client = client\n return api, nil\n}" ]
[ "0.6720532", "0.6609761", "0.6237471", "0.6196213", "0.6178451", "0.6154285", "0.6143491", "0.60950136", "0.60523546", "0.604515", "0.60034585", "0.600159", "0.5998623", "0.5981964", "0.59607154", "0.59574425", "0.59522617", "0.5945582", "0.59252137", "0.5911097", "0.58986217", "0.5881208", "0.58724403", "0.58671165", "0.5860708", "0.58506423", "0.58473027", "0.5811638", "0.58050156", "0.5803488", "0.58034766", "0.58014756", "0.5795896", "0.5780728", "0.57700336", "0.5764897", "0.5763612", "0.57560015", "0.5742924", "0.574108", "0.5731746", "0.57212186", "0.5669059", "0.56614584", "0.56604433", "0.5658112", "0.5652933", "0.5645484", "0.56431085", "0.5641121", "0.5637737", "0.5614218", "0.561102", "0.5603996", "0.55993855", "0.5596011", "0.559272", "0.55917406", "0.5589934", "0.55640656", "0.5559414", "0.55536574", "0.55501586", "0.5549015", "0.5537816", "0.5533037", "0.5532202", "0.552667", "0.5522901", "0.5514739", "0.55137753", "0.550931", "0.55066055", "0.55064297", "0.5500191", "0.54981637", "0.5497745", "0.5496714", "0.54934615", "0.5492223", "0.5485578", "0.5471904", "0.54700977", "0.5465344", "0.54586005", "0.5457458", "0.5456584", "0.5452079", "0.5449793", "0.54488045", "0.5447458", "0.54455477", "0.5444099", "0.5441458", "0.5437044", "0.54285103", "0.5427661", "0.54273045", "0.5421203", "0.54190624" ]
0.84185094
0
NewDummyKube creates a dummy client to kubeapi service. It does nothing but logs actions.
func NewDummyKube() Kube { return kubeDummy{log: logrus.WithField("component", "kube_stub")} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func createKubeClient() (kubernetes.Interface, error) {\n\tif mockedController {\n\t\treturn fake.NewSimpleClientset(), nil\n\t}\n\tkubeconfig, ok := os.LookupEnv(EnvLiqoKConfig)\n\tif !ok || kubeconfig == \"\" {\n\t\treturn nil, errors.New(\"no kubeconfig provided\")\n\t}\n\tcfg, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(cfg)\n}", "func newKubeClient(kubeConfig, apiServerURL string, requestTimeout time.Duration) (kubernetes.Interface, managednodeClientset.Interface, apiextensionClientset.Interface, error) {\n\tglog.Infof(\"Instantiating new Kubernetes client\")\n\n\tconfig, err := getRestConfig(kubeConfig, apiServerURL)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tconfig.Timeout = requestTimeout * time.Second\n\n\tconfig.WrapTransport = func(rt http.RoundTripper) http.RoundTripper {\n\t\treturn instrumented_http.NewTransport(rt, &instrumented_http.Callbacks{\n\t\t\tPathProcessor: func(path string) string {\n\t\t\t\tparts := strings.Split(path, \"/\")\n\t\t\t\treturn parts[len(parts)-1]\n\t\t\t},\n\t\t})\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tnodeManagerClientset, err := managednodeClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nil, nil, err\n\t}\n\n\tapiExtensionClient, err := apiextensionClientset.NewForConfig(config)\n\n\tif err != nil {\n\t\treturn client, nodeManagerClientset, nil, err\n\t}\n\n\tglog.Infof(\"Created Kubernetes client %s\", config.Host)\n\n\treturn client, nodeManagerClientset, apiExtensionClient, err\n}", "func MustNewKubeClient() kubernetes.Interface {\n\tcfg, err := InClusterConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn kubernetes.NewForConfigOrDie(cfg)\n}", "func NewDefaultKubeClient(ctx context.Context) (*kubernetes.Clientset, error) {\n\treturn NewKubeClientFromPath(ctx, \"\")\n}", "func New(t time.Duration, inCluster bool) (*KubeAPI, error) {\n\tvar api KubeAPI\n\tapi.Timeout = t\n\tapi.InCluster = inCluster\n\tvar err error\n\n\tif api.InCluster {\n\t\tapi.Config, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn &api, err\n\t\t}\n\t} else {\n\t\tkubeconfig := filepath.Join(homeDir(), \".kube\", \"config\")\n\t\tapi.Config, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t}\n\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\n\tapi.Client, err = kubernetes.NewForConfig(api.Config)\n\tif err != nil {\n\t\treturn &api, err\n\t}\n\treturn &api, nil\n}", "func NewFakeKubeClient(client kubernetes.Interface) KubeClient {\n\treturn &fakeKubeClient{client: client}\n}", "func makeTestKuberhealthy(t *testing.T) *Kuberhealthy {\n\tif testing.Short() {\n\t\tt.Skip()\n\t}\n\n\tkh := NewKuberhealthy()\n\n\t// override the client with a blank config\n\tconfig := &rest.Config{}\n\tclient, _ := kubernetes.NewForConfig(config)\n\tkh.overrideKubeClient = client\n\n\treturn kh\n}", "func newKubeClient() kubernetes.Interface {\n\tvar kubeconfig string\n\tif _, err := os.Stat(clientcmd.RecommendedHomeFile); err == nil {\n\t\tkubeconfig = clientcmd.RecommendedHomeFile\n\t}\n\tlog.Debugf(\"use config file %s\", kubeconfig)\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\tlog.Fatalf(\"build config failed: %v\", err)\n\t}\n\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tlog.Fatalf(\"initialize kubernetes client failed: %v\", err)\n\t}\n\tlog.Infof(\"Connected to cluster at %s\", config.Host)\n\n\treturn client\n}", "func newKubeClient() (*kclient.Client, error) {\n\tvar (\n\t\tconfig *kclient.Config\n\t\terr error\n\t\tmasterURL string\n\t)\n\t// If the user specified --kube_master_url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tmasterURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif masterURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube_master_url was provided.\n\t\tconfig = &kclient.Config{Host: masterURL}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube_master_url and --kubecfg_file\n\t\t// 2) just --kubecfg_file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &kclientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = masterURL // might be \"\", but that is OK\n\t\trules := &kclientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = kclientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tconfig.Version = k8sAPIVersion\n\tglog.Infof(\"Using %s for kubernetes master\", config.Host)\n\tglog.Infof(\"Using kubernetes API %s\", config.Version)\n\treturn kclient.New(config)\n}", "func NewDummyClient() *DummyRegistryClient {\n\treturn &DummyRegistryClient{\n\t\tSpy: spies.NewSpy(),\n\t}\n}", "func LazyCreateKubeClient(client kubernetes.Interface) (kubernetes.Interface, error) {\n\treturn LazyCreateKubeClientWithMandatory(client, false)\n}", "func newKubeClient(kubeconfigPath string) (*versioned.Clientset, error) {\n\tvar err error\n\tvar kubeConf *rest.Config\n\n\tif kubeconfigPath == \"\" {\n\t\t// creates the in-cluster config\n\t\tkubeConf, err = k8s.GetConfig()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build default in cluster kube config failed: %w\", err)\n\t\t}\n\t} else {\n\t\tkubeConf, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"build kube client config from config file failed: %w\", err)\n\t\t}\n\t}\n\treturn versioned.NewForConfig(kubeConf)\n}", "func New(config *rest.Config) (Client, error) {\n\tkubeset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn Client{}, err\n\t}\n\treturn Client{\n\t\tkubeset: kubeset,\n\t}, nil\n}", "func NewDefaultKubernetesAPI(cli *servicecatalog.SDK) *ServiceCatalogAPI {\n\treturn &ServiceCatalogAPI{\n\t\tSDK: cli,\n\t\tbrokersInProgress: make(map[string]bool),\n\t\tlock: &sync.Mutex{},\n\t}\n}", "func NewKubeHTTP(u *url.URL) Kube {\n\tlog := logrus.WithField(\"component\", \"kube_client\")\n\tclient := resty.New().\n\t\tSetHostURL(u.String()).\n\t\tSetLogger(log.WriterLevel(logrus.DebugLevel)).\n\t\tSetDebug(true).\n\t\tSetError(cherry.Err{}).\n\t\tSetHeader(\"Content-Type\", \"application/json\").\n\t\tSetHeader(\"Accept\", \"application/json\")\n\tclient.JSONMarshal = jsoniter.Marshal\n\tclient.JSONUnmarshal = jsoniter.Unmarshal\n\treturn kube{\n\t\tclient: client,\n\t\tlog: cherrylog.NewLogrusAdapter(log),\n\t}\n}", "func New(masterUrl,kubeconfig string)(*Client,error){\n // use the current context in kubeconfig\n config, err := clientcmd.BuildConfigFromFlags(masterUrl, kubeconfig)\n if err != nil {\n\t return nil,err\n }\n\n // create the clientset\n clientset, err := kubernetes.NewForConfig(config)\n if err!=nil{\n\t\treturn nil,err\n }\n return &Client{cset:clientset},nil\n}", "func (c *clientProxy) createK8sClient() (kubernetes.Interface, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif c.kubeconfig == \"\" {\n\t\tconfig, err = rest.InClusterConfig()\n\t} else {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", c.kubeconfig)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func NewKubeComponent() (api.Component, error) {\n\treturn &kubeComponent{}, nil\n}", "func TestNewClient_NoTF(t *testing.T) {\n\ttmp, binDir, cacheDir, cleanup := mkSubDirs(t)\n\tprojectCmdOutputHandler := jobmocks.NewMockProjectCommandOutputHandler()\n\tdefer cleanup()\n\n\t// Set PATH to only include our empty directory.\n\tdefer tempSetEnv(t, \"PATH\", tmp)()\n\n\t_, err := terraform.NewClient(binDir, cacheDir, \"\", cmd.DefaultTFVersionFlag, cmd.DefaultTFDownloadURL, nil, true, projectCmdOutputHandler)\n\tErrEquals(t, \"getting default version: terraform not found in $PATH. Set --default-tf-version or download terraform from https://www.terraform.io/downloads.html\", err)\n}", "func FakeNew() (*Client, *FakeClientset) {\n\treturn FakeNewWithIngressSupports(false, true)\n}", "func NewFakeKubernetesClient(ns string) *fake.Clientset {\n\treturn fake.NewSimpleClientset(&corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: ns,\n\t\t},\n\t})\n}", "func New() (*K8S, error) {\n\t// create the Kubernetes API client\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tk8s := &K8S{Client: client.CoreV1()}\n\tk8s.Services = &Services{\n\t\tclient: k8s.Client.Services(\"\"),\n\t\tinterrupt: make(chan bool),\n\t\tsvcMap: make(chan map[string]apiv1.Service),\n\t}\n\n\treturn k8s, nil\n}", "func NewK8sClient(t interface {\n\tmock.TestingT\n\tCleanup(func())\n}) *K8sClient {\n\tmock := &K8sClient{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewDefaultClient(t *testing.T) *Client {\n\tcl, err := NewClient(\"service\", \"hostname\", nil)\n\tif err != nil {\n\t\tt.Fatalf(\"could not create default client\")\n\t}\n\n\treturn cl\n}", "func NewKubeTestPlatform() *KubeTestPlatform {\n\treturn &KubeTestPlatform{\n\t\tAppResources: new(TestResources),\n\t\tComponentResources: new(TestResources),\n\t\tSecrets: new(TestResources),\n\t}\n}", "func NewKubeUtil(manager manager.Manager,\n\trequest *reconcile.Request) KubeUtil {\n\treturn KubeUtil{\n\t\trequest: request,\n\t\tmanager: manager,\n\t}\n}", "func CreateK8sClient(contextCluster string) error {\n\tconfig, err := buildConfig(contextCluster)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tK8sClient = InitK8SOrDie(config)\n\tlogrus.Debugf(\"Kubernetes API client initialized for %s\", contextCluster)\n\n\treturn nil\n}", "func NewClient(host, token, nodeName string, insecure, UseAPIOnCacheIssues bool) (*Client, error) {\n\tvar config *rest.Config\n\tvar err error\n\tif host != \"\" && token != \"\" {\n\t\tconfig = &rest.Config{\n\t\t\tHost: host,\n\t\t\tBearerToken: token,\n\t\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\t\tInsecure: insecure,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Client{Clientset: client, nodeName: nodeName, useAPIOnCacheIssues: UseAPIOnCacheIssues}, nil\n}", "func NewKubeclient(log *logrus.Entry, config *v1.Config, pluginConfig *api.PluginConfig) (Kubeclient, error) {\n\trestconfig, err := managedcluster.RestConfigFromV1Config(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcli, err := kubernetes.NewForConfig(restconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &kubeclient{\n\t\tpluginConfig: *pluginConfig,\n\t\tlog: log,\n\t\tclient: cli,\n\t}, nil\n\n}", "func GetFakeKubeClient(testNs string, logger *logrus.Logger) (*KubeClient, error) {\n\tscheme, err := PrepareScheme()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfakeClientWrapper := NewFakeClientWrapper(fake.NewFakeClientWithScheme(scheme), scheme)\n\treturn NewKubeClient(fakeClientWrapper, logger, testNs), nil\n}", "func NewClient(nodes int) (*fake.Clientset, error) {\n\tclientset := fake.NewSimpleClientset()\n\tfor i := 0; i < nodes; i++ {\n\t\tn := &v1.Node{\n\t\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t\tName: fmt.Sprintf(\"node-%d\", i),\n\t\t\t},\n\t\t\tStatus: v1.NodeStatus{\n\t\t\t\tConditions: []v1.NodeCondition{\n\t\t\t\t\tv1.NodeCondition{\n\t\t\t\t\t\tType: v1.NodeReady,\n\t\t\t\t\t\tStatus: v1.ConditionTrue,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAddresses: []v1.NodeAddress{\n\t\t\t\t\t{\n\t\t\t\t\t\tType: v1.NodeExternalIP,\n\t\t\t\t\t\tAddress: fmt.Sprintf(\"%d.%d.%d.%d\", i, i, i, i),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}\n\t\tctx := context.TODO()\n\t\t_, err := clientset.CoreV1().Nodes().Create(ctx, n, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\t// Something is definitely wrong in the fake client\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn clientset, nil\n}", "func newKubeBuilder(appMan Manifest) Builder {\n\treturn &KubeBuilder{Manifest: appMan}\n}", "func FakeK8sClient(initObjects ...runtime.Object) client.Client {\n\ts := scheme.Scheme\n\tcorev1.AddToScheme(s)\n\tmonitoringv1.AddToScheme(s)\n\tcluster_v1alpha1.AddToScheme(s)\n\treturn fake.NewClientBuilder().WithScheme(s).WithRuntimeObjects(initObjects...).Build()\n}", "func New() *KubeCross {\n\treturn &KubeCross{&defaultImpl{}}\n}", "func LazyCreateKubeClientWithMandatory(client kubernetes.Interface, mandatory bool) (kubernetes.Interface, error) {\n\tif client != nil {\n\t\treturn client, nil\n\t}\n\tif !mandatory && IsNoKubernetes() {\n\t\treturn NewFakeKubernetesClient(\"default\"), nil\n\t}\n\tf := kubeclient.NewFactory()\n\tcfg, err := f.CreateKubeConfig()\n\tif err != nil {\n\t\treturn client, errors.Wrap(err, \"failed to get kubernetes config\")\n\t}\n\tclient, err = kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn client, errors.Wrap(err, \"error building kubernetes clientset\")\n\t}\n\treturn client, nil\n}", "func New() (kubernetes.Interface, error) {\n\tcs, err := getClientSet()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cs, nil\n}", "func New(c rest.Interface) *KudzuV1alpha1Client {\n\treturn &KudzuV1alpha1Client{c}\n}", "func DefaultMainKubeClient(metricStorage *metric_storage.MetricStorage, metricLabels map[string]string) klient.Client {\n\tclient := klient.New()\n\tclient.WithContextName(app.KubeContext)\n\tclient.WithConfigPath(app.KubeConfig)\n\tclient.WithRateLimiterSettings(app.KubeClientQps, app.KubeClientBurst)\n\tclient.WithMetricStorage(metricStorage)\n\tclient.WithMetricLabels(DefaultIfEmpty(metricLabels, DefaultMainKubeClientMetricLabels))\n\treturn client\n}", "func NewAuthDummyClient() AuthClient {\n\treturn AuthDummyClient{\n\t\tlog: logrus.WithField(\"component\", \"auth_stub\"),\n\t}\n}", "func CreateTestingNS(baseName string, c clientset.Interface, labels map[string]string) (*corev1.Namespace, error) {\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tnamespaceObj := &corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\t// use a short name because long names produce long hostnames but\n\t\t\t// maximum allowed length by mysql is 60.\n\t\t\t// https://dev.mysql.com/doc/refman/8.0/en/change-master-to.html\n\t\t\tGenerateName: fmt.Sprintf(\"e2e-%v-\", baseName),\n\t\t\tNamespace: \"\",\n\t\t\tLabels: labels,\n\t\t},\n\t\tStatus: corev1.NamespaceStatus{},\n\t}\n\t// Be robust about making the namespace creation call.\n\tvar got *corev1.Namespace\n\tif err := wait.PollImmediate(Poll, 30*time.Second, func() (bool, error) {\n\t\tvar err error\n\t\tgot, err = c.CoreV1().Namespaces().Create(namespaceObj)\n\t\tif err != nil {\n\t\t\tLogf(\"Unexpected error while creating namespace: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn got, nil\n}", "func CreateKubeClient(config *configuration.Config, namespace string) (*KubeClient, error) {\n\tkubeclient, err := CreateKubeClientWithoutSvcConfig(namespace)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubeclient.SvcConfig = config\n\treturn kubeclient, nil\n}", "func newAPIClient(opts *ClientOpts) (*APIClient, error) {\n\tconfig := &rest.Config{\n\t\tHost: opts.URL,\n\t\tUsername: opts.Username,\n\t\tPassword: opts.Password,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t\tBearerToken: opts.BearerToken,\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &APIClient{\n\t\tclientSet: client,\n\t}, nil\n}", "func NewMockClient(obj ...runtime.Object) *kube.K8sClient {\n\tclient := &kube.K8sClient{\n\t\tClient: fake.NewSimpleClientset(obj...),\n\t}\n\n\treturn client\n}", "func initializeKubeClient(kubeconfigPath string) (*kubernetes.Clientset, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfigPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn kubernetes.NewForConfig(config)\n}", "func Create(kubeConfigFile string) (*kubernetes.Clientset, error) {\n\tkubeconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\t// If not in cluster, use kube config file\n\t\tkubeconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeConfigFile)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn kubernetes.NewForConfig(kubeconfig)\n}", "func NewDummy(log logr.Logger, zones []dnsname.Name) *Dummy {\n\treturn &Dummy{\n\t\tlog: log.WithName(\"providers\").WithName(\"Dummy\"),\n\t\tzones: zones,\n\t}\n}", "func newServiceNoPatchTest(name string, options ...controllertesting.ServiceOption) TableRow {\n\ttest := newDispatcherBasicTest(\"Existing Dispatcher Service, \" + name + \", No Patch\")\n\ttest.Objects = append(test.Objects,\n\t\tcontrollertesting.NewKafkaChannelDispatcherService(options...),\n\t\tcontrollertesting.NewKafkaChannelDispatcherDeployment())\n\treturn test\n}", "func New(kubeconfig string) (*Instance, error) {\n\tvar cfg *rest.Config\n\tvar err error\n\n\tif len(kubeconfig) == 0 {\n\t\tkubeconfig = os.Getenv(\"KUBECONFIG\")\n\t}\n\n\tif len(kubeconfig) > 0 {\n\t\tlogrus.Debugf(\"using kubeconfig: %s to create k8s client\", kubeconfig)\n\t\tcfg, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\t} else {\n\t\tlogrus.Debugf(\"will use in-cluster config to create k8s client\")\n\t\tcfg, err = rest.InClusterConfig()\n\t}\n\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error building kubeconfig: %s\", err.Error())\n\t}\n\n\tkubeClient, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Instance{\n\t\tkubeClient: kubeClient,\n\t\tk8sOps: core.Instance(),\n\t}, nil\n}", "func NewK8sClient(cfgfile string) (*K8sClient, error) {\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cfgfile)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\t// Create the ClientSet\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Trace(err)\n\t}\n\n\treturn &K8sClient{\n\t\tkubeConfig: cfgfile,\n\t\tclientSet: client,\n\t}, nil\n}", "func (s *VarlinkInterface) GenerateKube(ctx context.Context, c VarlinkCall, name_ string, service_ bool) error {\n\treturn c.ReplyMethodNotImplemented(ctx, \"io.podman.GenerateKube\")\n}", "func New(env v1alpha1.Environment) (*Kubernetes, error) {\n\t// setup client\n\tctl, err := client.New(env.Spec.APIServer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// setup diffing\n\tif env.Spec.DiffStrategy == \"\" {\n\t\tenv.Spec.DiffStrategy = \"native\"\n\n\t\tif ctl.Info().ServerVersion.LessThan(semver.MustParse(\"1.13.0\")) {\n\t\t\tenv.Spec.DiffStrategy = \"subset\"\n\t\t}\n\t}\n\n\tk := Kubernetes{\n\t\tEnv: env,\n\t\tctl: ctl,\n\t\tdiffers: map[string]Differ{\n\t\t\t\"native\": ctl.DiffClientSide,\n\t\t\t\"validate\": ctl.DiffServerSide,\n\t\t\t\"subset\": SubsetDiffer(ctl),\n\t\t},\n\t}\n\n\treturn &k, nil\n}", "func NewKubernetesHelper(k8sContext string, retryFor func(time.Duration, func() error) error) (*KubernetesHelper, error) {\n\trules := clientcmd.NewDefaultClientConfigLoadingRules()\n\toverrides := &clientcmd.ConfigOverrides{CurrentContext: k8sContext}\n\tkubeConfig := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides)\n\tconfig, err := kubeConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &KubernetesHelper{\n\t\tclientset: clientset,\n\t\tk8sContext: k8sContext,\n\t\tretryFor: retryFor,\n\t}, nil\n}", "func NewClient(kubeconfig string) (*Client, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func NewWithoutDefaults(endpoint string) BaseClient {\n\treturn BaseClient{\n\t\tClient: autorest.NewClientWithUserAgent(UserAgent()),\n\t\tEndpoint: endpoint,\n\t}\n}", "func LazyCreateKubeClientAndNamespace(client kubernetes.Interface, ns string) (kubernetes.Interface, string, error) {\n\tif client != nil && ns != \"\" {\n\t\treturn client, ns, nil\n\t}\n\tif IsNoKubernetes() {\n\t\tif ns == \"\" {\n\t\t\tns = \"default\"\n\t\t}\n\t\tif client == nil {\n\t\t\tclient = NewFakeKubernetesClient(ns)\n\t\t}\n\t\treturn client, ns, nil\n\t}\n\tif client == nil {\n\t\tf := kubeclient.NewFactory()\n\t\tcfg, err := f.CreateKubeConfig()\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"failed to get kubernetes config\")\n\t\t}\n\t\tclient, err = kubernetes.NewForConfig(cfg)\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"error building kubernetes clientset\")\n\t\t}\n\t}\n\tif ns == \"\" {\n\t\tvar err error\n\t\tns, err = kubeclient.CurrentNamespace()\n\t\tif err != nil {\n\t\t\treturn client, ns, errors.Wrap(err, \"failed to get current kubernetes namespace\")\n\t\t}\n\t}\n\treturn client, ns, nil\n}", "func setUpAPIClient() *APIClient {\n\t// Read config\n\terr := getConfig(contivKubeCfgFile, &contivK8Config)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed: %v\", err)\n\t\treturn nil\n\t}\n\n\treturn NewAPIClient(contivK8Config.K8sAPIServer, contivK8Config.K8sCa,\n\t\tcontivK8Config.K8sKey, contivK8Config.K8sCert)\n\n}", "func CreateTestingNS(baseName string, c client.Client, labels map[string]string) (*corev1.Namespace, error) {\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tlabels[selectorKey] = string(RunID)\n\n\t// We don't use ObjectMeta.GenerateName feature, as in case of API call\n\t// failure we don't know whether the namespace was created and what is its\n\t// name.\n\tname := fmt.Sprintf(\"%v-%v\", baseName, RandomSuffix())\n\n\tnamespaceObj := &corev1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: \"\",\n\t\t\tLabels: labels,\n\t\t},\n\t\tStatus: corev1.NamespaceStatus{},\n\t}\n\t// Be robust about making the namespace creation call.\n\tif err := wait.PollImmediate(poll, pollShortTimeout, func() (bool, error) {\n\t\tvar err error\n\t\terr = c.Create(context.Background(), namespaceObj)\n\t\tif err != nil {\n\t\t\tif apierrs.IsAlreadyExists(err) {\n\t\t\t\t// regenerate on conflict\n\t\t\t\tLogf(\"Namespace name %q was already taken, generate a new name and retry\", namespaceObj.Name)\n\t\t\t\tnamespaceObj.Name = fmt.Sprintf(\"%v-%v\", baseName, RandomSuffix())\n\t\t\t} else {\n\t\t\t\tLogf(\"Unexpected error while creating namespace: %v\", err)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn namespaceObj, nil\n}", "func newDummyKeyServer() *server {\n\tdummy, _ := storagetest.DummyStorage(nil)\n\treturn &server{storage: dummy}\n}", "func New(ctx context.Context, tenantClusterKubernetesClient tenantcluster.Client) (Client, error) {\n\treturnedSecret, err := tenantClusterKubernetesClient.GetSecret(ctx, defaultCredentialsSecretSecretName, defaultCredentialsSecretSecretNamespace)\n\tif err != nil {\n\t\tif apimachineryerrors.IsNotFound(err) {\n\t\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %s/%s: %v not found\", defaultCredentialsSecretSecretNamespace, defaultCredentialsSecretSecretName, err)\n\t\t}\n\t\treturn nil, err\n\t}\n\tplatformCredentials, ok := returnedSecret.Data[platformCredentialsKey]\n\tif !ok {\n\t\treturn nil, machineapiapierrors.InvalidMachineConfiguration(\"Infra-cluster credentials secret %v did not contain key %v\",\n\t\t\tdefaultCredentialsSecretSecretName, platformCredentials)\n\t}\n\n\tclientConfig, err := clientcmd.NewClientConfigFromBytes(platformCredentials)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trestClientConfig, err := clientConfig.ClientConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkubernetesClient, err := kubernetes.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdynamicClient, err := dynamic.NewForConfig(restClientConfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &client{\n\t\tkubernetesClient: kubernetesClient,\n\t\tdynamicClient: dynamicClient,\n\t}, nil\n}", "func Dummy(args map[string]interface{}) error {\n\topArgs := op.OperationArgs{\n\t\t\"iterations\": args[\"iterations\"],\n\t}\n\n\toperation, err := client.CreateOperation(op.OpDummy, opArgs)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ui.AddOperation(operation)\n}", "func New(kubeconfig, opImage string) (*Framework, error) {\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", kubeconfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"build config from flags failed\")\n\t}\n\n\tcli, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating new kube-client failed\")\n\t}\n\n\thttpc := cli.CoreV1().RESTClient().(*rest.RESTClient).Client\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating http-client failed\")\n\t}\n\n\tmaegusClientV1, err := maegusclient.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating v1 maegus client failed\")\n\t}\n\n\tapiextensionsClientV1, err := clientset.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating v1 apiextensions client failed\")\n\t}\n\n\tf := &Framework{\n\t\tMasterHost: config.Host,\n\t\tMaegusClientV1: maegusClientV1,\n\t\tApiextensionsClientV1: apiextensionsClientV1,\n\t\tKubeClient: cli,\n\t\tHTTPClient: httpc,\n\t\tDefaultTimeout: time.Minute,\n\t}\n\n\treturn f, nil\n}", "func newTestClusterController() (\n\t*ClusterController,\n\tcache.Store, // cluster store\n\tcache.Store, // machine set store\n\t*clientgofake.Clientset,\n\t*clusteroperatorclientset.Clientset,\n) {\n\tkubeClient := &clientgofake.Clientset{}\n\tclusterOperatorClient := &clusteroperatorclientset.Clientset{}\n\tinformers := informers.NewSharedInformerFactory(clusterOperatorClient, 0)\n\n\tcontroller := NewClusterController(\n\t\tinformers.Clusteroperator().V1alpha1().Clusters(),\n\t\tinformers.Clusteroperator().V1alpha1().MachineSets(),\n\t\tkubeClient,\n\t\tclusterOperatorClient,\n\t)\n\n\tcontroller.clustersSynced = alwaysReady\n\tcontroller.machineSetsSynced = alwaysReady\n\n\treturn controller,\n\t\tinformers.Clusteroperator().V1alpha1().Clusters().Informer().GetStore(),\n\t\tinformers.Clusteroperator().V1alpha1().MachineSets().Informer().GetStore(),\n\t\tkubeClient,\n\t\tclusterOperatorClient\n}", "func TestNewController(t *testing.T) {\n\tmessagingClientSet, err := clientset.NewForConfig(&rest.Config{})\n\tif err != nil {\n\t\tt.Fail()\n\t}\n\n\tmessagingInformerFactory := informers.NewSharedInformerFactory(messagingClientSet, 0)\n\tnatssChannelInformer := messagingInformerFactory.Messaging().V1alpha1().NatssChannels()\n\n\tc := NewController(reconciler.Options{\n\t\tKubeClientSet: fakekubeclientset.NewSimpleClientset(),\n\t\tDynamicClientSet: nil,\n\t\tNatssClientSet: nil,\n\t\tRecorder: nil,\n\t\tStatsReporter: nil,\n\t\tConfigMapWatcher: nil,\n\t\tLogger: logtesting.TestLogger(t),\n\t\tResyncPeriod: 0,\n\t\tStopChannel: nil,\n\t}, dispatchertesting.NewDispatcherDoNothing(), natssChannelInformer)\n\tif c == nil {\n\t\tt.Errorf(\"unable to create dispatcher controller\")\n\t}\n}", "func CreateK8sApiserverClient(configFile string) (*KubernetesAPIServer, error) {\n klog.Info(\"[INFO] Creating API Client\", configFile)\n api := &KubernetesAPIServer{}\n\tif (configFile != \"\") {\n config, err = clientcmd.BuildConfigFromFlags(\"\", configFile)\n if err != nil {\n klog.Error(\"[ERROR] Did not find valid kube config info\")\n\t\t\treturn nil, err\n }\n\t}else {\n \tconfig, err = clientcmd.BuildConfigFromFlags(\"\", \"\")\n \tif err != nil {\n \tklog.Error(\"[WARNING] Citrix Node Controller Failed to create a Client\")\n\t\t\treturn nil, err\n \t}\n\t}\n\n client, err := kubernetes.NewForConfig(config)\n if err != nil {\n klog.Error(\"[ERROR] Failed to establish connection\")\n klog.Fatal(err)\n }\n klog.Info(\"[INFO] Kubernetes Client is created\")\n api.Client = client\n return api, nil\n}", "func NewFakeDocker() *FakeDocker {\n dockerClient := &FakeDocker{}\n dockerClient.Containers = make(map[string]*docker.Container)\n return dockerClient\n}", "func NewKubeClient(kubeconfig string) *kubeClient {\n\treturn &kubeClient{\n\t\tclient: getKubeClient(kubeconfig),\n\t}\n}", "func FakeNewWithIngressSupports(networkingv1Supported, extensionV1Supported bool) (*Client, *FakeClientset) {\n\tvar client Client\n\tvar fkclientset FakeClientset\n\n\tfkclientset.Kubernetes = fakeKubeClientset.NewSimpleClientset()\n\tclient.KubeClient = fkclientset.Kubernetes\n\n\tfkclientset.ServiceCatalogClientSet = fakeServiceCatalogClientSet.NewSimpleClientset()\n\tclient.serviceCatalogClient = fkclientset.ServiceCatalogClientSet.ServicecatalogV1beta1()\n\n\tfkclientset.AppsClientset = fakeAppsClientset.NewSimpleClientset()\n\tclient.appsClient = fkclientset.Kubernetes.AppsV1()\n\tclient.isExtensionV1Beta1IngressSupported = extensionV1Supported\n\tclient.isNetworkingV1IngressSupported = networkingv1Supported\n\tclient.checkIngressSupports = false\n\tclient.discoveryClient = fkclientset.Kubernetes.Discovery().(*fakediscovery.FakeDiscovery)\n\tclient.cachedDiscoveryClient = memory.NewMemCacheClient(client.discoveryClient)\n\n\tfkclientset.ProjClientset = fakeProjClientset.NewSimpleClientset()\n\tclient.projectClient = fkclientset.ProjClientset.ProjectV1()\n\n\tfkclientset.RouteClientset = fakeRouteClientset.NewSimpleClientset()\n\tclient.routeClient = fkclientset.RouteClientset.RouteV1()\n\n\treturn &client, &fkclientset\n}", "func NewKubeClient(\n\tctx context.Context,\n\tcontrollerClient client.Client,\n\tcluster *clusterv1.Cluster) (kubernetes.Interface, error) {\n\tclusterKey := client.ObjectKey{Namespace: cluster.Namespace, Name: cluster.Name}\n\tkubeconfig, err := kcfg.FromSecret(ctx, controllerClient, clusterKey)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to retrieve kubeconfig secret for Cluster %q in namespace %q\",\n\t\t\tcluster.Name, cluster.Namespace)\n\t}\n\n\trestConfig, err := clientcmd.RESTConfigFromKubeConfig(kubeconfig)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to create client configuration for Cluster %q in namespace %q\",\n\t\t\tcluster.Name, cluster.Namespace)\n\t}\n\t// sets the timeout, otherwise this will default to 0 (i.e. no timeout) which might cause tests to hang\n\trestConfig.Timeout = 10 * time.Second\n\n\treturn kubernetes.NewForConfig(restConfig)\n}", "func CreateKubeNamespace(baseName string, kubeClientSet kubernetes.Interface) (*v1.Namespace, error) {\n\tns := &v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tGenerateName: fmt.Sprintf(\"e2e-tests-%v-\", baseName),\n\t\t},\n\t}\n\n\treturn kubeClientSet.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})\n}", "func NewClient(address string) (KubeClient, error) {\n\t// create tls client\n\tcacertFile := \"/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\"\n\tcapem, err := ioutil.ReadFile(cacertFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcacert := x509.NewCertPool()\n\tif !cacert.AppendCertsFromPEM(capem) {\n\t\treturn nil, fmt.Errorf(\"unable to load certificate authority\")\n\t}\n\tconfig := &tls.Config{RootCAs: cacert}\n\ttransport := &http.Transport{TLSClientConfig: config}\n\n\t// read token\n\tclient := &http.Client{Transport: transport}\n\ttokenFile := \"/var/run/secrets/kubernetes.io/serviceaccount/token\"\n\ttoken, err := ioutil.ReadFile(tokenFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &realKubeClient{client, address, string(token)}, nil\n}", "func newController(clusterCfg clusterConfig) (Controller, error) {\n\tcfg := &rest.Config{\n\t\tHost: clusterCfg.Host,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: false,\n\t\t\tCAData: []byte(clusterCfg.CACert),\n\t\t\tCertData: []byte(clusterCfg.ClientCert),\n\t\t\tKeyData: []byte(clusterCfg.ClientKey),\n\t\t},\n\t}\n\n\t// Init the knative serving client\n\tknsClientSet, err := knservingclientset.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Init the k8s clientset\n\tk8sClientset, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tistioClientSet, err := networkingv1alpha3.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsparkClient, err := sparkclient.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &controller{\n\t\tknServingClient: knsClientSet.ServingV1(),\n\t\tk8sCoreClient: k8sClientset.CoreV1(),\n\t\tk8sAppsClient: k8sClientset.AppsV1(),\n\t\tk8sBatchClient: k8sClientset.BatchV1(),\n\t\tk8sRBACClient: k8sClientset.RbacV1(),\n\t\tk8sSparkOperator: sparkClient.SparkoperatorV1beta2(),\n\t\tistioClient: istioClientSet,\n\t}, nil\n}", "func newK8sCluster(c config.Config) (*k8sCluster, error) {\n\tvar kubeconfig *string\n\tif home := homedir.HomeDir(); home != \"\" {\n\t\tkubeconfig = flag.String(\"kubeconfig\", filepath.Join(home, \".kube\", \"config\"), \"(optional) absolue path to the kubeconfig file\")\n\t} else {\n\t\tkubeconfig = flag.String(\"kubeconfig\", \"\", \"absolue path to the kubeconfig file\")\n\t}\n\tflag.Parse()\n\n\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", *kubeconfig)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &k8sCluster{\n\t\tconfig: c,\n\t\tmutex: sync.Mutex{},\n\t\tpods: make(map[string]string),\n\t\tclientset: clientset,\n\t}, nil\n}", "func SetupKubeconfig(t *testing.T, terraformDir string) {\n terraformOptions := test_structure.LoadTerraformOptions(t, terraformDir)\n kubeconfig := terraform.Output(t, terraformOptions, \"kubeconfig\")\n kubeconfigFile := CreateTempFile(t, []byte(kubeconfig))\n kubectlOptions := k8s.NewKubectlOptions(\"\", kubeconfigFile.Name(), \"default\")\n test_structure.SaveKubectlOptions(t, terraformDir, kubectlOptions)\n}", "func ExampleNewClient() {\n\t// initialize registrar\n\treg, err := dosaRenamed.NewRegistrar(\"test\", \"myteam.myservice\", cte1)\n\tif err != nil {\n\t\t// registration will fail if the object is tagged incorrectly\n\t\tfmt.Printf(\"NewRegistrar error: %s\", err)\n\t\treturn\n\t}\n\n\t// use a devnull connector for example purposes\n\tconn := devnull.NewConnector()\n\n\t// create the client using the registrar and connector\n\tclient := dosaRenamed.NewClient(reg, conn)\n\n\terr = client.Initialize(context.Background())\n\tif err != nil {\n\t\tfmt.Printf(\"Initialize error: %s\", err)\n\t\treturn\n\t}\n}", "func createTestingNS(t *testing.T, baseName string, c clientset.Interface) (*v1.Namespace, error) {\n\t// We don't use ObjectMeta.GenerateName feature, as in case of API call\n\t// failure we don't know whether the namespace was created and what is its\n\t// name.\n\tname := fmt.Sprintf(\"%v-%v\", baseName, strconv.Itoa(rand.Intn(10000)))\n\n\tnamespaceObj := &v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: \"\",\n\t\t},\n\t\tStatus: v1.NamespaceStatus{},\n\t}\n\t// Be robust about making the namespace creation call.\n\tvar got *v1.Namespace\n\tif err := wait.PollImmediate(nsCreationPollInterval, 30*time.Second, func() (bool, error) {\n\t\tvar err error\n\t\tgot, err = c.CoreV1().Namespaces().Create(context.TODO(), namespaceObj, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\t\t// regenerate on conflict\n\t\t\t\tt.Logf(\"Namespace name %q was already taken, generate a new name and retry\", namespaceObj.Name)\n\t\t\t\tnamespaceObj.Name = fmt.Sprintf(\"%v-%v\", baseName, strconv.Itoa(rand.Intn(10000)))\n\t\t\t} else {\n\t\t\t\tt.Logf(\"Unexpected error while creating namespace: %v\", err)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn got, nil\n}", "func newKubeClientConfig() (*client.Config, error) {\n\tvar (\n\t\tconfig *client.Config\n\t\terr error\n\t\tapiServerURL string\n\t)\n\t// If the user specified --kube-apiserver-url, expand env vars and verify it.\n\tif *argKubeMasterURL != \"\" {\n\t\tapiServerURL, err = expandKubeMasterURL()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif apiServerURL != \"\" && *argKubecfgFile == \"\" {\n\t\t// Only --kube-apiserver-url was provided.\n\t\tconfig = &client.Config{\n\t\t\tHost: apiServerURL,\n\t\t\tVersion: \"v1\",\n\t\t}\n\t} else {\n\t\t// We either have:\n\t\t// 1) --kube-apiserver-url and --kubecfg-file\n\t\t// 2) just --kubecfg-file\n\t\t// 3) neither flag\n\t\t// In any case, the logic is the same. If (3), this will automatically\n\t\t// fall back on the service account token.\n\t\toverrides := &clientcmd.ConfigOverrides{}\n\t\toverrides.ClusterInfo.Server = apiServerURL // might be \"\", but that is OK\n\t\trules := &clientcmd.ClientConfigLoadingRules{ExplicitPath: *argKubecfgFile} // might be \"\", but that is OK\n\t\tif config, err = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(rules, overrides).ClientConfig(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tglog.Infof(\"Using %s for kubernetes API server\", config.Host)\n\tglog.Infof(\"Using kubernetes API version %s\", config.Version)\n\n\treturn config, nil\n}", "func createNewPod(ctx context.Context, podName, clusterID string, shadow bool, clientset kubernetes.Interface) (*corev1.Pod, error) {\n\tresources := corev1.ResourceList{}\n\tresources[corev1.ResourceCPU] = *resource.NewQuantity(1, resource.DecimalSI)\n\tresources[corev1.ResourceMemory] = *resource.NewQuantity(50000, resource.DecimalSI)\n\tpod := &corev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: podName,\n\t\t\tNamespace: \"default\",\n\t\t\tLabels: map[string]string{},\n\t\t},\n\t\tSpec: corev1.PodSpec{\n\t\t\tContainers: []corev1.Container{\n\t\t\t\t0: {\n\t\t\t\t\tName: \"test-container1\",\n\t\t\t\t\tResources: corev1.ResourceRequirements{\n\t\t\t\t\t\tLimits: resources,\n\t\t\t\t\t\tRequests: resources,\n\t\t\t\t\t},\n\t\t\t\t\tImage: \"nginx\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tif clusterID != \"\" {\n\t\tpod.Labels[forge.LiqoOriginClusterIDKey] = clusterID\n\t}\n\tif shadow {\n\t\tpod.Labels[consts.LocalPodLabelKey] = consts.LocalPodLabelValue\n\t}\n\tpod, err := clientset.CoreV1().Pods(\"default\").Create(ctx, pod, metav1.CreateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// set Status Ready\n\tpod.Status = corev1.PodStatus{\n\t\tPhase: corev1.PodRunning,\n\t}\n\tpod, err = clientset.CoreV1().Pods(\"default\").UpdateStatus(ctx, pod, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pod, nil\n}", "func (f *FailingKubeClient) Create(resources kube.ResourceList) (*kube.Result, error) {\n\tf.CreateCallsCnt++\n\treturn nil, f.CreateError\n}", "func NewClientOrDie(eao *options.EvictionAgentOptions) Client {\n\tc := &evictionClient{}\n\tvar config *rest.Config\n\tvar err error\n\n\tkubeconfigFile := eao.KubeconfigFile\n\tif kubeconfigFile != \"\" {\n\t\tconfig, err = clientcmd.BuildConfigFromFlags(\"\", kubeconfigFile)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Infof(\"Create client using kubeconfig file %s\", kubeconfigFile)\n\t} else {\n\t\tconfig, err = rest.InClusterConfig()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tlog.Infof(\"Create client using in-cluster config\")\n\t}\n\n\tclientSet, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tc.client = clientSet\n\tc.nodeName = eao.NodeName\n\n\tipAddr, err := c.getNodeAddress()\n\tif err != nil {\n\t\tlog.Errorf(\"%v\", err)\n\t\tpanic(err)\n\t}\n\n\ttransport, err := rest.TransportFor(config)\n\tif err != nil {\n\t\tlog.Errorf(\"get transport error: %v\", err)\n\t\tpanic(err)\n\t}\n\n\tc.nodeInfo = summary.NodeInfo{\n\t\tName: c.nodeName,\n\t\tPort: 10255, // get port from node?\n\t\tConnectAddress: ipAddr,\n\t}\n\n\t// NewSummaryStatsApi\n\tc.summaryApi, err = summary.NewSummaryStatsApi(transport, c.nodeInfo)\n\n\treturn c\n}", "func CreateTestCluster() {\n\tmg.Deps(tools.EnsureKind, StartDockerRegistry)\n\n\t// Determine host ip to populate kind config api server details\n\t// https://kind.sigs.k8s.io/docs/user/configuration/#api-server\n\taddrs, err := net.InterfaceAddrs()\n\tmgx.Must(errors.Wrap(err, \"could not get a list of network interfaces\"))\n\n\tvar ipAddress string\n\tfor _, address := range addrs {\n\t\tif ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {\n\t\t\tif ipnet.IP.To4() != nil {\n\t\t\t\tfmt.Println(\"Current IP address : \", ipnet.IP.String())\n\t\t\t\tipAddress = ipnet.IP.String()\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tos.Setenv(\"KUBECONFIG\", filepath.Join(pwd(), Kubeconfig))\n\tkindCfgPath := \"mage/tests/kind.config.yaml\"\n\tkindCfg, err := ioutil.ReadFile(kindCfgPath)\n\tmgx.Must(errors.Wrapf(err, \"error reading %s\", kindCfgPath))\n\n\tkindCfgTmpl, err := template.New(\"kind.config.yaml\").Parse(string(kindCfg))\n\tmgx.Must(errors.Wrapf(err, \"error parsing EnsureKind config template %s\", kindCfgPath))\n\n\tvar kindCfgContents bytes.Buffer\n\tkindCfgData := struct {\n\t\tAddress string\n\t}{\n\t\tAddress: ipAddress,\n\t}\n\terr = kindCfgTmpl.Execute(&kindCfgContents, kindCfgData)\n\terr = ioutil.WriteFile(\"kind.config.yaml\", kindCfgContents.Bytes(), 0600)\n\tmgx.Must(errors.Wrap(err, \"could not write kind config file\"))\n\tdefer os.Remove(\"kind.config.yaml\")\n\n\tmust.Run(\"kind\", \"create\", \"cluster\", \"--name\", getKindClusterName(), \"--config\", \"kind.config.yaml\")\n\n\t// Connect the kind and registry containers on the same network\n\tmust.Run(\"docker\", \"network\", \"connect\", \"kind\", getRegistryName())\n\n\t// Document the local registry\n\tkubectl(\"apply\", \"-f\", \"mage/tests/local-registry.yaml\").Run()\n}", "func createObjectInMultipleFakeClusters(obj ...ctrlruntimeclient.Object) map[string]ctrlruntimeclient.Client {\n\treturn map[string]ctrlruntimeclient.Client{\n\t\t\"a\": fakectrlruntimeclient.NewClientBuilder().WithObjects(obj...).Build(),\n\t\t\"b\": fakectrlruntimeclient.NewClientBuilder().WithObjects(obj...).Build(),\n\t}\n}", "func NewDefaultClient(key, secret string) *Client {\n\treturn &Client{\n\t\tapi: \"https://b2b.daowallet.com/api/v2\",\n\t\tapiKey: key,\n\t\tsecret: secret,\n\t\tclient: &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tDialContext: (&net.Dialer{\n\t\t\t\t\tTimeout: 10 * time.Second,\n\t\t\t\t\tKeepAlive: 10 * time.Second,\n\t\t\t\t}).DialContext,\n\t\t\t\tTLSHandshakeTimeout: 10 * time.Second,\n\t\t\t\tExpectContinueTimeout: 4 * time.Second,\n\t\t\t\tResponseHeaderTimeout: 3 * time.Second,\n\t\t\t},\n\t\t\tTimeout: 10 * time.Minute,\n\t\t},\n\t}\n}", "func NewWatcher(cfg *rest.Config) (*NetWatcher,error) {\n netWatcher := &NetWatcher{\n Factories: make(map[string]danminformers.SharedInformerFactory),\n Clients: make(map[string]danmclientset.Interface),\n Controllers: make(map[string]cache.Controller),\n }\n //this is how we test if the specific API is used within the cluster, or not\n //we can only create an Informer for an existing API, otherwise we get errors\n dnetClient, err := danmclientset.NewForConfig(cfg)\n if err != nil {\n return nil, err\n }\n _, err = dnetClient.DanmV1().DanmNets(\"\").List(meta_v1.ListOptions{})\n if err == nil {\n netWatcher.createDnetInformer(dnetClient)\n }\n tnetClient, err := danmclientset.NewForConfig(cfg)\n if err != nil {\n return nil, err\n }\n _, err = tnetClient.DanmV1().TenantNetworks(\"\").List(meta_v1.ListOptions{})\n if err == nil {\n netWatcher.createTnetInformer(tnetClient)\n }\n cnetClient, err := danmclientset.NewForConfig(cfg)\n if err != nil {\n return nil, err\n }\n _, err = cnetClient.DanmV1().ClusterNetworks().List(meta_v1.ListOptions{})\n if err == nil {\n netWatcher.createCnetInformer(cnetClient)\n }\n log.Println(\"Number of watcher's started for recognized APIs:\" + strconv.Itoa(len(netWatcher.Controllers)))\n if len(netWatcher.Controllers) == 0 {\n return nil, errors.New(\"no network management APIs are installed in the cluster, netwatcher cannot start!\")\n }\n return netWatcher, nil\n}", "func New(config Config) (*Service, error) {\n\t// Settings.\n\tif config.Flag == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Flag must not be empty\")\n\t}\n\tif config.Viper == nil {\n\t\treturn nil, microerror.Maskf(invalidConfigError, \"config.Viper must not be empty\")\n\t}\n\n\tvar err error\n\n\tvar k8sClient kubernetes.Interface\n\t{\n\t\tk8sConfig := k8sclient.DefaultConfig()\n\n\t\tk8sConfig.Logger = config.Logger\n\n\t\tk8sConfig.Address = config.Viper.GetString(config.Flag.Service.Kubernetes.Address)\n\t\tk8sConfig.InCluster = config.Viper.GetBool(config.Flag.Service.Kubernetes.InCluster)\n\t\tk8sConfig.TLS.CAFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CAFile)\n\t\tk8sConfig.TLS.CrtFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.CrtFile)\n\t\tk8sConfig.TLS.KeyFile = config.Viper.GetString(config.Flag.Service.Kubernetes.TLS.KeyFile)\n\n\t\tk8sClient, err = k8sclient.New(k8sConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar vaultClient *vaultapi.Client\n\t{\n\t\tvaultConfig := vaultutil.Config{\n\t\t\tFlag: config.Flag,\n\t\t\tViper: config.Viper,\n\t\t}\n\n\t\tvaultClient, err = vaultutil.NewClient(vaultConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar crdFramework *framework.Framework\n\t{\n\t\tcrdFramework, err = newCRDFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar customObjectFramework *framework.Framework\n\t{\n\t\tcustomObjectFramework, err = newCustomObjectFramework(config)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar healthzService *healthz.Service\n\t{\n\t\thealthzConfig := healthz.DefaultConfig()\n\n\t\thealthzConfig.K8sClient = k8sClient\n\t\thealthzConfig.Logger = config.Logger\n\t\thealthzConfig.VaultClient = vaultClient\n\n\t\thealthzService, err = healthz.New(healthzConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tvar versionService *version.Service\n\t{\n\t\tversionConfig := version.DefaultConfig()\n\n\t\tversionConfig.Description = config.Description\n\t\tversionConfig.GitCommit = config.GitCommit\n\t\tversionConfig.Name = config.Name\n\t\tversionConfig.Source = config.Source\n\t\tversionConfig.VersionBundles = NewVersionBundles()\n\n\t\tversionService, err = version.New(versionConfig)\n\t\tif err != nil {\n\t\t\treturn nil, microerror.Mask(err)\n\t\t}\n\t}\n\n\tnewService := &Service{\n\t\t// Dependencies.\n\t\tCRDFramework: crdFramework,\n\t\tCustomObjectFramework: customObjectFramework,\n\t\tHealthz: healthzService,\n\t\tVersion: versionService,\n\n\t\t// Internals\n\t\tbootOnce: sync.Once{},\n\t}\n\n\treturn newService, nil\n}", "func SetupTest(ctx context.Context) *corev1.Namespace {\n\tvar stopCh chan struct{}\n\tns := &corev1.Namespace{}\n\n\tBeforeEach(func() {\n\t\tstopCh = make(chan struct{})\n\t\t*ns = corev1.Namespace{\n\t\t\tObjectMeta: metav1.ObjectMeta{Name: \"testns-\" + randStringRunes(5)},\n\t\t}\n\n\t\terr := k8sClient.Create(ctx, ns)\n\t\tExpect(err).NotTo(HaveOccurred(), \"failed to create a test namespace\")\n\n\t\tmgr, err := ctrl.NewManager(cfg, ctrl.Options{MetricsBindAddress: \"0\"})\n\t\tExpect(err).NotTo(HaveOccurred(), \"failed to create a manager\")\n\n\t\tselector, _ := labels.Parse(\"app.kubernetes.io/name,!kubesphere.io/creator\")\n\n\t\treconciler := &ApplicationReconciler{\n\t\t\tClient: mgr.GetClient(),\n\t\t\tScheme: mgr.GetScheme(),\n\t\t\tMapper: mgr.GetRESTMapper(),\n\t\t\tApplicationSelector: selector,\n\t\t}\n\t\terr = reconciler.SetupWithManager(mgr)\n\t\tExpect(err).NotTo(HaveOccurred(), \"failed to setup application reconciler\")\n\n\t\tgo func() {\n\t\t\terr = mgr.Start(context.Background())\n\t\t\tExpect(err).NotTo(HaveOccurred(), \"failed to start manager\")\n\t\t}()\n\t})\n\n\tAfterEach(func() {\n\t\tclose(stopCh)\n\n\t\terr := k8sClient.Delete(ctx, ns)\n\t\tExpect(err).NotTo(HaveOccurred(), \"failed to delete test namespace\")\n\t})\n\n\treturn ns\n}", "func NewFake() (*FakeClient, error) {\n\treturn &FakeClient{}, nil\n}", "func NewKubeClient(kubeCfgFile string) (*k8sclient.Clientset, error) {\n\n\tconfig, err := BuildConfig(kubeCfgFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//TODO refactor & log errors\n\treturn k8sclient.NewForConfig(config)\n}", "func New(client *http.Client, maxBytes int64, metricsName string, authorizer Authorizer, gatherKubeConfig *rest.Config) *Client {\n\tif client == nil {\n\t\tclient = &http.Client{}\n\t}\n\tif maxBytes == 0 {\n\t\tmaxBytes = 10 * 1024 * 1024\n\t}\n\treturn &Client{\n\t\tclient: client,\n\t\tmaxBytes: maxBytes,\n\t\tmetricsName: metricsName,\n\t\tauthorizer: authorizer,\n\t\tgatherKubeConfig: gatherKubeConfig,\n\t}\n}", "func NewKubeClient() (*kubernetes.Clientset, *rest.Config) {\n\tconfig, err := config.GetConfig()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\treturn clientset, config\n}", "func NewK8sClient(cPath string) (*kubernetes.Clientset, error) {\n\t// clientcmd.BuildConfigFromFlags will call rest.InClusterConfig when the kubeconfigPath\n\t// passed into it is empty. However it logs an inappropriate warning could give the operator\n\t// unnecessary concern. Thus, we'll only call this when there is a kubeconfig explicitly\n\t// passed.\n\tif cPath != \"\" {\n\t\tglog.Infof(\"--kubeconfig flag specified, attempting to load kubeconfig from %s\", cPath)\n\n\t\tconfig, err := clientcmd.BuildConfigFromFlags(\"\", cPath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\t\tcs, err := kubernetes.NewForConfig(config)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cs, err\n\t}\n\n\t// attempt to create client from in-cluster config (the service account associated witht the pod)\n\tglog.Infof(`no --kubeconfig flag specified, loading Kubernetes service account assigned to pod \n\t\tlocated at /var/run/secrets/kubernetes.io/serviceaccount/.`)\n\n\tconfig, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tglog.Infof(\"client being created to communicate with API server at %s\", config.Host)\n\n\tcs, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn cs, err\n}", "func CreateTestingNS(ctx context.Context, baseName string, c clientset.Interface, labels map[string]string) (*v1.Namespace, error) {\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tlabels[\"e2e-run\"] = string(RunID)\n\n\t// We don't use ObjectMeta.GenerateName feature, as in case of API call\n\t// failure we don't know whether the namespace was created and what is its\n\t// name.\n\tname := fmt.Sprintf(\"%v-%v\", baseName, RandomSuffix())\n\n\tnamespaceObj := &v1.Namespace{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: \"\",\n\t\t\tLabels: labels,\n\t\t},\n\t\tStatus: v1.NamespaceStatus{},\n\t}\n\t// Be robust about making the namespace creation call.\n\tvar got *v1.Namespace\n\tif err := wait.PollImmediateWithContext(ctx, Poll, 30*time.Second, func(ctx context.Context) (bool, error) {\n\t\tvar err error\n\t\tgot, err = c.CoreV1().Namespaces().Create(ctx, namespaceObj, metav1.CreateOptions{})\n\t\tif err != nil {\n\t\t\tif apierrors.IsAlreadyExists(err) {\n\t\t\t\t// regenerate on conflict\n\t\t\t\tLogf(\"Namespace name %q was already taken, generate a new name and retry\", namespaceObj.Name)\n\t\t\t\tnamespaceObj.Name = fmt.Sprintf(\"%v-%v\", baseName, RandomSuffix())\n\t\t\t} else {\n\t\t\t\tLogf(\"Unexpected error while creating namespace: %v\", err)\n\t\t\t}\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t}); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif TestContext.VerifyServiceAccount {\n\t\tif err := WaitForDefaultServiceAccountInNamespace(ctx, c, got.Name); err != nil {\n\t\t\t// Even if we fail to create serviceAccount in the namespace,\n\t\t\t// we have successfully create a namespace.\n\t\t\t// So, return the created namespace.\n\t\t\treturn got, err\n\t\t}\n\t}\n\treturn got, nil\n}", "func (b *Botanist) DefaultKubeAPIServerService(sniPhase component.Phase) component.DeployWaiter {\n\treturn b.newKubeAPIServiceServiceComponent(sniPhase)\n}", "func NewFake(force bool) (m starlark.HasAttrs, closeFn func(), err error) {\n\t// Create a fake API store with some endpoints pre-populated\n\tcm := corev1.ConfigMap{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tAPIVersion: \"v1\",\n\t\t\tKind: \"ConfigMap\",\n\t\t},\n\t\tData: map[string]string{\n\t\t\t\"client-ca-file\": \"contents\",\n\t\t},\n\t}\n\tcmData, err := apiruntime.Encode(unstructured.UnstructuredJSONScheme, &cm)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tfm := map[string][]byte{\n\t\t\"/api/v1/namespaces/kube-system/configmaps/extension-apiserver-authentication\": cmData,\n\t}\n\n\ts := httptest.NewTLSServer(&fakeKube{m: fm})\n\n\tu, err := url.Parse(s.URL)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\th := \"https://\" + u.Host\n\ttlsConfig := rest.TLSClientConfig{\n\t\tInsecure: true,\n\t}\n\trConf := &rest.Config{Host: h, TLSClientConfig: tlsConfig}\n\n\tt, err := rest.TransportFor(rConf)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tk := New(\n\t\th,\n\t\tfakeDiscovery(),\n\t\tdynamic.NewForConfigOrDie(rConf),\n\t\t&http.Client{Transport: t},\n\t\tfalse, /* dryRun */\n\t\tforce,\n\t\tfalse, /* diff */\n\t\tnil, /* diffFilters */\n\t)\n\n\treturn newFakeModule(k.(*kubePackage)), s.Close, nil\n}", "func NewClient(kubeClient kube.Interface, istioClient istio.Interface, gatewayapiClient gatewayapiclient.Interface) *K8SClient {\n\treturn &K8SClient{\n\t\tistioClientset: istioClient,\n\t\tk8s: kubeClient,\n\t\tgatewayapi: gatewayapiClient,\n\t}\n}", "func NewDefaultComponentTest() *ComponentTest {\n\treturn &ComponentTest{\n\t\tCreateFunc: func(t testing.TB) feature.PodTemplateManagers {\n\t\t\treturn fake.NewPodTemplateManagers(t, v1.PodTemplateSpec{})\n\t\t},\n\t}\n}", "func NewDefaultClient() *Client {\n\taddress := os.Getenv(\"VAULT_ADDR\")\n\tif address == \"\" {\n\t\taddress = \"http://127.0.0.1:8200\"\n\t}\n\treturn &Client{&http.Client{}, address, os.Getenv(\"VAULT_TOKEN\"), NewStdLogger()}\n}", "func NewKubeInClusterClient() (kubernetes.Interface, error) {\n\tcfg, err := rest.InClusterConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to initialize inclusterconfig: %v\", err)\n\t}\n\tc, err := kubernetes.NewForConfig(cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to initialize client: %v\", err)\n\t}\n\treturn c, nil\n}", "func NewClient(logger log.Logger) (Client, error) {\n\tclient, err := k8s.NewInClusterClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn k8sclient{\n\t\tclient: client,\n\t\tlogger: logger,\n\t}, nil\n}", "func NewInternalClient(controlPlaneNamespace string, kubeAPIHost string) (APIClient, error) {\n\tapiURL, err := url.Parse(fmt.Sprintf(\"http://%s/\", kubeAPIHost))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn newClient(apiURL, &http.Client{Transport: &ochttp.Transport{}}, controlPlaneNamespace)\n}", "func newK8sService(config *K8sServiceConfig) *k8sService {\n\tif config == nil {\n\t\tconfig = &K8sServiceConfig{}\n\t}\n\n\tlog.Infof(\"k8sConfig %#v\", config)\n\treturn &k8sService{\n\t\tobservers: make([]types.K8sPodEventObserver, 0),\n\t\tconfig: *config,\n\t\tgetContainerInfo: utils.GetContainerInfo,\n\t}\n}" ]
[ "0.6764563", "0.6506686", "0.644636", "0.6340893", "0.6247618", "0.6195816", "0.6160903", "0.61370575", "0.6092504", "0.60601497", "0.60588753", "0.6037607", "0.6017768", "0.5995572", "0.59678555", "0.5954527", "0.59464544", "0.59281915", "0.5926527", "0.5844413", "0.58358985", "0.58082145", "0.57677287", "0.5754593", "0.57294333", "0.5711082", "0.5698427", "0.5697166", "0.56443405", "0.5639955", "0.5628619", "0.5620028", "0.5612049", "0.5599593", "0.55644757", "0.554723", "0.5532356", "0.55301446", "0.55274224", "0.55179894", "0.5515521", "0.5511168", "0.5499426", "0.54849064", "0.5472196", "0.5472184", "0.54624754", "0.5459971", "0.5448268", "0.5446164", "0.5416412", "0.54115653", "0.54090023", "0.540697", "0.53999776", "0.5396358", "0.53929317", "0.5390824", "0.5383191", "0.5380858", "0.53808254", "0.53686684", "0.5368553", "0.5365477", "0.536494", "0.5346353", "0.534517", "0.53323966", "0.5326247", "0.5321083", "0.53199565", "0.53121597", "0.53114736", "0.530417", "0.5293186", "0.52921575", "0.5282405", "0.52792114", "0.5278698", "0.5270447", "0.5269746", "0.52607745", "0.5255572", "0.5255353", "0.52523994", "0.5251392", "0.5245462", "0.52430594", "0.5242948", "0.5241626", "0.52397794", "0.5239394", "0.5238232", "0.5237523", "0.52361894", "0.52309483", "0.52272123", "0.5219123", "0.5214769", "0.52141666" ]
0.8445243
0
New creates a config for the network tracer
func New() *Config { cfg := ddconfig.SystemProbe sysconfig.Adjust(cfg) c := &Config{ Config: *ebpf.NewConfig(), NPMEnabled: cfg.GetBool(join(netNS, "enabled")), ServiceMonitoringEnabled: cfg.GetBool(join(smNS, "enabled")), DataStreamsEnabled: cfg.GetBool(join(dsNS, "enabled")), CollectTCPv4Conns: cfg.GetBool(join(netNS, "collect_tcp_v4")), CollectTCPv6Conns: cfg.GetBool(join(netNS, "collect_tcp_v6")), TCPConnTimeout: 2 * time.Minute, TCPClosedTimeout: 1 * time.Second, CollectUDPv4Conns: cfg.GetBool(join(netNS, "collect_udp_v4")), CollectUDPv6Conns: cfg.GetBool(join(netNS, "collect_udp_v6")), UDPConnTimeout: defaultUDPTimeoutSeconds * time.Second, UDPStreamTimeout: defaultUDPStreamTimeoutSeconds * time.Second, OffsetGuessThreshold: uint64(cfg.GetInt64(join(spNS, "offset_guess_threshold"))), ExcludedSourceConnections: cfg.GetStringMapStringSlice(join(spNS, "source_excludes")), ExcludedDestinationConnections: cfg.GetStringMapStringSlice(join(spNS, "dest_excludes")), MaxTrackedConnections: uint32(cfg.GetInt64(join(spNS, "max_tracked_connections"))), MaxClosedConnectionsBuffered: uint32(cfg.GetInt64(join(spNS, "max_closed_connections_buffered"))), ClosedConnectionFlushThreshold: cfg.GetInt(join(spNS, "closed_connection_flush_threshold")), ClosedChannelSize: cfg.GetInt(join(spNS, "closed_channel_size")), MaxConnectionsStateBuffered: cfg.GetInt(join(spNS, "max_connection_state_buffered")), ClientStateExpiry: 2 * time.Minute, DNSInspection: !cfg.GetBool(join(spNS, "disable_dns_inspection")), CollectDNSStats: cfg.GetBool(join(spNS, "collect_dns_stats")), CollectLocalDNS: cfg.GetBool(join(spNS, "collect_local_dns")), CollectDNSDomains: cfg.GetBool(join(spNS, "collect_dns_domains")), MaxDNSStats: cfg.GetInt(join(spNS, "max_dns_stats")), MaxDNSStatsBuffered: 75000, DNSTimeout: time.Duration(cfg.GetInt(join(spNS, "dns_timeout_in_s"))) * time.Second, ProtocolClassificationEnabled: cfg.GetBool(join(netNS, "enable_protocol_classification")), EnableHTTPMonitoring: cfg.GetBool(join(smNS, "enable_http_monitoring")), EnableHTTP2Monitoring: cfg.GetBool(join(smNS, "enable_http2_monitoring")), EnableHTTPSMonitoring: cfg.GetBool(join(netNS, "enable_https_monitoring")), EnableIstioMonitoring: cfg.GetBool(join(smNS, "enable_istio_monitoring")), MaxHTTPStatsBuffered: cfg.GetInt(join(smNS, "max_http_stats_buffered")), MaxKafkaStatsBuffered: cfg.GetInt(join(smNS, "max_kafka_stats_buffered")), MaxTrackedHTTPConnections: cfg.GetInt64(join(smNS, "max_tracked_http_connections")), HTTPNotificationThreshold: cfg.GetInt64(join(smNS, "http_notification_threshold")), HTTPMaxRequestFragment: cfg.GetInt64(join(smNS, "http_max_request_fragment")), EnableConntrack: cfg.GetBool(join(spNS, "enable_conntrack")), ConntrackMaxStateSize: cfg.GetInt(join(spNS, "conntrack_max_state_size")), ConntrackRateLimit: cfg.GetInt(join(spNS, "conntrack_rate_limit")), ConntrackRateLimitInterval: 3 * time.Second, EnableConntrackAllNamespaces: cfg.GetBool(join(spNS, "enable_conntrack_all_namespaces")), IgnoreConntrackInitFailure: cfg.GetBool(join(netNS, "ignore_conntrack_init_failure")), ConntrackInitTimeout: cfg.GetDuration(join(netNS, "conntrack_init_timeout")), EnableEbpfConntracker: true, AllowNetlinkConntrackerFallback: cfg.GetBool(join(netNS, "allow_netlink_conntracker_fallback")), EnableGatewayLookup: cfg.GetBool(join(netNS, "enable_gateway_lookup")), EnableMonotonicCount: cfg.GetBool(join(spNS, "windows.enable_monotonic_count")), RecordedQueryTypes: cfg.GetStringSlice(join(netNS, "dns_recorded_query_types")), EnableProcessEventMonitoring: cfg.GetBool(join(evNS, "network_process", "enabled")), MaxProcessesTracked: cfg.GetInt(join(evNS, "network_process", "max_processes_tracked")), EnableRootNetNs: cfg.GetBool(join(netNS, "enable_root_netns")), HTTPMapCleanerInterval: time.Duration(cfg.GetInt(join(smNS, "http_map_cleaner_interval_in_s"))) * time.Second, HTTPIdleConnectionTTL: time.Duration(cfg.GetInt(join(smNS, "http_idle_connection_ttl_in_s"))) * time.Second, // Service Monitoring EnableJavaTLSSupport: cfg.GetBool(join(smjtNS, "enabled")), JavaAgentDebug: cfg.GetBool(join(smjtNS, "debug")), JavaAgentArgs: cfg.GetString(join(smjtNS, "args")), JavaAgentAllowRegex: cfg.GetString(join(smjtNS, "allow_regex")), JavaAgentBlockRegex: cfg.GetString(join(smjtNS, "block_regex")), EnableGoTLSSupport: cfg.GetBool(join(smNS, "enable_go_tls_support")), EnableHTTPStatsByStatusCode: cfg.GetBool(join(smNS, "enable_http_stats_by_status_code")), } httpRRKey := join(smNS, "http_replace_rules") rr, err := parseReplaceRules(cfg, httpRRKey) if err != nil { log.Errorf("error parsing %q: %v", httpRRKey, err) } else { c.HTTPReplaceRules = rr } if !c.CollectTCPv4Conns { log.Info("network tracer TCPv4 tracing disabled") } if !c.CollectUDPv4Conns { log.Info("network tracer UDPv4 tracing disabled") } if !c.CollectTCPv6Conns { log.Info("network tracer TCPv6 tracing disabled") } if !c.CollectUDPv6Conns { log.Info("network tracer UDPv6 tracing disabled") } if !c.DNSInspection { log.Info("network tracer DNS inspection disabled by configuration") } c.EnableKafkaMonitoring = c.DataStreamsEnabled if c.EnableProcessEventMonitoring { log.Info("network process event monitoring enabled") } return c }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newConfig() *config {\n\treturn &config{\n\t\tAddr: \":80\",\n\t\tCacheSize: 1000,\n\t\tLogLevel: \"info\",\n\t\tRequestTimeout: 3000,\n\t\tTargetAddr: \"https://places.aviasales.ru\",\n\t}\n}", "func New(conf Config, opts ...func(Type)) (Type, error) {\n\tif c, ok := Constructors[conf.Type]; ok {\n\t\treturn c.constructor(conf, opts...)\n\t}\n\treturn nil, ErrInvalidTracerType\n}", "func New() *Config {\n\tc := &Config{\n\t\tTargets: make([]string, 0),\n\t}\n\tsetDefaultValues(c)\n\n\treturn c\n}", "func newConfig() *Config {\n\treturn &Config{\n\t\tgeneral{\n\t\t\tVerbose: false,\n\t\t},\n\t\tserver{\n\t\t\tType: \"http\",\n\t\t\tHost: \"0.0.0.0\",\n\t\t},\n\t\tmongo{\n\t\t\tHost: \"0.0.0.0:27017\",\n\t\t\tDatabase: \"etlog\",\n\t\t\tCollection: \"logs\",\n\t\t},\n\t}\n}", "func New(t *testing.T, configs ...Config) *Network {\n\tt.Helper()\n\tif len(configs) > 1 {\n\t\tpanic(\"at most one config should be provided\")\n\t}\n\tvar cfg Config\n\tif len(configs) == 0 {\n\t\tcfg = DefaultConfig()\n\t} else {\n\t\tcfg = configs[0]\n\t}\n\tnet := newNetwork(t, cfg)\n\tt.Cleanup(net.Cleanup)\n\n\treturn net\n}", "func newConfig() *Config {\n\n\tc := &Config{}\n\tvar logLevel, bServers, dServers string\n\n\tflag.StringVar(&c.ControlAddress, \"controlAddress\", \"localhost:4000\",\n\t\t\"Control process IP address, default localhost:4000\")\n\n\tflag.BoolVar(&c.Broadcast, \"broadcast\", true,\n\t\t\"Set to false to squash actual broadcast.\")\n\n\tflag.IntVar(&c.Bclients, \"bClients\", 1,\n\t\t\"The number of broadcast clients; Default 1\")\n\n\tflag.IntVar(&c.Dclients, \"dClients\", 1,\n\t\t\"The number of deliver clients; Default 1\")\n\n\tflag.IntVar(&c.Channels, \"channels\", 1,\n\t\t\"The number of channels; Default 1\")\n\n\tflag.StringVar(&bServers, \"bServers\", \"\",\n\t\t\"A comma-separated list of IP:PORT of broadcast servers to target; Required\")\n\n\tflag.StringVar(&dServers, \"dServers\", \"\",\n\t\t\"A comma-separated list of IP:PORT of deliver servers to target; Defaults to broadcast szervers\")\n\n\tflag.IntVar(&c.Transactions, \"transactions\", 1,\n\t\t\"The number of transactions broadcast to each client's servers; Default 1\")\n\n\tflag.IntVar(&c.Payload, \"payload\", TxHeaderSize,\n\t\t\"Payload size in bytes; Minimum/default is the performance header size (56 bytes)\")\n\n\tflag.IntVar(&c.Burst, \"burst\", 1,\n\t\t\"The number of transactions burst to each server during broadcast; Dafault 1\")\n\n\tflag.DurationVar(&c.Delay, \"delay\", 0,\n\t\t\"The delay between bursts, in the form required by time.ParseDuration(); Default is no delay\")\n\n\tflag.IntVar(&c.Window, \"window\", 100,\n\t\t\"The number of blocks allowed to be delivered without an ACK; Default 100\")\n\n\tflag.IntVar(&c.AckEvery, \"ackEvery\", 70,\n\t\t\"The deliver client will ACK every (this many) blocks; Default 70\")\n\n\tflag.DurationVar(&c.Timeout, \"timeout\", 30*time.Second,\n\t\t\"The initialization timeout, in the form required by time.ParseDuration(); Default 30s\")\n\n\tflag.BoolVar(&c.LatencyAll, \"latencyAll\", false,\n\t\t\"By default, only block latencies are reported. Set -latencyAll=true to report all transaction latencies\")\n\n\tflag.StringVar(&c.LatencyDir, \"latencyDir\", \"\",\n\t\t\"The directory to contain latency files; These files are only created if -latencyDir is specified\")\n\n\tflag.StringVar(&c.LatencyPrefix, \"latencyPrefix\", \"client\",\n\t\t\"Prefix for latency file names\")\n\n\tflag.StringVar(&logLevel, \"logLevel\", \"info\",\n\t\t\"The global logging level; Default 'info'\")\n\n\tflag.StringVar(&c.ControlLogging, \"controlLogging\", \"\",\n\t\t\"Override logging level for the 'control' process\")\n\n\tflag.StringVar(&c.BroadcastLogging, \"broadcastLogging\", \"\",\n\t\t\"Override logging level for the 'broadcast' processes\")\n\n\tflag.StringVar(&c.DeliverLogging, \"deliverLogging\", \"\",\n\t\t\"Override logging level for the 'deliver' processes\")\n\n\tflag.Parse()\n\n\tif c.ControlLogging == \"\" {\n\t\tc.ControlLogging = logLevel\n\t}\n\tif c.BroadcastLogging == \"\" {\n\t\tc.BroadcastLogging = logLevel\n\t}\n\tif c.DeliverLogging == \"\" {\n\t\tc.DeliverLogging = logLevel\n\t}\n\n\tinitLogging(c.ControlLogging)\n\n\trequireUint16(\"bclients\", c.Bclients)\n\trequireUint16(\"dclients\", c.Dclients)\n\trequireUint16(\"channels\", c.Channels)\n\trequireNonEmpty(\"bServers\", bServers)\n\tif dServers == \"\" {\n\t\tdServers = bServers\n\t}\n\trequireUint32(\"transactions\", c.Transactions)\n\trequirePosInt(\"payload\", c.Payload)\n\tif c.Payload < TxHeaderSize {\n\t\tlogger.Infof(\"Payload size will be set to the default (%d bytes)\\n\",\n\t\t\tTxHeaderSize)\n\t\tc.Payload = TxHeaderSize\n\t}\n\trequirePosInt(\"burst\", c.Burst)\n\trequirePosDuration(\"delay\", c.Delay)\n\trequirePosInt(\"window\", c.Window)\n\trequirePosInt(\"ackevery\", c.AckEvery)\n\trequireLE(\"ackevery\", \"window\", c.AckEvery, c.Window)\n\trequirePosDuration(\"timeout\", c.Timeout)\n\n\tc.Bservers = strings.Split(bServers, \",\")\n\tc.NumBservers = len(c.Bservers)\n\n\tc.Dservers = strings.Split(dServers, \",\")\n\tc.NumDservers = len(c.Dservers)\n\n\tlogger.Infof(\"Configuration\")\n\tlogger.Infof(\" Broadcast Servers: %d: %v\", c.NumBservers, c.Bservers)\n\tlogger.Infof(\" Broadcast Clients: %d\", c.Bclients)\n\tlogger.Infof(\" Deliver Servers : %d: %v\", c.NumDservers, c.Dservers)\n\tlogger.Infof(\" Deliver Clients : %d\", c.Dclients)\n\tlogger.Infof(\" Channels : %d\", c.Channels)\n\tlogger.Infof(\" Transactions : %d\", c.Transactions)\n\tlogger.Infof(\" Payload : %d\", c.Payload)\n\tlogger.Infof(\" Burst : %d\", c.Burst)\n\tlogger.Infof(\" Delay : %s\", c.Delay.String())\n\tlogger.Infof(\" Window : %d\", c.Window)\n\tlogger.Infof(\" AckEvery : %d\", c.AckEvery)\n\tlogger.Infof(\" Broadcast? : %v\", c.Broadcast)\n\n\tc.TotalBroadcastClients =\n\t\tuint64(c.NumBservers) * uint64(c.Channels) * uint64(c.Bclients)\n\tc.TxBroadcastPerClient = uint64(c.Transactions)\n\tc.BytesBroadcastPerClient = c.TxBroadcastPerClient * uint64(c.Payload)\n\tc.TotalTxBroadcast = uint64(c.TotalBroadcastClients) * c.TxBroadcastPerClient\n\tc.TotalBytesBroadcast = c.TotalTxBroadcast * uint64(c.Payload)\n\n\tc.TotalDeliverClients =\n\t\tuint64(c.NumDservers) * uint64(c.Channels) * uint64(c.Dclients)\n\tc.TxDeliveredPerClient =\n\t\tuint64(c.NumBservers) * uint64(c.Bclients) * uint64(c.Transactions)\n\tc.BytesDeliveredPerClient = c.TxDeliveredPerClient * uint64(c.Payload)\n\tc.TotalTxDelivered = c.TxDeliveredPerClient * c.TotalDeliverClients\n\tc.TotalBytesDelivered = c.TotalTxDelivered * uint64(c.Payload)\n\n\treturn c\n}", "func New() AgentConfig {\n\treturn AgentConfig{\n\t\tCentral: corecfg.NewCentralConfig(corecfg.TraceabilityAgent),\n\t\t//Gateway: NewGatewayConfig(),\n\t\t//Manager: apimgrcfg.APIManagerConfiguration{\n\t\t//\tPollInterval: 1 * time.Minute,\n\t\t//\tTLS: corecfg.NewTLSConfig(),\n\t\t//},\n\t\tStatus: corecfg.NewStatusConfig(),\n\t}\n}", "func NewTracer(_ *config.Config) (*Tracer, error) {\n\treturn nil, ebpf.ErrNotImplemented\n}", "func NewConfig() *Config {\r\n\t//config := Config{}\r\n\treturn &Config{\r\n\t\tInsteon: Credential{BaseURL: \"http://192.168.1.1:25105\", Username: \"fobar\", Password: \"password\"},\r\n\t\tWifiInterface: \"wlan0\",\r\n\t\tSSID: \"ssid_to_track\",\r\n\t\tGarageID: \"A3BF45\",\r\n\t\tLogfile: \"/var/log/opensesame.log\",\r\n\t}\r\n}", "func newConfig(initiator bool) noise.Config {\n\treturn noise.Config{\n\t\tCipherSuite: cipherSuite,\n\t\tPattern: noise.HandshakeNK,\n\t\tInitiator: initiator,\n\t\tPrologue: []byte(\"dnstt 2020-04-13\"),\n\t}\n}", "func NewTracer(cfg TracerConfig) opentracing.Tracer {\n\tvar tracer opentracing.Tracer\n\tswitch cfg.Provider {\n\tcase Zipkin:\n\t\tlogrus.Error(\"No implements yet.\")\n\t\t// fmt.Sprintf(\"http://%s:%s/api/v1/spans\",cfg.Host, cfg.Port)\n\t\tbreak\n\tcase Jaeger:\n\t\ttracer = newJaegerTracer(cfg)\n\t\tbreak\n\tdefault:\n\t\tlogrus.Errorf(\"unsported provider %s, use opentracing.GlobalTracer()\", cfg.Provider)\n\t\ttracer = opentracing.GlobalTracer()\n\t}\n\treturn tracer\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tEnable: true,\n\t\tAddress: \"0.0.0.0:30003\",\n\t}\n}", "func newConfig(opts ...Option) config {\n\tc := config{\n\t\tMeterProvider: otel.GetMeterProvider(),\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&c)\n\t}\n\treturn c\n}", "func New() *Config {\n\tc := &Config{\n\t\tAgent: &AgentConfig{\n\t\t\tEventReceiverCount: 5,\n\t\t\tEventQueueLimit: 50,\n\t\t\tHealthCheckPort: 10240,\n\t\t\tLogLevel: \"info\",\n\t\t},\n\t\tPlugins: make([]*pluginrunner.PluginRunner, 0),\n\t\tEventKinds: make(map[events.EventKind]bool),\n\t}\n\treturn c\n}", "func New(args *cniSkel.CmdArgs) (*NetConfig, error) {\n\t// Parse Json configuration.\n\tvar config netConfigJSON\n\tif err := json.Unmarshal(args.StdinData, &config); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse network config: %v\", err)\n\t}\n\n\t// Parse the configuration.\n\treturn parseConfig(&config)\n}", "func New(conf Config) *AppTracer {\n\treturn &AppTracer{\n\t\tConfig: conf,\n\t}\n}", "func newConfig() *Config {\n\t// TODO: use config as default, allow setting some values per-job\n\t// and prevent config changes affecting already-running tasks\n\treturn &Config{\n\t\tPath: DefaultPath,\n\t\tDatastorePrefix: \"MP_\",\n\t\tDefaultQueue: \"\",\n\t\tShards: 8,\n\t\tOversampling: 32,\n\t\tLeaseDuration: time.Duration(30) * time.Second,\n\t\tLeaseTimeout: time.Duration(10)*time.Minute + time.Duration(30)*time.Second,\n\t\tTaskTimeout: time.Duration(10)*time.Minute - time.Duration(30)*time.Second,\n\t\tCursorTimeout: time.Duration(50) * time.Second,\n\t\tRetries: 31,\n\t\tLogVerbose: false,\n\t\tHost: \"\",\n\t}\n}", "func New() (io.Closer, error) {\n\tif config.disabled || config.host == \"\" {\n\t\treturn closers.Noop, nil\n\t}\n\n\tsender, err := jaeger.NewUDPTransport(config.host, 0)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttracer, closer := jaeger.NewTracer(\n\t\tenvironment.ApplicationName,\n\t\tjaeger.NewRateLimitingSampler(config.sampleRate),\n\t\tjaeger.NewRemoteReporter(\n\t\t\tsender,\n\t\t\tjaeger.ReporterOptions.BufferFlushInterval(config.bufferFlushInterval),\n\t\t\tjaeger.ReporterOptions.Logger(logging.JaegerLogger()),\n\t\t),\n\t\tjaeger.TracerOptions.Logger(logging.JaegerLogger()),\n\t)\n\n\topentracing.SetGlobalTracer(tracer)\n\treturn closer, nil\n}", "func New(cfg *Config) (*Agent, error) {\n\n\tlogger := cfg.Logger\n\tif logger == nil {\n\t\tlogLevel := hlog.LevelFromString(cfg.LogLevel)\n\t\tif logLevel == hlog.NoLevel {\n\t\t\tlogLevel = hlog.Info\n\t\t}\n\t\tlogFormat := cfg.LogTimeFormat\n\t\tif logFormat == \"\" {\n\t\t\tlogFormat = rkvApi.DefaultTimeFormat\n\t\t}\n\t\tlogOpts := &hlog.LoggerOptions{\n\t\t\tName: fmt.Sprintf(\"rkv-%s\", cfg.NodeName),\n\t\t\tLevel: logLevel,\n\t\t\tIncludeLocation: cfg.LogIncludeLocation,\n\t\t\tOutput: cfg.LogOutput,\n\t\t\tTimeFormat: logFormat,\n\t\t}\n\t\tif logLevel > hlog.Debug {\n\t\t\t// to skip serf and memberlist debug logs\n\t\t\tlogOpts.Exclude = func(\n\t\t\t\tlevel hlog.Level, msg string, args ...interface{}) bool {\n\n\t\t\t\treturn strings.Index(msg, \"[DEBUG]\") > -1\n\t\t\t}\n\t\t}\n\t\tlogger = hlog.New(logOpts)\n\t}\n\tcfg.Logger = logger\n\n\thostname, _ := os.Hostname()\n\trpcAddr, _ := cfg.RPCAddr()\n\tlogger.Info(\"os\", \"hostname\", hostname)\n\tlogger.Info(\"config\", \"log-level\", cfg.LogLevel)\n\tlogger.Info(\"config\", \"node-name\", cfg.NodeName)\n\tlogger.Info(\"config\", \"data-dir\", cfg.DataDir)\n\tlogger.Info(\"config\", \"db\", cfg.Backend.DSN())\n\tlogger.Info(\"config\", \"discovery-join-address\", cfg.StartJoinAddrs)\n\tlogger.Info(\"config\", \"gRPC address\", rpcAddr)\n\tlogger.Info(\"config\", \"Raft.Heartbeat timeout\", cfg.Raft.HeartbeatTimeout)\n\tlogger.Info(\"config\", \"Raft.Election timeout\", cfg.Raft.ElectionTimeout)\n\n\ta := &Agent{\n\t\tConfig: cfg,\n\t\tlogger: logger,\n\t\tregistry: cfg.Registry,\n\t}\n\n\tif a.registry == nil {\n\t\ta.registry = registry.NewApplyRegistrator()\n\t}\n\n\tvar setup = []struct {\n\t\tname string\n\t\tfn func() error\n\t}{\n\t\t{\"setupRoute\", a.setupRoute},\n\t\t{\"setupRaft\", a.setupRaft},\n\t\t{\"setupMembership\", a.setupMembership},\n\t\t{\"setupGrpcServer\", a.setupGrpcServer},\n\t\t{\"setupHTTPServer\", a.setupHTTPServer},\n\t}\n\tfor _, s := range setup {\n\t\tif err := s.fn(); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%v: %v\", s.name, err)\n\t\t}\n\t}\n\treturn a, nil\n}", "func newConfig(path string) *Config {\n\tfile, e := ioutil.ReadFile(path)\n\tif e != nil {\n\t\tlog.Fatalf(\"config error: %v\", e)\n\t}\n\tvar cfg Config\n\te = json.Unmarshal(file, &cfg)\n\tif e != nil {\n\t\tlog.Fatalf(\"config error: %v\", e)\n\t}\n\n\t// redirect logging to a file\n\twriter, err := os.OpenFile(\"gorobot.log\", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to open file log: %v\", err)\n\t}\n\tlog.SetOutput(writer)\n\treturn &cfg\n}", "func ConfigNew() *Config {\n\tc := Config{\n\t\tHosts: map[string]*ConfigHost{},\n\t}\n\treturn &c\n}", "func NewTracer(cfg Config) (otrace.Tracer, io.Closer, error) {\n\tconf := cfg.New()\n\ttracer, closer, err := conf.New(\n\t\tcfg.App,\n\t\tconfig.Logger(jaeger.StdLogger),\n\t)\n\n\tif err != nil {\n\t\treturn nil, nil, errCreateTracer\n\t}\n\n\treturn tracer, closer, nil\n}", "func New(config config.Config) Logconfigurations {\n\tclient := http.NewClient(config)\n\n\tpkg := Logconfigurations{\n\t\tclient: client,\n\t\tlogger: config.GetLogger(),\n\t}\n\n\treturn pkg\n}", "func NewConfig() Config {\n\treturn Config{\n\t\t0.0, 0.0,\n\t\t4.0, 4.0,\n\t\t1000, 1000,\n\t\t512,\n\t\t\"ramp.json\",\n\t\t\"default.gob\",\n\t\t\"output.jpg\",\n\t\t\"000000\",\n\t\t0.0, 0.0}\n}", "func newNetwork(config neuralNetConfig) *neuralNet {\n\treturn &neuralNet{config: config}\n}", "func newConfig(serviceName string) config {\n\t// Use stdlib to parse. If it's an invalid value and doesn't parse, log it\n\t// and keep going. It should already be false on error but we force it to\n\t// be extra clear that it's failing closed.\n\tinsecure, err := strconv.ParseBool(os.Getenv(\"OTEL_EXPORTER_OTLP_INSECURE\"))\n\tif err != nil {\n\t\tinsecure = false\n\t\tlog.Println(\"Invalid boolean value in OTEL_EXPORTER_OTLP_INSECURE. Try true or false.\")\n\t}\n\n\treturn config{\n\t\tservicename: serviceName,\n\t\tendpoint: os.Getenv(\"OTEL_EXPORTER_OTLP_ENDPOINT\"),\n\t\tinsecure: insecure,\n\t}\n}", "func New() (Config, error) {\n\tconfig := Config{}\n\tif err := env.Parse(&config); err != nil {\n\t\treturn config, errors.Wrap(err, \"failed to load enviroment variables\")\n\t}\n\n\tconfig.Baker.Blacklist = cleanList(config.Baker.Blacklist)\n\tconfig.Baker.DexterLiquidityContracts = cleanList(config.Baker.DexterLiquidityContracts)\n\n\tif config.Notifications.Twilio.To != nil {\n\t\tconfig.Notifications.Twilio.To = cleanList(config.Notifications.Twilio.To)\n\t}\n\n\terr := validator.New().Struct(&config)\n\tif err != nil {\n\t\treturn config, errors.Wrap(err, \"invalid input\")\n\t}\n\n\treturn config, nil\n}", "func newConfig(appName string, pathToKeybase string, log Log, ignoreSnooze bool) (*config, error) {\n\tcfg := newDefaultConfig(appName, pathToKeybase, log, ignoreSnooze)\n\terr := cfg.load()\n\treturn &cfg, err\n}", "func newConfigFromViper(v *viper.Viper) Config {\n\treturn Config{\n\t\tChainlinkURL: v.GetString(\"chainlinkurl\"),\n\t\tInitiatorToChainlinkAccessKey: v.GetString(\"ic_accesskey\"),\n\t\tInitiatorToChainlinkSecret: v.GetString(\"ic_secret\"),\n\t\tDatabaseURL: v.GetString(\"databaseurl\"),\n\t\tChainlinkToInitiatorAccessKey: v.GetString(\"ci_accesskey\"),\n\t\tChainlinkToInitiatorSecret: v.GetString(\"ci_secret\"),\n\t\tExpectsMock: v.GetBool(\"mock\"),\n\t\tChainlinkTimeout: v.GetDuration(\"cl_timeout\"),\n\t\tChainlinkRetryAttempts: v.GetUint(\"cl_retry_attempts\"),\n\t\tChainlinkRetryDelay: v.GetDuration(\"cl_retry_delay\"),\n\t}\n}", "func New() (*Config, error) {\n\tflags := pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)\n\tcfg := &Config{\n\t\tFlags: flags,\n\t\tHTTPAddr: flags.StringP(\"http-addr\", \"l\", \":8080\", \"http listen address\"),\n\t\tHTTPReadHeaderTimeout: flags.DurationP(\"http-timeout\", \"h\", 1*time.Second, \"http timeout for reading request headers\"),\n\t\tCallTimeout: flags.DurationP(\"call-timeout\", \"t\", 0*time.Second, \"function call timeout\"),\n\t\tReadLimit: flags.Int64(\"read-limit\", -1, \"limit the amount of data which can be contained in a requests body\"),\n\t\tFramer: flags.StringP(\"framer\", \"f\", \"\", \"afterburn framer to use: line, json or http\"),\n\t\tBuffer: flags.BoolP(\"buffer\", \"b\", false, \"buffer output before writing\"),\n\t}\n\tif err := cfg.parseCommandline(); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := cfg.parseEnvironment(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, nil\n}", "func new() exampleInterface {\n\treturn config{}\n}", "func New() *Config {\n\treturn &Config{\n\t\tdevices: make([]Device, 0),\n\t}\n}", "func (endpoint *HTTPEndpoint) NewConfig(config *Config) {\n\tendpoint.Init()\n\n\tt0 := time.Now()\n\tendpoint.metrics.NewConfig.Requests.Hit()\n\n\tendpoint.Router.NewConfig(config)\n\n\tendpoint.metrics.NewConfig.Latency.RecordSince(t0)\n}", "func New(key []byte) *Config {\n\treturn &Config{\n\t\tsigningKey: key,\n\t\tclock: &utils.RealClock{},\n\t}\n}", "func NewTracerConfig(applicationName, token string) *Config {\n\treturn &Config{\n\t\tConfig: tracer.Config{\n\t\t\tApplicationName: applicationName,\n\t\t\tToken: token,\n\t\t\tMetadataOnly: true,\n\t\t\tDebug: false,\n\t\t\tSendTimeout: \"1s\",\n\t\t\tMaxTraceSize: tracer.DefaultMaxTraceSize,\n\t\t},\n\t}\n}", "func newTracesExporter(params exporter.CreateSettings, cfg component.Config) (*traceExporterImp, error) {\n\texporterFactory := otlpexporter.NewFactory()\n\n\tlb, err := newLoadBalancer(params, cfg, func(ctx context.Context, endpoint string) (component.Component, error) {\n\t\toCfg := buildExporterConfig(cfg.(*Config), endpoint)\n\t\treturn exporterFactory.CreateTracesExporter(ctx, params, &oCfg)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttraceExporter := traceExporterImp{loadBalancer: lb, routingKey: traceIDRouting}\n\n\tswitch cfg.(*Config).RoutingKey {\n\tcase \"service\":\n\t\ttraceExporter.routingKey = svcRouting\n\tcase \"traceID\", \"\":\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unsupported routing_key: %s\", cfg.(*Config).RoutingKey)\n\t}\n\treturn &traceExporter, nil\n}", "func (client *HTTPClient) NewConfig(config *Config) {\n\tclient.sendRequest(\"POST\", config, nil, &HTTPClientMetrics{NewConfig: true})\n}", "func New() *Config {\n\treturn &Config{\n\t\tfilename: \"\",\n\t\tmp: make(map[string]interface{}),\n\t\tseparator: \".\",\n\t}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func New() *Config {\n\treturn &Config{}\n}", "func newConfig() Config {\n\treturn Config{\n\t\tDefaultContainerConfig: newDefaultContainerConfig(),\n\t\tContainersConfig: map[string]ContainerConfig{},\n\t\tExclude: []string{},\n\t}\n}", "func New(configPathRel string) *Config {\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tc := &Config{}\n\tc.workinkDir = dir\n\n\tconfigPathAbs := path.Join(dir, configPathRel)\n\n\tfile, err := ioutil.ReadFile(configPathAbs)\n\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Config not found in path: %s\", configPathAbs))\n\t}\n\n\te := json.Unmarshal(file, c)\n\n\tif e != nil {\n\t\tpanic(fmt.Errorf(\"Cannot read config: %s\", err))\n\t}\n\n\treturn c\n}", "func NewConfig() Config {\n\treturn Config{\n\t\tFormat: \"auto\",\n\t\tLevel: zapcore.InfoLevel,\n\t}\n}", "func newPeersConfigImpl() *examplePeersConfig {\n\tpConfig := verifyIsLocalPeersURLs(peersConfig)\n\tpeersConfig = pConfig\n\tp := &examplePeersConfig{}\n\treturn p\n}", "func New(configPath string) *Lightheus {\n\tcfg := getConfigFromFile(configPath)\n\taf, cc := parseUrls(cfg.Addresses)\n\tcommon.PrettyPrint(af)\n\tcommon.PrettyPrint(cc.file2urlMap)\n\n\tae := aetos.NewBaseWithFiles(\"aetos-base.yml\", af)\n\tae.Debug()\n\treturn &Lightheus{\n\t\tcfg: cc,\n\t\taetos: ae,\n\t}\n}", "func New(device, addr string, port int) (*Transport, error) {\n return &Transport{\n device: device,\n addr: addr,\n port: port,\n sessions: make(map[string]*ssh.Session, 800),\n clients: make(map[string]*ssh.Client, 100),\n }, nil\n}", "func newTraceExporter(logger *zap.Logger, cfg configmodels.Exporter) (component.TracesExporter, error) {\n\n\tl := &logServiceTraceSender{\n\t\tlogger: logger,\n\t}\n\n\tvar err error\n\tif l.client, err = NewLogServiceClient(cfg.(*Config), logger); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporterhelper.NewTraceExporter(\n\t\tcfg,\n\t\tlogger,\n\t\tl.pushTraceData)\n}", "func newConfig() *config {\n\t/*According to Liqo Agent installation process, first check if\n\tuser has defined XDG_DATA_HOME env variable. Otherwise, use the\n\tfallback directory according to XDG specifications\n\t(www.freedesktop.com)*/\n\tXDGBaseDir, present := os.LookupEnv(\"XDG_DATA_HOME\")\n\tif !present {\n\t\tXDGBaseDir = filepath.Join(os.Getenv(\"HOME\"), \".local/share\")\n\t}\n\tliqoPath := filepath.Join(XDGBaseDir, \"liqo\")\n\tif err := os.Setenv(client.EnvLiqoPath, liqoPath); err != nil {\n\t\tos.Exit(1)\n\t}\n\tconf := &config{notifyLevel: NotifyLevelMax, notifyIconPath: filepath.Join(liqoPath, \"icons\")}\n\tconf.notifyTranslateMap = make(map[NotifyLevel]string)\n\tconf.notifyTranslateReverseMap = make(map[string]NotifyLevel)\n\tconf.notifyTranslateMap[NotifyLevelOff] = NotifyLevelOffDescription\n\tconf.notifyTranslateMap[NotifyLevelMin] = NotifyLevelMinDescription\n\tconf.notifyTranslateMap[NotifyLevelMax] = NotifyLevelMaxDescription\n\tfor k, v := range conf.notifyTranslateMap {\n\t\tconf.notifyTranslateReverseMap[v] = k\n\t}\n\treturn conf\n}", "func New(b *beat.Beat, rawConfig *common.Config) (beat.Beater, error) {\n\tparsedConfig := config.DefaultConfig\n\tif err := rawConfig.Unpack(&parsedConfig); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading config file: %v\", err)\n\t}\n\n\tlimit := parsedConfig.Scheduler.Limit\n\tlocationName := parsedConfig.Scheduler.Location\n\tif locationName == \"\" {\n\t\tlocationName = \"Local\"\n\t}\n\tlocation, err := time.LoadLocation(locationName)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tscheduler := scheduler.NewWithLocation(limit, location)\n\tbt := &Infobeat{\n\t\tdone: make(chan struct{}),\n\t\tconfig: parsedConfig,\n\t\tscheduler: scheduler,\n\t}\n\treturn bt, nil\n}", "func New(filename string) *Config {\n\tconfig := Config{filename, nil}\n\tconfig.Reload()\n\tgo config.watch()\n\treturn &config\n}", "func newNetworkWithConfig(configFunc func(*Config), peers ...stateMachine) *network {\n\tsize := len(peers)\n\tpeerAddrs := idsBySize(size)\n\tpeerGroups := grpsByIds(peerAddrs)\n\n\tnpeers := make(map[uint64]stateMachine, size)\n\tnstorage := make(map[uint64]IExtRaftStorage, size)\n\n\tfor j, p := range peers {\n\t\tid := peerAddrs[j]\n\t\tswitch v := p.(type) {\n\t\tcase nil:\n\t\t\tnstorage[id] = NewMemoryStorage()\n\t\t\tcfg := newTestConfig(id, peerAddrs, 10, 1, nstorage[id])\n\t\t\tif configFunc != nil {\n\t\t\t\tconfigFunc(cfg)\n\t\t\t}\n\t\t\tsm := newRaft(cfg)\n\t\t\tnpeers[id] = sm\n\t\tcase *raft:\n\t\t\tlearners := make(map[uint64]bool, len(v.learnerPrs))\n\t\t\tfor i := range v.learnerPrs {\n\t\t\t\tlearners[i] = true\n\t\t\t}\n\t\t\tv.id = id\n\t\t\tv.prs = make(map[uint64]*Progress)\n\t\t\tv.learnerPrs = make(map[uint64]*Progress)\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tif _, ok := learners[peerAddrs[i]]; ok {\n\t\t\t\t\tv.learnerPrs[peerAddrs[i]] = &Progress{group: peerGroups[peerAddrs[i]], IsLearner: true}\n\t\t\t\t} else {\n\t\t\t\t\tv.prs[peerAddrs[i]] = &Progress{group: peerGroups[peerAddrs[i]]}\n\t\t\t\t}\n\t\t\t}\n\t\t\tv.reset(v.Term)\n\t\t\tnpeers[id] = v\n\t\tcase *blackHole:\n\t\t\tnpeers[id] = v\n\t\tdefault:\n\t\t\tpanic(fmt.Sprintf(\"unexpected state machine type: %T\", p))\n\t\t}\n\t}\n\treturn &network{\n\t\tpeers: npeers,\n\t\tstorage: nstorage,\n\t\tdropm: make(map[connem]float64),\n\t\tignorem: make(map[pb.MessageType]bool),\n\t}\n}", "func (c Config) New() (*Server, error) {\n\tpromPeerRTT := prometheus.NewHistogramVec(prometheus.HistogramOpts{\n\t\tNamespace: \"nethealth\",\n\t\tSubsystem: \"echo\",\n\t\tName: \"duration_seconds\",\n\t\tHelp: \"The round trip time to reach the peer\",\n\t\tBuckets: []float64{\n\t\t\t0.0001, // 0.1 ms\n\t\t\t0.0002, // 0.2 ms\n\t\t\t0.0003, // 0.3 ms\n\t\t\t0.0004, // 0.4 ms\n\t\t\t0.0005, // 0.5 ms\n\t\t\t0.0006, // 0.6 ms\n\t\t\t0.0007, // 0.7 ms\n\t\t\t0.0008, // 0.8 ms\n\t\t\t0.0009, // 0.9 ms\n\t\t\t0.001, // 1ms\n\t\t\t0.0015, // 1.5ms\n\t\t\t0.002, // 2ms\n\t\t\t0.003, // 3ms\n\t\t\t0.004, // 4ms\n\t\t\t0.005, // 5ms\n\t\t\t0.01, // 10ms\n\t\t\t0.02, // 20ms\n\t\t\t0.04, // 40ms\n\t\t\t0.08, // 80ms\n\t\t},\n\t}, []string{LabelNodeName, LabelPeerName})\n\tpromPeerRTTSummary := prometheus.NewSummaryVec(prometheus.SummaryOpts{\n\t\tNamespace: \"nethealth\",\n\t\tSubsystem: \"echo\",\n\t\tName: \"latency_summary_milli\",\n\t\tHelp: \"The round trip time between peers in milliseconds\",\n\t\tMaxAge: 30 * time.Second,\n\t\tAgeBuckets: 5,\n\t\tObjectives: map[float64]float64{\n\t\t\t0.1: 0.09, // 10th percentile\n\t\t\t0.2: 0.08, // ...\n\t\t\t0.3: 0.07,\n\t\t\t0.4: 0.06,\n\t\t\t0.5: 0.05,\n\t\t\t0.6: 0.04,\n\t\t\t0.7: 0.03,\n\t\t\t0.8: 0.02,\n\t\t\t0.9: 0.01,\n\t\t\t0.95: 0.005,\n\t\t\t0.99: 0.001, // 99th percentile\n\t\t},\n\t}, []string{LabelNodeName, LabelPeerName})\n\tpromPeerTimeout := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: \"nethealth\",\n\t\tSubsystem: \"echo\",\n\t\tName: \"timeout_total\",\n\t\tHelp: \"The number of echo requests that have timed out\",\n\t}, []string{LabelNodeName, LabelPeerName})\n\tpromPeerRequest := prometheus.NewCounterVec(prometheus.CounterOpts{\n\t\tNamespace: \"nethealth\",\n\t\tSubsystem: \"echo\",\n\t\tName: \"request_total\",\n\t\tHelp: \"The number of echo requests that have been sent\",\n\t}, []string{LabelNodeName, LabelPeerName})\n\n\tprometheus.MustRegister(\n\t\tpromPeerRTT,\n\t\tpromPeerRTTSummary,\n\t\tpromPeerTimeout,\n\t\tpromPeerRequest,\n\t)\n\n\tselector := DefaultSelector\n\tif c.Selector != \"\" {\n\t\tselector = c.Selector\n\t}\n\n\tlabelSelector, err := labels.Parse(selector)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\n\tif c.ServiceDiscoveryQuery == \"\" {\n\t\tc.ServiceDiscoveryQuery = DefaultServiceDiscoveryQuery\n\t}\n\n\treturn &Server{\n\t\tconfig: c,\n\t\tFieldLogger: logrus.WithField(trace.Component, \"nethealth\"),\n\t\tpromPeerRTT: promPeerRTT,\n\t\tpromPeerRTTSummary: promPeerRTTSummary,\n\t\tpromPeerTimeout: promPeerTimeout,\n\t\tpromPeerRequest: promPeerRequest,\n\t\tselector: labelSelector,\n\t\ttriggerResync: make(chan bool, 1),\n\t\trxMessage: make(chan messageWrapper, RxQueueSize),\n\t\tpeers: make(map[string]*peer),\n\t\taddrToPeer: make(map[string]string),\n\t}, nil\n}", "func NewTrace(localAddr string, logPath string) *Trace {\n\tt := &Trace{\n\t\tstopCh: make(chan struct{}),\n\t\tmsgCh: make(chan []byte, 1000),\n\t\tlocalAddr: localAddr,\n\t\tlogPath: logPath,\n\t\tforceLog: false,\n\t}\n\treturn t\n}", "func New() *Config {\n\treturn &Config{\n\t\tEncryptor: &encryption.KMSEncryptor{\n\t\t\tKMS: kms.New(session.New(), &aws.Config{Region: aws.String(os.Getenv(\"EC2_REGION\"))}),\n\t\t},\n\t\tdata: (unsafe.Pointer)(&configData{\n\t\t\tbody: new(sjson.Json),\n\t\t\tdecrypted: make(map[uint64]*sjson.Json),\n\t\t}),\n\t\tobservers: make([]chan bool, 0),\n\t}\n}", "func New(name string) *Config {\n\treturn &Config{name: name}\n}", "func New(config *interface{}) {\n\tv := reflect.ValueOf(*config)\n\tfieldCount := v.NumField()\n\n\tfor i := 0; i < fieldCount; i++ {\n\t\tswitch v.Field(i).Kind() {\n\t\tcase reflect.Int:\n\t\t\tval := reflect.ValueOf(getIntFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.String:\n\t\t\tval := reflect.ValueOf(getStringFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tcase reflect.Bool:\n\t\t\tval := reflect.ValueOf(getBoolFromEnv(v.Field(i).Type().Name()))\n\t\t\tv.Field(i).Set(val)\n\t\tdefault:\n\t\t\tlog.Fatalf(\"error building config -- %s is not of an acceptable type\", v.Field(i).Type().Name())\n\t\t}\n\t}\n}", "func New() *Config {\n\treturn &Config{\n\t\tChecks: []*checkInstance{},\n\t}\n}", "func New(indexer cache.Store) *Manager {\n\tlogger := &bgplog.Logger{Entry: log}\n\tc := &metallbctl.Controller{\n\t\tClient: bgpk8s.New(logger.Logger),\n\t\tIPs: metallballoc.New(),\n\t}\n\n\tf, err := os.Open(option.Config.BGPConfigPath)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to open BGP config file\")\n\t}\n\tdefer f.Close()\n\n\tconfig, err := bgpconfig.Parse(f)\n\tif err != nil {\n\t\tlog.WithError(err).Fatal(\"Failed to parse BGP configuration\")\n\t}\n\tc.SetConfig(logger, config)\n\n\tmgr := &Manager{\n\t\tController: c,\n\t\tlogger: logger,\n\n\t\tqueue: workqueue.New(),\n\t\tindexer: indexer,\n\t}\n\tgo mgr.run()\n\n\treturn mgr\n}", "func CreateConfig() *Config {\n return &Config{\n HeaderName: defaultHeader,\n }\n}", "func NewTracer(ctx context.Context, yamlConfig []byte) (opentracing.Tracer, io.Closer, error) {\n\tconfig := Config{}\n\tif err := yaml.Unmarshal(yamlConfig, &config); err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\toptions := lightstep.Options{\n\t\tAccessToken: config.AccessToken,\n\t\tCollector: config.Collector,\n\t}\n\tlighstepTracer, err := lightstep.CreateTracer(options)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tt := &Tracer{\n\t\tlighstepTracer,\n\t\tctx,\n\t}\n\treturn t, t, nil\n}", "func newConfig() (*config, error) {\n\tec2Metadata := ec2metadata.New(session.Must(session.NewSession()))\n\tregion, err := ec2Metadata.Region()\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get region from ec2 metadata\")\n\t}\n\n\tinstanceID, err := ec2Metadata.GetMetadata(\"instance-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get instance id from ec2 metadata\")\n\t}\n\n\tmac, err := ec2Metadata.GetMetadata(\"mac\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get mac from ec2 metadata\")\n\t}\n\n\tsecurityGroups, err := ec2Metadata.GetMetadata(\"security-groups\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get security groups from ec2 metadata\")\n\t}\n\n\tinterfaces, err := ec2Metadata.GetMetadata(\"network/interfaces/macs\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get interfaces from ec2 metadata\")\n\t}\n\n\tsubnet, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/subnet-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get subnet from ec2 metadata\")\n\t}\n\n\tvpc, err := ec2Metadata.GetMetadata(\"network/interfaces/macs/\" + mac + \"/vpc-id\")\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"unable to get vpc from ec2 metadata\")\n\t}\n\n\treturn &config{region: region,\n\t\tsubnet: subnet,\n\t\tindex: int64(len(strings.Split(interfaces, \"\\n\"))),\n\t\tinstanceID: instanceID,\n\t\tsecurityGroups: strings.Split(securityGroups, \"\\n\"),\n\t\tvpc: vpc,\n\t}, nil\n}", "func New(path string) (*Config, error) {\n\ttree, err := toml.LoadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Config{tree: tree}, nil\n}", "func New(opts ...Option) Config {\n\tcfg := Config{\n\t\tFormat: gnfmt.CSV,\n\t\tLanguage: lang.English,\n\t\tWithBayes: true,\n\t\tBayesOddsThreshold: 80.0,\n\t\tTokensAround: 0,\n\t\tVerifierURL: \"https://verifier.globalnames.org/api/v1/\",\n\t\tTikaURL: \"https://tika.globalnames.org\",\n\t\tAPIDoc: \"https://apidoc.globalnames.org/gnfinder\",\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(&cfg)\n\t}\n\n\tif len(cfg.DataSources) > 0 {\n\t\tcfg.WithVerification = true\n\t}\n\treturn cfg\n}", "func New() *Config {\n\tcfg := &Config{}\n\tcfg.SetDefaults()\n\tcfg.ChangedCH = make(chan bool)\n\treturn cfg\n}", "func New() *Config {\n\treturn &Config{ Modules: []*Module{} }\n}", "func newConfig(envParams envParams) error {\n\t// Initialize server config.\n\tsrvCfg := newServerConfigV14()\n\n\t// If env is set for a fresh start, save them to config file.\n\tif globalIsEnvCreds {\n\t\tsrvCfg.SetCredential(envParams.creds)\n\t}\n\n\tif globalIsEnvBrowser {\n\t\tsrvCfg.SetBrowser(envParams.browser)\n\t}\n\n\t// Create config path.\n\tif err := createConfigDir(); err != nil {\n\t\treturn err\n\t}\n\n\t// hold the mutex lock before a new config is assigned.\n\t// Save the new config globally.\n\t// unlock the mutex.\n\tserverConfigMu.Lock()\n\tserverConfig = srvCfg\n\tserverConfigMu.Unlock()\n\n\t// Save config into file.\n\treturn serverConfig.Save()\n}", "func newNetwork(peers ...stateMachine) *network {\n\treturn newNetworkWithConfig(nil, peers...)\n}", "func newTraceExporter(config *Config, transportChannel transportChannel, logger *zap.Logger) (exporter.TraceExporter, error) {\n\n\texporter := &traceExporter{\n\t\tconfig: config,\n\t\ttransportChannel: transportChannel,\n\t\tlogger: logger,\n\t}\n\n\texp, err := exporterhelper.NewTraceExporter(\n\t\tconfig,\n\t\texporter.pushTraceData,\n\t\texporterhelper.WithTracing(true),\n\t\texporterhelper.WithMetrics(true))\n\n\treturn exp, err\n}", "func New(pushURL, owner string) {\n\tSave(pushURL, config.Tart{\n\t\tName: pushURL,\n\t\tPushURL: pushURL,\n\t\tIsRunning: false,\n\t\tOwners: []string{owner},\n\t\tPID: -1,\n\t\tRestartDelaySecs: 30,\n\t\tRestartOnStop: false,\n\t\tLogStdout: true,\n\t})\n}", "func (o *out) NewWithConfig(ctx context.Context, conf ast.Node, l spray.Logger) (spray.Sprayer, error) {\n\tc := &conspray{logger: new(discardLog)}\n\tif l != nil {\n\t\tc.logger = l\n\t}\n\treturn c, nil\n}", "func newCfg() *cfg {\n\tcfg := &cfg{}\n\n\tflag.IntVar(&cfg.pool, \"pool\", 32,\n\t\t\"count of the workers in pool (default: 32)\")\n\n\tflag.BoolVar(&cfg.greedy, \"greedy\", true,\n\t\t\"enable greedy mode (default: true)\")\n\n\tflag.DurationVar(&cfg.dur, \"duration\", time.Minute,\n\t\t\"pool's heartbeat duration\")\n\n\tflag.Parse()\n\n\treturn cfg\n}", "func createConfig(ctx context.Context, req *events.Request) *config {\n\treturn &config{\n\t\tlog: l.Create(ctx, l.Input{\n\t\t\t\"service\": service,\n\t\t\t\"function\": function,\n\t\t\t\"env\": os.Getenv(\"ENVIRONMENT\"),\n\t\t\t\"stackId\": req.StackID,\n\t\t\t\"requestType\": req.RequestType,\n\t\t\t\"requestId\": req.RequestID,\n\t\t\t\"resourceType\": req.ResourceType,\n\t\t\t\"logicalResourceId\": req.LogicalResourceID,\n\t\t\t\"resourceProperties\": req.ResourceProperties,\n\t\t\t\"oldResourceProperties\": req.OldResourceProperties,\n\t\t}),\n\t\tphysicalID: \"NotAviable\",\n\t\tresourceProperties: &Client{},\n\t\toldResourceProperties: &Client{},\n\t}\n}", "func NewConfig() (c *Config, lisErr *listtoErr.ListtoError) {\n\tdefer func() {\n\t\tif lisErr != nil {\n\t\t\tlisErr.SetCallingMethodIfNil(\"NewConfig\")\n\t\t}\n\t}()\n\n\ttoken := strings.TrimSpace(os.Getenv(\"LISTTO_TOKEN\"))\n\tif token == \"\" {\n\t\tlisErr = listtoErr.InvalidEnvvar(\"token\")\n\t\treturn\n\t}\n\n\tprefix := strings.TrimSpace(os.Getenv(\"LISTTO_PREFIX\"))\n\tif prefix == \"\" {\n\t\tprefix = \"^\"\n\t}\n\n\tc = new(Config)\n\tc.Token = token\n\tc.Prefix = prefix\n\n\treturn\n}", "func NewConfig(opts ...Option) *Config {\n\tc := Config{\n\t\ttree: make(tree),\n\t\tParms: &Parms{\n\t\t\tDex: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t\tExc: list{RWMutex: &sync.RWMutex{}, entry: make(entry)},\n\t\t},\n\t}\n\tfor _, opt := range opts {\n\t\topt(&c)\n\t}\n\treturn &c\n}", "func New(memberID, listenAddress, etcdPrefix string, etcdMembers []string, dalClient dal.IDal, eqClient *event.Client) *Config {\n\tcfg := &Config{\n\t\tListenAddress: listenAddress,\n\t\tEtcdPrefix: etcdPrefix,\n\t\tEtcdMembers: etcdMembers,\n\t\tDalClient: dalClient,\n\t\tEQClient: eqClient,\n\t\tMemberID: memberID,\n\t}\n\n\treturn cfg\n}", "func New(c *Config) (*Relay, error) {\n\t// make a new relay\n\tr := &Relay{\n\t\tc: &http.Client{},\n\t}\n\n\t// if they gave us a config, use it\n\tif c != nil {\n\t\tr.to = c.To\n\t\tr.from = c.From\n\t\tr.key = c.Key\n\t\tr.domain = c.Domain\n\t} else { // otherwise read config.json\n\t\tinfile, err := os.Open(\"config.json\")\n\t\tdefer infile.Close()\n\t\tif err != nil {\n\t\t\treturn nil, ErrNoConfig\n\t\t}\n\n\t\tdec := json.NewDecoder(infile)\n\n\t\tconfig := new(Config)\n\t\terr = dec.Decode(config)\n\t\tif err != nil {\n\t\t\treturn nil, ErrBadConfig\n\t\t}\n\n\t\tr.to = config.To\n\t\tr.from = config.From\n\t\tr.key = config.Key\n\t\tr.domain = config.Domain\n\t}\n\n\t// ensure all necessary fields are set\n\tif r.to == \"\" || r.from == \"\" || r.key == \"\" || r.domain == \"\" {\n\t\treturn nil, ErrBadConfig\n\t} else {\n\t\treturn r, nil\n\t}\n}", "func New(file string) (conf *Config, err error) {\n\tconf = &Config{\n\t\tLogLevel: \"info\",\n\t\tSite: \"default\",\n\t\taudit: []auditors.Auditor{},\n\t}\n\n\trawconf, err := os.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not read config file %s\", file)\n\t}\n\n\terr = json.Unmarshal(rawconf, conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse config file %s\", file)\n\t}\n\n\tccfg, err := cconf.NewConfig(conf.ChoriaConfigFile)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not parse choria config %s\", conf.ChoriaConfigFile)\n\t}\n\n\tccfg.LogFile = conf.LogFile\n\tccfg.LogLevel = conf.LogLevel\n\tccfg.RPCAuthorization = false\n\n\t// by definition these are clients who do not have security credentials, verification is based on the JWT\n\tccfg.DisableSecurityProviderVerify = true\n\n\tconf.fw, err = choria.NewWithConfig(ccfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"could not configure choria\")\n\t}\n\n\terr = configureAuthenticator(conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not configure %s authenticator\", conf.AuthenticatorType)\n\t}\n\n\terr = configureSigner(conf)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"could not configure %s signer\", conf.SignerType)\n\t}\n\n\treturn conf, nil\n}", "func New() *Config {\n\tvar conf Config\n\tappName := \"live-config\"\n\n\terr := envconfig.Process(appName, &conf)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn &conf\n}", "func (s *cpuSource) NewConfig() source.Config { return newDefaultConfig() }", "func New(nftOutPath string) Endpoint {\n\treturn config{\n\t\tnftOutPath: nftOutPath,\n\t}\n}", "func NewConfig() Config {\n\tlc := LocalConfig{\n\t\tAddr: new(string),\n\t\tCloseStdDesc: new(bool),\n\t\tPProfAddr: new(string),\n\t\tAutoConnect: new(bool),\n\t\tCertFile: new(string),\n\t\tKeyFile: new(string),\n\t\tConnTimeout: new(int64),\n\t\tPort: new(int),\n\t\tRootCA: new(string),\n\t}\n\tpprof := PProfConfig{\n\t\tCPUProfileFile: new(string),\n\t\tMemoryProfileFile : new(string),\n\t}\n\tc := Config{\n\t\tLocal: lc,\n\t\tDb: da.DbConfig{},\n\t\tPProf: pprof,\n\t\tCache: cache.NewConfig(),\n\t}\n\n\t\n\n\treturn c\n}", "func NewTracer(parent *Logger, prefix string) *Logger {\n\treturn &Logger{parent: parent, prefix: prefix, tracer: true}\n}", "func New(b *beat.Beat, cfg *common.Config) (beat.Beater, error) {\n\tc := config.DefaultConfig\n\tif err := cfg.Unpack(&c); err != nil {\n\t\treturn nil, fmt.Errorf(\"Error reading config file: %v\", err)\n\t}\n\n\tbt := &trivybeat{\n\t\tdone: make(chan struct{}),\n\t\tconfig: c,\n\t}\n\treturn bt, nil\n}", "func NewConfig() *Config {\n\treturn &Config{\n\t\tBindAddr: \"127.0.0.1:8080\",\n\t\tNetwork: \"udp4\",\n\t}\n}", "func New() (*Config, error) {\n\tc := &Config{}\n\terr := env.Parse(c)\n\treturn c, err\n}", "func NewConfig() *Config {\n\treturn &Config{NodeAddresses: make(map[string]string)}\n}", "func New(timeout time.Duration) *Config {\n\treturn &Config{\n\t\ttimeout: timeout,\n\t\tcontent: make(map[string]*futures.Expirable),\n\t}\n}", "func New(config *Config) (Logger, error) {\n\troot = logrus.New()\n\tif err := SetOutput(config.Output); err != nil {\n\t\treturn nil, err\n\t}\n\t// Set level\n\tif err := SetLevel(config.Level); err != nil {\n\t\treturn nil, err\n\t}\n\tconsole := false\n\tswitch config.Output {\n\tcase \"stdout\":\n\t\tconsole = true\n\tcase \"stderr\":\n\t\tconsole = true\n\tcase \"split\":\n\t\tconsole = true\n\t}\n\tif console {\n\t\tSetTextFormatter(config.ConsoleFormat)\n\t} else {\n\t\tSetJSONFormatter()\n\t}\n\t// Add global fields\n\tSetFields(config.Fields)\n\tlogg = &logger{\n\t\tentry: logrus.NewEntry(root),\n\t\tconfig: config,\n\t}\n\treturn logg, nil\n}", "func NewConfig() Config {\n\tc := Config{}\n\tc.Forwards = map[string][]PortMappings{}\n\treturn c\n}", "func New(config Config) (spec.Forwarder, error) {\n\tnewForwarder := &forwarder{\n\t\tConfig: config,\n\n\t\tID: id.MustNew(),\n\t\tType: ObjectType,\n\t}\n\n\t// Dependencies.\n\tif newForwarder.FactoryCollection == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"factory collection must not be empty\")\n\t}\n\tif newForwarder.Log == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"logger must not be empty\")\n\t}\n\tif newForwarder.StorageCollection == nil {\n\t\treturn nil, maskAnyf(invalidConfigError, \"storage collection must not be empty\")\n\t}\n\n\t// Settings.\n\tif newForwarder.MaxSignals == 0 {\n\t\treturn nil, maskAnyf(invalidConfigError, \"maximum signals must not be empty\")\n\t}\n\n\tnewForwarder.Log.Register(newForwarder.GetType())\n\n\treturn newForwarder, nil\n}", "func New() Config {\n\tvar conf Config\n\tif _, err := toml.DecodeFile(configFilename, &conf); err != nil {\n\t\tpanic(err)\n\t}\n\treturn conf\n}", "func New() JsonnetFile {\n\treturn JsonnetFile{\n\t\tDependencies: make(map[string]Dependency),\n\t}\n}", "func New(path string) (*viper.Viper, error) {\r\n\tif c, ok := os.LookupEnv(\"ANTENNA_CONFIG\"); ok {\r\n\t\tpath = c\r\n\t}\r\n\r\n\tv := viper.New()\r\n\tif path != \"\" {\r\n\t\tv.SetConfigFile(path)\r\n\t\tif err := v.ReadInConfig(); err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t}\r\n\tv.SetEnvPrefix(\"ANTENNA\")\r\n\tv.SetEnvKeyReplacer(strings.NewReplacer(\".\", \"_\"))\r\n\tv.AutomaticEnv()\r\n\treturn v, nil\r\n}", "func New() Config {\n\treturn Config{\n\t\tDatabase: \"messaging\",\n\t\tThreadColl: \"thread\",\n\t\tMessageColl: \"message\",\n\t}\n}", "func New(config Config) (*zap.Logger, error) {\n\tvar c zap.Config\n\tif config.Development {\n\t\tc = zap.NewDevelopmentConfig()\n\t\tc.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder\n\t} else {\n\t\tc = zap.NewProductionConfig()\n\t}\n\n\tlevel := zap.NewAtomicLevel()\n\terr := level.UnmarshalText([]byte(config.Level))\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tc.DisableStacktrace = true\n\tc.Encoding = config.Encoding\n\tc.Development = config.Development\n\tc.DisableCaller = config.DisableCaller\n\tc.Level = level\n\n\tlogger, err := c.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\t_ = logger.Sync()\n\t}()\n\n\treturn logger, nil\n}", "func NewConfig(logger *zap.Logger) *config {\n\tcwd, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Fatal(\"Error getting current working directory.\", zap.Error(err))\n\t}\n\treturn &config{\n\t\tName: \"nakama\",\n\t\tDatadir: filepath.Join(cwd, \"data\"),\n\t\tShutdownGraceSec: 0,\n\t\tLogger: NewLoggerConfig(),\n\t\tMetrics: NewMetricsConfig(),\n\t\tSession: NewSessionConfig(),\n\t\tSocket: NewSocketConfig(),\n\t\tDatabase: NewDatabaseConfig(),\n\t\tSocial: NewSocialConfig(),\n\t\tRuntime: NewRuntimeConfig(),\n\t\tMatch: NewMatchConfig(),\n\t\tTracker: NewTrackerConfig(),\n\t\tConsole: NewConsoleConfig(),\n\t\tLeaderboard: NewLeaderboardConfig(),\n\t}\n}", "func New() Config {\n\treturn Config{\n\t\tAPIHost: \":9999\",\n\t\tDBConnInfo: \"/Users/robertrowe/go/src/github.com/rippinrobr/lunch-n-learn/database/colada-lottery.db\",\n\t\tDBType: \"sqlite3\",\n\t}\n}", "func New(w io.Writer) Tracer{\n\treturn &tracer{out:w}\n}", "func New() *Config {\n\treturn &Config{DataFormat: \"influx\"}\n}", "func newOpentelemetryTracerProvider(address string, customAttributes ...attribute.KeyValue) (*tracesdk.TracerProvider, error) {\n\t// Same as Grafana core\n\tclient := otlptracegrpc.NewClient(otlptracegrpc.WithEndpoint(address), otlptracegrpc.WithInsecure())\n\texp, err := otlptrace.New(context.Background(), client)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn initTracerProvider(exp, customAttributes...)\n}" ]
[ "0.63668066", "0.6287799", "0.6007782", "0.5997846", "0.5991698", "0.5963639", "0.59091645", "0.5867563", "0.58512455", "0.5826894", "0.5795078", "0.5785921", "0.57754505", "0.576236", "0.57603073", "0.5747832", "0.5725367", "0.5711215", "0.57026625", "0.5671328", "0.5662771", "0.56266236", "0.56222564", "0.5619804", "0.55891013", "0.5585764", "0.55853087", "0.5577193", "0.55709475", "0.556435", "0.55399114", "0.5497834", "0.5494713", "0.5488787", "0.54811734", "0.5471304", "0.5465026", "0.54541874", "0.5453666", "0.5453666", "0.5447445", "0.5430697", "0.5428041", "0.54179966", "0.5414596", "0.54122394", "0.53962404", "0.5395125", "0.53831327", "0.53805315", "0.5378079", "0.5377621", "0.53661877", "0.53656983", "0.5365321", "0.5364724", "0.5362422", "0.53586525", "0.53576845", "0.53573", "0.53529644", "0.5346408", "0.5345146", "0.53450525", "0.53276265", "0.53273255", "0.53269756", "0.5291329", "0.5290541", "0.5286851", "0.52795273", "0.5269746", "0.5264501", "0.5263981", "0.52572465", "0.5254864", "0.524925", "0.52471423", "0.5247005", "0.5246244", "0.5244038", "0.52428263", "0.52404755", "0.5239162", "0.5239031", "0.5234112", "0.5230036", "0.522782", "0.5227775", "0.52169067", "0.5216571", "0.52107084", "0.52056736", "0.52019924", "0.5195719", "0.51940984", "0.5178789", "0.51774734", "0.5172451", "0.5172099" ]
0.5757199
15
NewPoint is a Point constructor. It only takes one Z argument, since W defaults to 1, i.e. the point is already normalized.
func NewPoint(Z complex128) *Point { return &Point{Z, 1} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewPoint(x, y, z float64) Point {\n\treturn Point{x, y, z, pointW}\n}", "func NewPoint(x, y, z float64) Tuple {\n\treturn Tuple{\n\t\tX: x,\n\t\tY: y,\n\t\tZ: z,\n\t\tW: pointW,\n\t}\n}", "func NewPoint(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 1.0}\n}", "func NewPoint(x1, y1 int) Point {\n\treturn Point{X: x1, Y: y1}\n}", "func NewPoint(x, y int) Point {\n\treturn Point{x, y}\n}", "func NewPoint(x, y int) Point {\n\treturn Point{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func New(x, y int) *Point {\n\treturn &Point{\n\t\tx: x,\n\t\ty: y,\n\t}\n}", "func NewPoint(x float32, y float32) *Point {\n\treturn &Point{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func NewPoint(latitude float64, longitude float64) *Point {\n return &Point{latitude: latitude, longitude: longitude}\n}", "func NewPoint(x, y int) *Point {\n\treturn &Point{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func NewPoint(x, y int) *Point {\n\treturn &Point{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func NewPoint() *Point {\n\tx := rand.Float(-100, 101)\n\ty := rand.Float(-100, 101)\n\n\tlabel := -1\n\tif x > y { // f(x) = x (identity function)\n\t\tlabel = 1\n\t}\n\n\treturn &Point{\n\t\tX: x,\n\t\tY: y,\n\t\tLabel: label,\n\t\tBias: 1,\n\t}\n}", "func NewPoint(lon, lat float64) Point {\n\treturn Point{\n\t\tLon: lon,\n\t\tLat: lat,\n\t}\n}", "func NewPoint(x, y float64) *Point {\n\tp := Point{Type: \"point\", Coordinates: []float64{x, y}}\n\treturn &p\n}", "func NewPoint(s *Space, x, y float64) Point {\n\treturn Point{physics.NewVector(x, y), s}\n}", "func NewPoint(lat, lng float64) Location {\r\n\treturn Location{\r\n\t\t\"Point\",\r\n\t\t[]float64{lng, lat},\r\n\t}\r\n}", "func NewPoint(lat float64, lng float64) Point {\n\treturn Point{lng, lat}\n}", "func (c *Curve) NewPoint(x, y float64) (CurvePoint, error) {\n\n\tvar point CurvePoint\n\n\tif !c.IsPointOnCurve(x, y) {\n\t\terr := fmt.Errorf(\"Point (%f, %f) is not on y^2 = x^3 + %fx + %f\", x, y, c.a, c.b)\n\t\treturn point, err\n\t}\n\n\tpoint.x = x\n\tpoint.y = y\n\tpoint.order = -1\n\tpoint.curve = c\n\n\treturn point, nil\n}", "func NewPoint(x, y float64, data interface{}) *Point {\n\treturn &Point{x, y, data}\n}", "func NewPoint(intensity colour.Colour, position vector.Vector) *Point {\n\treturn &Point{intensity: intensity, position: position}\n}", "func NewPoint(name string) (*Point, error) {\n\tif name == \"\" {\n\t\treturn nil, ErrNameEmptyOrNull\n\t}\n\n\tif len(name) > 3 {\n\t\treturn nil, ErrInvalidName\n\t}\n\n\treturn &Point{\n\t\tName: name,\n\t\tConnections: make([]*Connection, 0),\n\t}, nil\n}", "func NewPoint(lat, lng float64) *Point {\n\tpos := MakePosition(lat, lng)\n\treturn (*Point)(&pos)\n}", "func NewPoint(group Group) Point {\n\treturn C.EC_POINT_new(group)\n}", "func NewPoint(color *math32.Color, intensity float32) *Point {\n\n\tlp := new(Point)\n\tlp.Node.Init(lp)\n\tlp.color = *color\n\tlp.intensity = intensity\n\n\t// Creates uniform and sets initial values\n\tlp.uni.Init(\"PointLight\")\n\tlp.SetColor(color)\n\tlp.SetIntensity(intensity)\n\tlp.SetLinearDecay(1.0)\n\tlp.SetQuadraticDecay(1.0)\n\treturn lp\n}", "func NewPoint() api.IPoint {\n\to := new(point)\n\treturn o\n}", "func NewPoint(lat float64, lng float64) *Point {\n\treturn &Point{lat: lat, lng: lng}\n}", "func NewPoints() Points {\n\treturn Points{\n\t\t\"P\": NewAttributes(Vector, 3),\n\t}\n}", "func create_point(x float64, y float64) Point{\n\tp1 := Point{ x:x, y:y,}\n\treturn p1\n}", "func NewPoint(s data.Point) Point {\n\tvar time *time.Time\n\n\tif !s.Time.IsZero() {\n\t\ttime = &s.Time\n\t}\n\n\treturn Point{\n\t\tType: s.Type,\n\t\tKey: s.Key,\n\t\tValue: s.Value,\n\t\tTime: time,\n\t}\n}", "func Point(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 1.0}\n}", "func NewFzPoint() *FzPoint {\n\treturn (*FzPoint)(allocFzPointMemory(1))\n}", "func newPoint(v *view.View, row *view.Row, start, end time.Time) *monitoringpb.Point {\n\tswitch v.Aggregation.Type {\n\tcase view.AggTypeLastValue:\n\t\treturn newGaugePoint(v, row, end)\n\tdefault:\n\t\treturn newCumulativePoint(v, row, start, end)\n\t}\n}", "func NewPoints(igeom geometry.IGeometry, imat material.IMaterial) *Points {\n\n\tp := new(Points)\n\tp.Graphic.Init(p, igeom, gls.POINTS)\n\tif imat != nil {\n\t\tp.AddMaterial(p, imat, 0, 0)\n\t}\n\tp.uniMVPm.Init(\"MVP\")\n\tp.uniMVm.Init(\"MV\")\n\treturn p\n}", "func NewVertex(x, y, z float64) *Vertex {\n\treturn &Vertex{\n\t\tgeom.Point{x, y, z},\n\t\tnil,\n\t}\n}", "func newVertex(x, y, theta, v, w float64, parent *Vertex) *Vertex {\n\treturn &Vertex{Point{X: x, Y: y, Theta: theta, V: v, W: w}, parent, nil}\n}", "func NewPointPolicy(window *Window) *PointPolicy {\n\treturn &PointPolicy{\n\t\twindow: window,\n\t\tsize: window.Size(),\n\t\toffset: -1,\n\t}\n}", "func Point(x, y, z float64) Tuple {\n\treturn Tuple{x, y, z, 1}\n}", "func New(x, y, z float64) *Vector {\n\treturn &Vector{Scalar(x), Scalar(y), Scalar(z)}\n}", "func TestNewPoint(t *testing.T) {\n\tp := NewPoint(1, 1, 1)\n\tif (p.X != 1) || (p.X != 1) || (p.X != 1) {\n\t\tt.Log(\"Wrong assignment of the coordinates!\")\n\t\tt.Fail()\n\t}\n}", "func NewPointXY(x, y float64, f F) *Point {\n\tlabel := AboveF(x, y, f)\n\treturn &Point{\n\t\tX: x,\n\t\tY: y,\n\t\tLabel: label,\n\t\tBias: 1,\n\t}\n}", "func NewPoint3D(srId int, x float64, y float64, z float64) *Point {\n\treturn &Point{\n\t\tdimension: 3,\n\t\tsrId: srId,\n\t\tx: x,\n\t\ty: y,\n\t\tz: z,\n\t}\n}", "func (s *internalPointPtrView) New() (PointPtr, error) {\n\tslice, allocErr := s.state.makeSlice(1)\n\tif allocErr != nil {\n\t\treturn PointPtr{}, allocErr\n\t}\n\tptr := PointPtr{ptr: slice.data}\n\treturn ptr, nil\n}", "func New() *PointFeed {\n\td := &PointFeed{\n\t\tpoints: sync.Map{},\n\t\tsubs: sync.Map{},\n\t\tinput: make(chan coordinates.Point, bufferSize),\n\t}\n\tgo d.handleInput()\n\treturn d\n}", "func PointXYZ(x, y, z float64) Point {\n\treturn Point{x, y, z}\n}", "func NewVector(x, y, z float64) Vector {\n\treturn Vector{x, y, z, vectorW}\n}", "func (*Secp256k1) Point() kyber.Point {\n\treturn &secp256k1Point{newFieldZero(), newFieldZero()}\n}", "func NewAFPoint(w, h, x, y int16) AFPoint {\n\treturn AFPoint{w, h, x, y}\n}", "func NewVertex(x, y, z, u, v float64) *Vertex {\n\treturn &Vertex{\n\t\tPosition: vector.Vector{x, y, z},\n\t\tColor: NewColor(1, 1, 1, 1),\n\t\tUV: vector.Vector{u, v},\n\t\ttransformed: vector.Vector{0, 0, 0},\n\t}\n}", "func NewCoord(x, y, z, m float64) Coord {\n\treturn Coord{x, y, z, m}\n}", "func New_point(x big.Int,y big.Int) (Point) {\n\t\n\n\t// if !(0 <= x && float64(x)<FIELD_MODULUS) || !(0 <= y && float64(y)< FIELD_MODULUS){\n\t// \treturn Point{value: val},errors.New(\"Invalid value\")\n\t// }\n\t// y_packed = y | ((x & 1) << 255)\n\ttemp_x := x\n\ttemp_y := y\n\ty_packed := new(big.Int).Or(&temp_y,new(big.Int).Mul(new(big.Int).And(&temp_x,big.NewInt(1)),new(big.Int).Exp(big.NewInt(2), big.NewInt(255), nil)))\n\tval := y_packed.Bytes()\n\tfor i, j := 0, len(val)-1; i < j; i, j = i+1, j-1 { // reversal of bytes for little endian rep.\n\t\tval[i], val[j] = val[j], val[i]\n\t}\n\tfor len(val)<32 {\n\t\tval = append(val,0)\n\t}\n\treturn Point{x,y,val}\n\t// TODO: Error Checking\n\t\n\t\n}", "func NewGeoPoint(lat float64, lng float64) GeoPoint {\n\treturn GeoPoint{lat: lat, lng: lng}\n}", "func NewVector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func NewPointInt(x, y int) Point {\n\treturn Point{int8(x), int8(y)}\n}", "func (c *Curve) NewIdentityPoint() CurvePoint {\n\treturn CurvePoint{\n\t\tx: math.Inf(0),\n\t\ty: math.Inf(0),\n\t\tcurve: c,\n\t}\n}", "func New2DPoint(x, y float64) SimplePoint {\n\treturn SimplePoint{x, y}\n}", "func NewPointUsing(x, y float64) api.IPoint {\n\to := new(point)\n\to.x = x\n\to.y = y\n\treturn o\n}", "func (k Key) Point() *Point {\n\treturn New(k.X, k.Y)\n}", "func NewDataPoint(name string, value float64, unit Unit, dimensions ...Dimension) Point {\n\tp := Point{Name: name, Value: value, Unit: unit, Timestamp: time.Now().UTC()}\n\tp.AddDimensions(dimensions...)\n\treturn p\n}", "func NewCoordinate(x, y float64) Coordinate {\n\treturn Coordinate{X: x, Y: y}\n}", "func New(latitude, longitude float64, name string) *Place {\n\treturn &Place{saneAngle(0, latitude), saneAngle(0, longitude), name}\n}", "func (this *NurbsCurve) Point(u float64) vec3.T {\n\thomoPt := this.nonRationalPoint(u)\n\treturn homoPt.Dehomogenized()\n}", "func NewPoints(points []data.Point) []Point {\n\tret := make([]Point, len(points))\n\n\tfor i, p := range points {\n\t\tret[i] = NewPoint(p)\n\t}\n\n\treturn ret\n}", "func NewCoordinate(row, col int) Coordinate {\n\treturn Coordinate{row, col}\n}", "func InitNew() {\n\tPos = image.Point{}\n}", "func New(args ...float64) Tuple {\n\treturn args\n}", "func (p *Point) Clone() *Point {\n\treturn &Point{p.X, p.Y}\n}", "func NewFzPointRef(ref unsafe.Pointer) *FzPoint {\n\treturn (*FzPoint)(ref)\n}", "func NewMultiPoint(pos ...Position) *MultiPoint {\n\treturn (*MultiPoint)(&pos)\n}", "func New(p string, t time.Time) *PT {\n\treturn &PT{p, t}\n}", "func NewWhite() Vector3 {\n\treturn New(1, 1, 1)\n}", "func NewPoint2D(srId int, x float64, y float64) *Point {\n\treturn &Point{\n\t\tdimension: 2,\n\t\tsrId: srId,\n\t\tx: x,\n\t\ty: y,\n\t\tz: math.NaN(),\n\t}\n}", "func ( self * Akima_curve )\tPoint ( x float64 )\t\tfloat64\t{\n\tvar (\n\t\tx_minus_x1 = x - self.X1\n\t\tx_minus_x1_pow2\t= x_minus_x1 * x_minus_x1\n\t)\n\treturn\tself.p0 + self.p3 * x_minus_x1 * x_minus_x1_pow2 +\n\t\t\tself.T1 * x_minus_x1 + self.p2 * x_minus_x1_pow2\n}", "func NewPosition(x, y, z float64) Position {\n\treturn [3]float64{x, y, z}\n}", "func Point_one() (Point) { \n\ttoken := make([]byte,32)\n\ttoken[0]=1\n\treturn Point{*big.NewInt(0),*big.NewInt(0),token}\n}", "func NewPointWithElevation(lat, lng, elevation float64) *Point {\n\tpos := MakePositionWithElevation(lat, lng, elevation)\n\treturn (*Point)(&pos)\n}", "func (p Point) Minus(v Point) Point {\n\treturn NewPoint(p.X-v.X, p.Y-v.Y)\n}", "func NewCoord(x, y float64) *Coord {\n\treturn &Coord{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func NewCoord(x, y float64) *Coord {\n\treturn &Coord{\n\t\tx: x,\n\t\ty: y,\n\t}\n}", "func PointToVertex(dp geom.D3) *Vertex {\n\treturn NewVertex(dp.Val(0), dp.Val(1), dp.Val(2))\n}", "func NewPolygon(points ...floatgeom.Point2) (*Polygon, error) {\n\n\tif len(points) < 3 {\n\t\treturn nil, oakerr.InsufficientInputs{AtLeast: 3, InputName: \"points\"}\n\t}\n\n\t// Calculate the bounding rectangle of the polygon by\n\t// finding the maximum and minimum x and y values of the given points\n\treturn NewStrictPolygon(floatgeom.NewBoundingRect2(points...), points...)\n}", "func Pt(x, y float64) Point {\n\treturn Point{x, y}\n}", "func NewPlane(corner1 rays.Point, corner2 rays.Point, corner3 rays.Point, color rays.Point) Plane {\n\tp := Plane{Color: color, CornerOne: corner1, CornerTwo: corner2, CornerThree: corner3}\n\n\tp.normal = calcNormal(p)\n\n\treturn p\n}", "func (p Point) Add(v Point) Point {\n\treturn NewPoint(p.X+v.X, p.Y+v.Y)\n}", "func NewPointer(elem Type) *Pointer { return &Pointer{base: elem} }", "func newLocation(lat, long coordinate) *location {\n\treturn &location{lat.decimal(), long.decimal()}\n}", "func (s *Scalar) toPoint() Point {\n x,y := getCurve().ScalarBaseMult(s.data)\n return (Point { x, y })\n}", "func NewDistPoint(coords []int, dist float64) *PointWithDist {\n\tvar DP PointWithDist\n\tDP.Coords = coords\n\tDP.Dist = dist\n\treturn &DP\n}", "func NewVector(newX uint, newY uint) *Vector {\n\treturn &Vector{X: newX, Y: newY}\n}", "func NewPointAffine(x, y fr.Element) PointAffine {\n\treturn PointAffine{x, y}\n}", "func Pt(x, y int) Point {\n\treturn Point{x, y}\n}", "func (geom Geometry) AddPoint(x, y, z float64) {\n\tC.OGR_G_AddPoint(geom.cval, C.double(x), C.double(y), C.double(z))\n}", "func Pt(x, y int) Point {\n\treturn Point{X:x, Y:y}\n}", "func (ec *EC) Add(p, q *Point) *Point {\n\tif ec.Infinite(p) {\n\t\treturn &Point{new(big.Int).SetBytes(q.X.Bytes()), new(big.Int).SetBytes(q.Y.Bytes())}\n\t}\n\tif ec.Infinite(q) {\n\t\treturn &Point{new(big.Int).SetBytes(p.X.Bytes()), new(big.Int).SetBytes(p.Y.Bytes())}\n\t}\n\tif p.X.Cmp(q.X) == 0 && p.Y.Cmp(q.Y) != 0 {\n\t\treturn &Point{}\n\t}\n\tvar s *big.Int\n\t// https://ja.wikipedia.org/wiki/%E6%A5%95%E5%86%86%E6%9B%B2%E7%B7%9A#%E7%BE%A4%E6%A7%8B%E9%80%A0\n\tif p.X.Cmp(q.X) == 0 && p.Y.Cmp(q.Y) == 0 {\n\t\t// s = ( 3*Xp*Xp + a ) * ( 2*Yp ) ^ ( P - 2 ) mod P\n\t\ts = new(big.Int).Mod(\n\t\t\tnew(big.Int).Mul(\n\t\t\t\tnew(big.Int).Add(new(big.Int).Mul(new(big.Int).Mul(big.NewInt(3), p.X), p.X), ec.a),\n\t\t\t\tnew(big.Int).Exp(\n\t\t\t\t\tnew(big.Int).Mul(big.NewInt(2), p.Y),\n\t\t\t\t\tnew(big.Int).Sub(ec.P, big.NewInt(2)),\n\t\t\t\t\tec.P)),\n\t\t\tec.P)\n\t} else {\n\t\t// s = ( Yp - Yq ) * ( Xp - Xq ) ^ ( P - 2 ) mod P\n\t\ts = new(big.Int).Mod(\n\t\t\tnew(big.Int).Mul(\n\t\t\t\tnew(big.Int).Sub(p.Y, q.Y),\n\t\t\t\tnew(big.Int).Exp(\n\t\t\t\t\tnew(big.Int).Sub(p.X, q.X),\n\t\t\t\t\tnew(big.Int).Sub(ec.P, big.NewInt(2)),\n\t\t\t\t\tec.P)),\n\t\t\tec.P)\n\t}\n\tr := &Point{}\n\t// Xr = s*s - Xp - Xq mod P\n\tr.X = new(big.Int).Mod(new(big.Int).Sub(new(big.Int).Mul(s, s), new(big.Int).Add(p.X, q.X)), ec.P)\n\t// Yr = s*( Xp - Xr ) - Yp mod P\n\tr.Y = new(big.Int).Mod(new(big.Int).Sub(new(big.Int).Mul(s, new(big.Int).Sub(p.X, r.X)), p.Y), ec.P)\n\treturn r\n}", "func (p Point2D) ToPoint() Point {\n\treturn Point{p.X, p.Y, 0}\n}", "func NewEdwardsPoint() *EdwardsPoint {\n\tvar p EdwardsPoint\n\treturn p.Identity()\n}", "func NewPointToPoint() AStarConfig {\n\tp2p := &pointToPoint{}\n\n\treturn p2p\n}", "func (ts *Timeseries) AddNewPoint(v float64, x interface{}) error {\n\tts.Lock()\n\tdefer ts.Unlock() // unlocks at the end\n\n\tswitch T := x.(type) {\n\tcase int64:\n\t\tts.XY[T] = v\n\tcase time.Time:\n\t\tts.XY[T.UnixNano()] = v\n\tcase int:\n\t\tts.XY[int64(T)] = v\n\tdefault:\n\t\treturn fmt.Errorf(\"Adding point not possible\")\n\t}\n\n\treturn nil\n}", "func Point(x string) (geometry.Point, error) {\n\tif x[0] != '(' || x[len(x)-1] != ')' {\n\t\treturn geometry.Point{}, ErrBadPoint\n\t}\n\tfs := strings.Split(x[1:len(x)-1], \" \")\n\tif len(fs) != 2 {\n\t\treturn geometry.Point{}, ErrBadPoint\n\t}\n\tnx, err := Number(fs[0])\n\tif err != nil {\n\t\treturn geometry.Point{}, ErrBadPoint\n\t}\n\tny, err := Number(fs[1])\n\tif err != nil {\n\t\treturn geometry.Point{}, ErrBadPoint\n\t}\n\treturn geometry.Point{X: nx, Y: ny}, nil\n}", "func newPointFromLatLngStrings(latStr string, lngStr string) (*geo.Point, error) {\n\tlat, err1 := strconv.ParseFloat(latStr, 64)\n\tlng, err2 := strconv.ParseFloat(lngStr, 64)\n\tvar p *geo.Point\n\tif err1 != nil || err2 != nil {\n\t\tmsg := []string{\"Unable to convert \", latStr, \",\", lngStr, \" to a Point\"}\n\t\treturn nil, errors.New(strings.Join(msg, \"\"))\n\t}\n\tp = geo.NewPointFromLatLng(lat, lng)\n\treturn p, nil\n}", "func newOutPoint(txHash *chainhash.Hash, vout uint32) outPoint {\n\treturn outPoint{\n\t\ttxHash: *txHash,\n\t\tvout: vout,\n\t}\n}" ]
[ "0.8289436", "0.76452273", "0.73365086", "0.7122396", "0.70763147", "0.7061288", "0.7044858", "0.69908166", "0.6978003", "0.6913814", "0.6913814", "0.682751", "0.6785859", "0.6784859", "0.6770373", "0.67468137", "0.65999067", "0.6564521", "0.65005046", "0.64920133", "0.64630914", "0.63988125", "0.63678885", "0.6367557", "0.6358108", "0.6335459", "0.6303042", "0.62362415", "0.6142503", "0.5986144", "0.5966585", "0.59407634", "0.59024596", "0.58496183", "0.5825679", "0.5768221", "0.57374245", "0.57221276", "0.56759965", "0.5604893", "0.55809134", "0.5579291", "0.5576745", "0.5567898", "0.5545188", "0.551274", "0.5468875", "0.5395344", "0.53864336", "0.5368585", "0.5361754", "0.5319291", "0.531821", "0.53123933", "0.5310782", "0.52570844", "0.52206224", "0.520301", "0.52015465", "0.5191011", "0.5170716", "0.51235414", "0.5108546", "0.50927556", "0.50620794", "0.5060211", "0.50501615", "0.50220776", "0.5022033", "0.5021057", "0.5004822", "0.5002249", "0.4981897", "0.49733254", "0.49456933", "0.4944339", "0.4937254", "0.49321458", "0.49317223", "0.4921675", "0.49089947", "0.48851013", "0.48834756", "0.48650077", "0.48620275", "0.48594266", "0.48536104", "0.4851754", "0.4845243", "0.48425543", "0.4835254", "0.48239627", "0.48009276", "0.47970164", "0.47950658", "0.47836488", "0.47830153", "0.47760865", "0.47722274", "0.47713435" ]
0.7341503
2
Conj returns the conjugated point.
func Conj(p Point) Point { return Point{cmplx.Conj(p.Z), cmplx.Conj(p.W)} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Conj(value gcv.Value) gcv.Value {\n\treturn gcv.MakeValue(cmplx.Conj(value.Complex()))\n}", "func (z *BiComplex) Conj(y *BiComplex) *BiComplex {\n\tz.l.Set(&y.l)\n\tz.r.Neg(&y.r)\n\treturn z\n}", "func (z *Float64) Conj(y *Float64) *Float64 {\n\tz.l = y.l\n\tz.r = -y.r\n\treturn z\n}", "func (z *Perplex) Conj(y *Perplex) *Perplex {\n\tz.l.Set(&y.l)\n\tz.r.Neg(&y.r)\n\treturn z\n}", "func (z *InfraHamilton) Conj(y *InfraHamilton) *InfraHamilton {\n\tz.l.Conj(&y.l)\n\tz.r.Neg(&y.r)\n\treturn z\n}", "func (z *E12) Conjugate(x *E12) *E12 {\n\tz.Set(x)\n\tz.C1.Neg(&z.C1)\n\treturn z\n}", "func Conj(scope *Scope, input tf.Output) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Conj\",\n\t\tInput: []tf.Input{\n\t\t\tinput,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (q Quat) Conjugate() Quat {\n\treturn Quat{q.W, -q.X, -q.Y, -q.Z}\n}", "func (gd *Definition) ConatainsPoint(x, y, buf float64) bool {\n\tif x < gd.Eorig-buf {\n\t\treturn false\n\t}\n\tif x > gd.Eorig+float64(gd.Ncol)*gd.Cwidth+buf {\n\t\treturn false\n\t}\n\tif y > gd.Norig+buf {\n\t\treturn false\n\t}\n\tif y < gd.Norig-float64(gd.Nrow)*gd.Cwidth-buf {\n\t\treturn false\n\t}\n\treturn true\n}", "func RemoveConj(s *basically.Sentence) {\n\t// Sanity check to ensure that the string is sufficiently long.\n\tif len(s.Tokens) < 2 {\n\t\treturn\n\t}\n\n\tif s.Tokens[0].Tag == \"CC\" {\n\t\tidx := strings.Index(s.Raw, s.Tokens[0].Text)\n\t\tlen := utf8.RuneCountInString(s.Tokens[0].Text) + 1\n\t\ts.Raw = strings.TrimSpace(SubStr(s.Raw, idx+len, -1))\n\t\ts.Raw = Capitalize(s.Raw)\n\t\ts.Tokens = s.Tokens[1:]\n\t}\n}", "func (m *TMap) Conj(value interface{}) interface{} {\n\tentry := value.(Entry)\n\treturn m.Assoc(entry.Key(), entry.Value())\n}", "func (v Vect) c() C.cpVect {\n\tvar cp C.cpVect\n\tcp.x = C.cpFloat(v.X)\n\tcp.y = C.cpFloat(v.Y)\n\treturn cp\n}", "func (r *Ring) Convex() bool {\n\tif Cross(r.Prev().Value.(Point), r.Value.(Point), r.Next().Value.(Point)) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}", "func (s *Trainer) Convex() {}", "func JCS(r operand.Op) { ctx.JCS(r) }", "func (cm ConcurrenceModel) GetConcurrence(i, j int) float64 {\n\tweightIJ, exists := cm.concurrences[i][j]\n\tif exists {\n\t\treturn weightIJ\n\t} else {\n\t\treturn 0.0\n\t}\n}", "func JCC(r operand.Op) { ctx.JCC(r) }", "func (m Vec2Modulus) GetCongruent(v1, v2 mgl.Vec2) mgl.Vec2 {\n\treturn mgl.Vec2{\n\t\tm.x.GetCongruent(v1[0], v2[0]),\n\t\tm.y.GetCongruent(v1[1], v2[1]),\n\t}\n}", "func CollatzConjecture(n int) (int, error) {\n\tif n < 1 {\n\t\treturn -1, errors.New(\"input is less than 1\")\n\t}\n\tres := 0\n\tfor n != 1 {\n\t\tif n%2 == 0 {\n\t\t\tn /= 2\n\t\t} else {\n\t\t\tn = n*3 + 1\n\t\t}\n\t\tres++\n\t}\n\treturn res, nil\n}", "func Quat2Conjugate(out, a []float64) []float64 {\n\tout[0] = -a[0]\n\tout[1] = -a[1]\n\tout[2] = -a[2]\n\tout[3] = a[3]\n\tout[4] = -a[4]\n\tout[5] = -a[5]\n\tout[6] = -a[6]\n\tout[7] = a[7]\n\treturn out\n}", "func CollatzConjecture(n int) (int, error) {\n\tif n <= 0 {\n\t\treturn 0, errors.New(\"invalid input\")\n\t}\n\n\tsteps := 0\n\n\tfor n != 1 {\n\t\tsteps++\n\t\t//If n is even, divide n by 2 to get n / 2. If n is odd, multiply n by 3 and add 1 to get 3n + 1.\n\t\tif n%2 == 0 {\n\t\t\tn /= 2\n\t\t} else {\n\t\t\tn = n*3 + 1\n\t\t}\n\t}\n\n\treturn steps, nil\n}", "func (c *Coord) X() float64 { return c[0] }", "func (n *Node) Convconst(con *Node, t *Type)", "func (m Vec2Modulus) Congruent(vec mgl.Vec2) mgl.Vec2 {\n\treturn mgl.Vec2{\n\t\tm.x.Congruent(vec[0]),\n\t\tm.y.Congruent(vec[1]),\n\t}\n}", "func (a Ave) Cacareja() string {\n\treturn \"Cócóricó...\"\n}", "func CollatzConjecture(n int) (int, error) {\n\n\tsteps := 0\n\n\tif n <= 0 {\n\t\treturn n, fmt.Errorf(\"number n must be greater than 0\")\n\t}\n\n\tfor i := 1; n > 1; i++ {\n\t\tif n%2 == 0 {\n\t\t\tn /= 2\n\t\t} else {\n\t\t\tn = n*3 + 1\n\t\t}\n\t\tsteps = i\n\t}\n\n\treturn steps, nil\n}", "func (m Vec3Modulus) GetCongruent(v1, v2 mgl.Vec3) mgl.Vec3 {\n\treturn mgl.Vec3{\n\t\tm.x.GetCongruent(v1[0], v2[0]),\n\t\tm.y.GetCongruent(v1[1], v2[1]),\n\t\tm.z.GetCongruent(v1[2], v2[2]),\n\t}\n}", "func (curve *Curve) CompressPoint(X, Y *big.Int) (cp []byte) {\n\tby := new(big.Int).And(Y, big.NewInt(1)).Int64()\n\tbx := X.Bytes()\n\tcp = make([]byte, len(bx)+1)\n\tif by == 1 {\n\t\tcp[0] = byte(3)\n\t} else {\n\t\tcp[0] = byte(2)\n\t}\n\tcopy(cp[1:], bx)\n\n\treturn\n}", "func (a Vec2) Proj(b Vec2) Vec2 {\n\treturn b.MulScalar(a.Dot(b) / b.LengthSq())\n}", "func (c *Clac) Comb() error {\n\treturn c.applyInt(2, func(vals []value.Value) (value.Value, error) {\n\t\te := &eval{}\n\t\tnf := e.e(func() (value.Value, error) { return factorial(vals[1]) })\n\t\trf := e.e(func() (value.Value, error) { return factorial(vals[0]) })\n\t\tnr := e.binary(vals[1], \"-\", vals[0])\n\t\tnrf := e.e(func() (value.Value, error) { return factorial(nr) })\n\t\tdenom := e.binary(nrf, \"*\", rf)\n\t\tn := e.binary(nf, \"/\", denom)\n\t\treturn n, e.err\n\t})\n}", "func ConjugateTranspose(scope *Scope, x tf.Output, perm tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"ConjugateTranspose\",\n\t\tInput: []tf.Input{\n\t\t\tx, perm,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (p *Image64) Convolved(k Kernel64) *Image64 {\n\tswitch k.(type) {\n\tcase *separableKernel64:\n\t\treturn p.separableConvolution(k.(*separableKernel64))\n\tdefault:\n\t\treturn p.fullConvolution(k)\n\t}\n\tpanic(\"unreachable\")\n}", "func (m Vec4Modulus) GetCongruent(v1, v2 mgl.Vec4) mgl.Vec4 {\n\treturn mgl.Vec4{\n\t\tm.x.GetCongruent(v1[0], v2[0]),\n\t\tm.y.GetCongruent(v1[1], v2[1]),\n\t\tm.z.GetCongruent(v1[2], v2[2]),\n\t\tm.w.GetCongruent(v1[3], v2[3]),\n\t}\n}", "func (o NetworkGrantOutput) CcnId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkGrant) pulumi.StringOutput { return v.CcnId }).(pulumi.StringOutput)\n}", "func ComputeCommitmentPoint(commitSecret []byte) *btcec.PublicKey {\n\tx, y := btcec.S256().ScalarBaseMult(commitSecret)\n\n\treturn &btcec.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t\tCurve: btcec.S256(),\n\t}\n}", "func CollatzConjecture(input int) (int, error) {\n\tvar steps int = 0\n\tif input < 1 {\n\t\treturn 0, errors.New(\"Input must be positive integer\")\n\t}\n\tfor input != 1 {\n\t\tif input%2 == 0 {\n\t\t\tinput = input / 2\n\t\t\tsteps++\n\n\t\t} else {\n\t\t\tinput = (input * 3) + 1\n\t\t\tsteps++\n\t\t}\n\t}\n\treturn steps, nil\n}", "func (a Ave) Cacarejar() string {\n\treturn \"cocoricó\"\n}", "func cathetus(a, b Point) (cx, cy float64) {\n\tcx = math.Abs(b.x - a.x)\n\tcy = math.Abs(b.y - a.y)\n\n\treturn\n}", "func Contour(seg mapping.Segmentation) geo.Contour {\n\tpolygons := []geo.Polygon{}\n\tfor _, c := range getDualSampaContours(seg) {\n\t\tfor _, p := range c {\n\t\t\tpolygons = append(polygons, p)\n\t\t}\n\t}\n\tcontour, err := geo.NewContour(polygons)\n\tif err != nil {\n\t\tlog.Fatalf(\"could not get contour of segmentation: %v\", err)\n\t}\n\treturn contour\n}", "func CollatzConjecture(n int) (int, error) {\n\tif n < 1 {\n\t\treturn 0, errors.New(\"Number should be greater than equal to 1\")\n\t}\n\tsteps := 0\n\tfor ; n != 1; steps++ {\n\t\tif n%2 == 0 {\n\t\t\tn = n / 2\n\t\t} else {\n\t\t\tn = (3 * n) + 1\n\t\t}\n\t}\n\treturn steps, nil\n}", "func (c *Capsule) Min() Coord {\n\treturn c.P1.Min(c.P2).AddScalar(-c.Radius)\n}", "func GetCSDCOProj(identity string) *sparql.Results {\n\t// repo, err := sparql.NewRepo(\"http://data.oceandrilling.org/sparql\",\n\trepo, err := getJena()\n\tif err != nil {\n\t\tlog.Printf(\"%s\\n\", err)\n\t}\n\n\tf := bytes.NewBufferString(projdetails)\n\tbank := sparql.LoadBank(f)\n\n\t// q, err := bank.Prepare(\"my-query\", struct{ Limit, Offset int }{10, 100})\n\tq, err := bank.Prepare(\"csdcoproj\", struct{ ID string }{identity})\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\tlog.Println(q)\n\n\tres, err := repo.Query(q)\n\tif err != nil {\n\t\tlog.Print(err)\n\t}\n\n\treturn res\n}", "func (p *Pattern) Csimple() *Pattern {\n\treturn Csimple(p)\n}", "func (a Ave) Carcareja() string {\n\treturn \"cocorico\"\n}", "func (g *GeoPolygon) toCPtr() *C.GeoPolygon {\n\tif g.v != nil {\n\t\treturn g.v\n\t}\n\n\t// allocate memory for GeoPolygon\n\tpolyPtr := C.malloc(C.sizeof_GeoPolygon)\n\n\tg.v = (*C.GeoPolygon)(polyPtr)\n\n\t// if Exterior is not nil\n\tif g.Exterior != nil {\n\t\tif g.Exterior.GeoCoords != nil {\n\t\t\t// fmt.Printf(\"Before verts: %v\\n\", g.v.geofence.verts)\n\t\t\tg.v.geofence.verts = g.Exterior.GeoCoords.toCPtr()\n\t\t\t// fmt.Printf(\"After verts: %v\\n\", g.v.geofence.verts)\n\t\t\tg.v.geofence.numVerts = C.int(len(g.Exterior.GeoCoords.Coords))\n\t\t\t// fmt.Printf(\"NumHoles: %v\\n\", g.v.geofence.numVerts)\n\t\t}\n\t}\n\n\tif len(g.Holes) > 0 {\n\t\t// malloc the *GeoCoord for the provided coordinates\n\t\tptr := C.malloc(C.size_t(len(g.Holes)) * C.sizeof_Geofence)\n\n\t\tholesArr := (*[1 << 30]C.Geofence)(unsafe.Pointer(ptr))[:len(g.Holes):len(g.Holes)]\n\t\tfor i, hole := range g.Holes {\n\t\t\tholesArr[i].verts = hole.GeoCoords.toCPtr()\n\t\t\tholesArr[i].numVerts = C.int(len(hole.GeoCoords.Coords))\n\t\t}\n\t\tg.v.holes = (*C.Geofence)(ptr)\n\t} else {\n\t\tg.v.holes = nil\n\t}\n\n\tg.v.numHoles = C.int(len(g.Holes))\n\treturn g.v\n}", "func c1(n int) int { return n - WIDTH - 1 }", "func (o ServiceOutput) ConvergeConfig() ServiceConvergeConfigPtrOutput {\n\treturn o.ApplyT(func(v *Service) ServiceConvergeConfigPtrOutput { return v.ConvergeConfig }).(ServiceConvergeConfigPtrOutput)\n}", "func (p *Pattern) Csubst() *Pattern {\n\treturn Csubst(p)\n}", "func (c *Circle) Min() Coord {\n\treturn c.Center.AddScalar(-c.Radius)\n}", "func JOC(r operand.Op) { ctx.JOC(r) }", "func (pe *PathEnd) ConnConfirm(dstConnState *conntypes.QueryConnectionResponse, signer sdk.AccAddress) sdk.Msg {\n\treturn conntypes.NewMsgConnectionOpenConfirm(\n\t\tpe.ConnectionID,\n\t\tdstConnState.Proof,\n\t\tdstConnState.ProofHeight,\n\t\tsigner,\n\t)\n}", "func DigitToConsonantTable() string {\n\tvar b bytes.Buffer\n\n\tfor i := 0; i < numDigit; i++ {\n\t\tlist := DigitToConsonant(i)\n\t\tb.WriteString(fmt.Sprintf(\"%d = %v\\n\", i, list))\n\t}\n\treturn b.String()\n}", "func PieceCommitmentV1ToCID(commP []byte) cid.Cid {\n\treturn DataCommitmentV1ToCID(commP)\n}", "func CollatzConjecture(n int) []int {\n\tsequence := make([]int, 0)\n\tcurrent := n\n\tfor current > 1 {\n\t\tsequence = append(sequence, current)\n\t\tif current%2 == 0 {\n\t\t\tcurrent = current / 2\n\t\t} else {\n\t\t\tcurrent = 3*current + 1\n\t\t}\n\t}\n\tsequence = append(sequence, current)\n\treturn sequence\n}", "func CircIn(t, b, c, d float64) float64 {\n\tif t > d {\n\t\treturn c\n\t}\n\n\tt /= d\n\n\treturn -c*(math.Sqrt(1-t*t)-1) + b\n}", "func CollatzConjecture(n int) (int, error) {\n\tif n < 1 {\n\t\treturn 0, errors.New(\"input must be at least 1\")\n\t}\n\n\tvar steps int = 0\n\tfor n != 1 {\n\t\tn = CollatzStep(n)\n\t\tsteps += 1\n\t}\n\treturn steps, nil\n}", "func CollatzConjecture(number int) (int, error) {\n\tif number < 1 {\n\t\treturn -1, errors.New(\"function doesn't work with a negative or zero number\")\n\t}\n\n\tcounter := 0\n\tfor ; number > 1; number = step(number) {\n\t\tcounter++\n\t}\n\n\treturn counter, nil\n}", "func (l *LinkedGeoPolygon) toCPtr() *C.LinkedGeoPolygon {\n\tl.v = &C.LinkedGeoPolygon{}\n\treturn l.v\n}", "func (o GetTrafficPolicyDocumentRuleLocationOutput) Continent() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v GetTrafficPolicyDocumentRuleLocation) *string { return v.Continent }).(pulumi.StringPtrOutput)\n}", "func CircOut(t, b, c, d float64) float64 {\n\tif t > d {\n\t\treturn c\n\t}\n\n\tt /= d\n\tt--\n\n\treturn c*math.Sqrt(1-t*t) + b\n}", "func FindCelebrity(matrix [][]int) int {\n\n\tn, i, j := len(matrix), 0, 1\n\n\tfor j < n {\n\n\t\tif matrix[i][j] == 1 { // means 'j' is known and 'i' is definitely not the celebrity\n\t\t\ti=j+1\n\t\t\ti=j\n\t\t} else { // 'j' is not known and he is not the celebrity\n\t\t\tj=j+1\n\t\t}\n\t}\n\n\treturn i\n}", "func calculateMinimalCost(mural string, X, Y int) int {\n\tif len(mural) == 0 || len(mural) == 1 {\n\t\treturn 0\n\t}\n\tcost := 0\n\tvar prevCharacter = ' '\n\tvar postCharacter = ' '\n\tfor i := 0; i < len(mural); i++ {\n\t\tif mural[i] == '?' {\n\t\t\tif i-1 >= 0 {\n\t\t\t\tprevCharacter = rune(mural[i-1])\n\t\t\t}\n\t\t\tfor i < len(mural) && mural[i] == '?' {\n\t\t\t\ti++\n\t\t\t}\n\t\t\tif i != len(mural) {\n\t\t\t\tpostCharacter = rune(mural[i])\n\t\t\t}\n\t\t\tif prevCharacter == 'C' && postCharacter == 'J' {\n\t\t\t\tcost += X\n\t\t\t} else if prevCharacter == 'J' && postCharacter == 'C' {\n\t\t\t\tcost += Y\n\t\t\t}\n\t\t\tprevCharacter = ' '\n\t\t\tpostCharacter = ' '\n\t\t\ti--\n\t\t}\n\t}\n\n\t//calculate the original cost\n\tfor i := 0; i < len(mural)-1; i++ {\n\t\tif mural[i:i+2] == \"CJ\" {\n\t\t\tcost += X\n\t\t} else if mural[i:i+2] == \"JC\" {\n\t\t\tcost += Y\n\t\t}\n\t}\n\treturn cost\n}", "func JC(r operand.Op) { ctx.JC(r) }", "func (m Vec3Modulus) Congruent(vec mgl.Vec3) mgl.Vec3 {\n\treturn mgl.Vec3{\n\t\tm.x.Congruent(vec[0]),\n\t\tm.y.Congruent(vec[1]),\n\t\tm.z.Congruent(vec[2]),\n\t}\n}", "func (m *PatientMutation) Congenital() (r string, exists bool) {\n\tv := m._Congenital\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m *DiseaseMutation) Contagion() (r string, exists bool) {\n\tv := m._Contagion\n\tif v == nil {\n\t\treturn\n\t}\n\treturn *v, true\n}", "func (m Vec4Modulus) Congruent(vec mgl.Vec4) mgl.Vec4 {\n\treturn mgl.Vec4{\n\t\tm.x.Congruent(vec[0]),\n\t\tm.y.Congruent(vec[1]),\n\t\tm.z.Congruent(vec[2]),\n\t\tm.w.Congruent(vec[3]),\n\t}\n}", "func CN(noot string, index int) string {\n\tvar nootClean string\n\tvar tmpval string\n\tvar vastus string\n\tvar variatsioon bool\n\t//Kui väli on tühi siis saadame tühja vastuse\n\tif len(noot) == 0 {\n\t\treturn \"<empty>\"\n\t}\n\t//Alternatiivide puhul võtame välja esimese ja teise alternatiivi\n\tif index == 1 && string(noot[len(noot)-1:]) == \"]\" {\n\t\tnootClean = (strings.Split(noot, \"[\"))[0]\n\t} else if index == 2 && string(noot[len(noot)-1:]) == \"]\" {\n\t\ttmpval = (strings.Split(noot, \"[\"))[1]\n\t\tnootClean = string(tmpval[:len(tmpval)-1])\n\t\tvariatsioon = true\n\t} else {\n\t\tnootClean = noot\n\t}\n\n\t//Ehitame vastuse vastavalt sellele mis elemendid meile sattusid\n\n\tif strings.Contains(nootClean, \"/\") == true {\n\t\t//Kui on kiirem noot siis teeme nii\n\t\tvastus = ConvertNoot(strings.Split(nootClean, \"/\")[0]) + \"/\" + ConvertNoot(strings.Split(nootClean, \"/\")[1]) + \"/\"\n\t} else if strings.Contains(nootClean, \"(\") == true && strings.Contains(nootClean, \")\") == true {\n\t\t//Kui on eellöök siis teeme nii\n\t\tvastus = \"{\" + ConvertNoot(strings.Split(strings.Split(nootClean, \"(\")[1], \")\")[0]) + \"}\" + ConvertNoot(strings.Split(nootClean, \")\")[1])\n\t} else {\n\t\tvastus = ConvertNoot(nootClean)\n\t}\n\n\tif variatsioon == true {\n\t\tvastus = \"!mark!\" + vastus\n\t}\n\n\treturn vastus\n}", "func Brcom(op Op) Op", "func (g SimplePoint) CalculatedPoint() Position {\n\treturn Position{X: g.X, Y: g.Y, Z: 0}\n}", "func (e *Exponential) ConjugateUpdate(suffStat []float64, nSamples float64, priorStrength []float64) {\n\tif len(suffStat) != e.NumSuffStat() {\n\t\tpanic(\"exponential: incorrect suffStat length\")\n\t}\n\tif len(priorStrength) != e.NumSuffStat() {\n\t\tpanic(\"exponential: incorrect priorStrength length\")\n\t}\n\n\ttotalSamples := nSamples + priorStrength[0]\n\n\ttotalSum := nSamples / suffStat[0]\n\tif !(priorStrength[0] == 0) {\n\t\ttotalSum += priorStrength[0] / e.Rate\n\t}\n\te.Rate = totalSamples / totalSum\n\tpriorStrength[0] = totalSamples\n}", "func (p *Path) CCW() bool {\n\t// use the Shoelace formula\n\tarea := 0.0\n\tvar start, end Point\n\tfor i := 0; i < len(p.d); {\n\t\tcmd := p.d[i]\n\t\ti += cmdLen(cmd)\n\n\t\tend = Point{p.d[i-2], p.d[i-1]}\n\t\tif cmd != moveToCmd {\n\t\t\tarea += (end.X - start.X) * (start.Y + end.Y)\n\t\t}\n\t\tstart = end\n\t}\n\treturn area <= 0.0\n}", "func (p Point) Col() int {\n\treturn p.col\n}", "func (p *Point) Inv(c Circle) {\n\tvar A = -c.C\n\tvar B = complex(-c.D, 0)\n\tvar C = complex(c.A, 0)\n\tvar D = cmplx.Conj(c.C)\n\n\tvar Z = p.Z\n\tvar W = p.W\n\n\tp.Z = A*Z + B*W\n\tp.W = C*Z + D*W\n}", "func (s *Simple) Solve(g *Grid) (string, error) {\n\tsolution := \"\"\n\tfor _, point := range s.order {\n\t\tfor s.current.X < point.X {\n\t\t\tsolution = solution + \"E\"\n\t\t\ts.current.X++\n\t\t}\n\n\t\tfor s.current.X > point.X {\n\t\t\tsolution = solution + \"W\"\n\t\t\ts.current.X--\n\t\t}\n\n\t\tfor s.current.Y < point.Y {\n\t\t\tsolution = solution + \"N\"\n\t\t\ts.current.Y++\n\t\t}\n\n\t\tfor s.current.Y > point.Y {\n\t\t\tsolution = solution + \"S\"\n\t\t\ts.current.Y--\n\t\t}\n\n\t\tsolution = solution + \"D\"\n\t}\n\treturn solution, nil\n}", "func (o NetworkGrantOutput) CenId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *NetworkGrant) pulumi.StringOutput { return v.CenId }).(pulumi.StringOutput)\n}", "func (c *CSC) ToCOO() *COO {\n\trows := make([]int, c.NNZ())\n\tcols := make([]int, c.NNZ())\n\tdata := make([]float64, c.NNZ())\n\n\tfor i := 0; i < len(c.matrix.Indptr)-1; i++ {\n\t\tfor j := c.matrix.Indptr[i]; j < c.matrix.Indptr[i+1]; j++ {\n\t\t\tcols[j] = i\n\t\t}\n\t}\n\tcopy(rows, c.matrix.Ind)\n\tcopy(data, c.matrix.Data)\n\n\tcoo := NewCOO(c.matrix.J, c.matrix.I, rows, cols, data)\n\treturn coo\n}", "func (c Coordinate) Col() int { return c.col }", "func CCW(a, b, c Point) bool {\n\t// a->b->c is ccw iff sin(Θ) < 0\n\t// c\n\t// /\n\t// /Θ\n\t// b +---- a\n\tv1 := a.Sub(b)\n\tv2 := c.Sub(b)\n\tx := v1.X*v2.Y - v1.Y*v2.X // x = |v1 x v2| = sin(Θ)|v1||v2|\n\treturn x < 0\n}", "func NotationToCoord(algebra string) Coord {\n\tif len(algebra) != 2 {\n\t\tpanic(\"Algebraic notation must be 2 characters precisely; got: '\" + algebra + \"'\")\n\t}\n\talgebra = strings.ToUpper(algebra)\n\n\tvar c Coord\n\tfile := algebra[0]\n\trank := algebra[1]\n\n\t// Remember, these are ASCII code points, not numbers\n\tif file < 65 || file > 72 || rank < 48 || rank > 57 {\n\t\tpanic(\"Bad position (\" + algebra + \")\")\n\t}\n\n\tc.Row = int(rank - 48 - 1)\n\tc.Col = int(file - 65)\n\n\treturn c\n}", "func (o CertificateAuthorityOutput) ConfigJson() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *CertificateAuthority) pulumi.StringPtrOutput { return v.ConfigJson }).(pulumi.StringPtrOutput)\n}", "func JNC(r operand.Op) { ctx.JNC(r) }", "func (r Rat) AsContinuedFraction() ContinuedFraction { return r.CFTerms }", "func (fn *formulaFuncs) COVARIANCEdotP(argsList *list.List) formulaArg {\n\treturn fn.covar(\"COVARIANCE.P\", argsList)\n}", "func (pt *Coord) X() float64 { return pt.x }", "func (c *Context) JCC(r operand.Op) {\n\tc.addinstruction(x86.JCC(r))\n}", "func (f *Frame) CharOf(pt draw.Point) int {\n\tpt = f.grid(pt)\n\tqt := f.R.Min\n\tp := 0\n\tbn := 0\n\tfor ; bn < len(f.box) && qt.Y < pt.Y; bn++ {\n\t\tb := &f.box[bn]\n\t\tf.cklinewrap(&qt, b)\n\t\tif qt.Y >= pt.Y {\n\t\t\tbreak\n\t\t}\n\t\tf.advance(&qt, b)\n\t\tp += b.NRUNE()\n\t}\n\tfor ; bn < len(f.box) && qt.X <= pt.X; bn++ {\n\t\tb := &f.box[bn]\n\t\tf.cklinewrap(&qt, b)\n\t\tif qt.Y > pt.Y {\n\t\t\tbreak\n\t\t}\n\t\tif qt.X+b.wid > pt.X {\n\t\t\tif b.nrune < 0 {\n\t\t\t\tf.advance(&qt, b)\n\t\t\t} else {\n\t\t\t\ts := b.bytes\n\t\t\t\tfor {\n\t\t\t\t\tif len(s) == 0 {\n\t\t\t\t\t\tdrawerror(f.Display, \"end of string in frcharofpt\")\n\t\t\t\t\t}\n\t\t\t\t\t_, size := utf8.DecodeRune(s)\n\t\t\t\t\tqt.X += f.Font.BytesWidth(s[:size])\n\t\t\t\t\ts = s[size:]\n\t\t\t\t\tif qt.X > pt.X {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tp++\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tp += b.NRUNE()\n\t\t\tf.advance(&qt, b)\n\t\t}\n\t}\n\treturn p\n}", "func (o GetListenersListenerOutput) Cps() pulumi.IntOutput {\n\treturn o.ApplyT(func(v GetListenersListener) int { return v.Cps }).(pulumi.IntOutput)\n}", "func (p Polynom) Coeff(i int) *big.Int {\n\treturn cp(p.coeff[i])\n}", "func (s *Stat) ConstructingConns() int32 {\n\treturn s.s.ConstructingResources()\n}", "func CoVar(x, y []float64) float64 {\n\tif len(x) != len(y) {\n\t\tpanic(\"dimension mismatch\")\n\t}\n\n\tvar (\n\t\tmx, my = Mean(x...), Mean(y...)\n\t\tcv float64\n\t)\n\n\tfor i := 0; i < len(x); i++ {\n\t\tcv += (x[i] - mx) * (y[i] - my)\n\t}\n\n\treturn cv / float64(len(x))\n}", "func (pt Coord) String() string {\n\treturn fmt.Sprintf(\"{%v,%v}\", pt.x, pt.y)\n}", "func (v GeodeticPoint) GCJ02ToWGS84() GeodeticPoint {\n\tp := v.WGS84ToGCJ02()\n\treturn GeodeticPoint{v.Latitude*2 - p.Latitude, v.Longitude*2 - p.Longitude}\n}", "func (o *GetPortfolioAccountIDPositionConidParams) SetConid(conid int64) {\n\to.Conid = conid\n}", "func (g *Geocodio) GeocodeAndReturnCongressionalDistrict(address string) (GeocodeResult, error) {\n\treturn g.GeocodeReturnFields(address, \"cd\")\n}", "func (o LookupServerResultOutput) Commitment() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupServerResult) string { return v.Commitment }).(pulumi.StringOutput)\n}", "func (o GetVpcEndpointsEndpointOutput) ConnectionStatus() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetVpcEndpointsEndpoint) string { return v.ConnectionStatus }).(pulumi.StringOutput)\n}", "func (s *Smplen) Complex() complex128 {\n\treturn s.c\n}", "func (joint Joint) Coords() (int, int, int) {\n\n\tif joint.joint == nil {\n\t\tpanic(\"cannot get the coordinates of a nil Joint object\")\n\t}\n\n\treturn int(joint.joint.x), int(joint.joint.y), int(joint.joint.z)\n}", "func SparseMatrixMatMulConjugateOutput(value bool) SparseMatrixMatMulAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"conjugate_output\"] = value\n\t}\n}" ]
[ "0.6772554", "0.65858155", "0.655946", "0.6487533", "0.6158264", "0.5945205", "0.5887121", "0.57443815", "0.5568718", "0.50892806", "0.50141805", "0.4936331", "0.48034164", "0.47119483", "0.47070533", "0.47059134", "0.4685934", "0.46850988", "0.46353832", "0.45752066", "0.45739165", "0.4562532", "0.45561025", "0.45152634", "0.44980332", "0.44941878", "0.4484624", "0.44790927", "0.4473801", "0.44537514", "0.44428387", "0.44272494", "0.44085786", "0.4388938", "0.4380916", "0.43632016", "0.4358385", "0.43553475", "0.43401977", "0.4327403", "0.4320041", "0.4316606", "0.43050873", "0.42947072", "0.4283505", "0.42760265", "0.42738667", "0.4270656", "0.4251374", "0.42497206", "0.424947", "0.4245378", "0.42320183", "0.42144772", "0.42073375", "0.4207047", "0.41941452", "0.418547", "0.41666076", "0.41631874", "0.41584337", "0.4157866", "0.41573578", "0.41516498", "0.41510847", "0.4141236", "0.41350213", "0.41344535", "0.41325736", "0.4130209", "0.41289654", "0.41247964", "0.41221118", "0.41198817", "0.41010815", "0.40985826", "0.40776768", "0.4061231", "0.4059681", "0.40404016", "0.40393713", "0.40390843", "0.40322682", "0.4027776", "0.40200332", "0.40182093", "0.40173423", "0.40168348", "0.4010319", "0.4008815", "0.39972815", "0.39850506", "0.39819285", "0.39801833", "0.3977381", "0.39709863", "0.39696434", "0.39513606", "0.39386654", "0.39371762" ]
0.7751994
0
PointEq checks that two points are equal.
func PointEq(p Point, q Point) bool { return p.Z*q.W == p.W*q.Z }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p Point) Eq(q Point) bool { return p.X == q.X && p.Y == q.Y }", "func (p Point) Eq(q Point) bool {\n\treturn p == q\n}", "func pointsEquals(p1, p2 *point) bool {\n\treturn p1.x == p2.x && p1.y == p2.y\n}", "func (ec *ECPoint) Equal(other *ECPoint) bool {\n\treturn ec.X.Cmp(other.X) == 0 && ec.Y.Cmp(other.Y) == 0\n}", "func (pt *Point) Equal(other *Point) bool {\n\treturn other != nil && pt.X() == other.X() && pt.Y() == other.Y()\n}", "func (p *EdwardsPoint) Equal(other *EdwardsPoint) int {\n\t// We would like to check that the point (X/Z, Y/Z) is equal to\n\t// the point (X'/Z', Y'/Z') without converting into affine\n\t// coordinates (x, y) and (x', y'), which requires two inversions.\n\t// We have that X = xZ and X' = x'Z'. Thus, x = x' is equivalent to\n\t// (xZ)Z' = (x'Z')Z, and similarly for the y-coordinate.\n\tvar sXoZ, oXsZ, sYoZ, oYsZ field.FieldElement\n\tsXoZ.Mul(&p.inner.X, &other.inner.Z)\n\toXsZ.Mul(&other.inner.X, &p.inner.Z)\n\tsYoZ.Mul(&p.inner.Y, &other.inner.Z)\n\toYsZ.Mul(&other.inner.Y, &p.inner.Z)\n\n\treturn sXoZ.Equal(&oXsZ) & sYoZ.Equal(&oYsZ)\n}", "func (p1 Point) Equals(p2 Point) bool {\n\treturn p1.X == p2.X && p1.Y == p2.Y\n}", "func (p *PointAffine) Equal(p1 *PointAffine) bool {\n\treturn p.X.Equal(&p1.X) && p.Y.Equal(&p1.Y)\n}", "func (point Point) Equal(obj Objecter) bool {\n\totherPoint, ok := obj.(Point)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tswitch {\n\tcase point.X != otherPoint.X:\n\t\treturn false\n\tcase point.Y != otherPoint.Y:\n\t\treturn false\n\t}\n\n\treturn true\n}", "func equals(p1, p2 *node) bool {\n\treturn p1.x == p2.x && p1.y == p2.y\n}", "func (a Points) Equal(b Points) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i := 0; i < len(a); i++ {\n\t\tif a[i] != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (p *PointProj) Equal(p1 *PointProj) bool {\n\tif p.Z.IsZero() || p1.Z.IsZero() {\n\t\treturn false\n\t}\n\tvar pAffine, p1Affine PointAffine\n\tpAffine.FromProj(p)\n\tp1Affine.FromProj(p1)\n\treturn pAffine.Equal(&p1Affine)\n}", "func TestDetectSimplePointSimplePoint(t *testing.T) {\n\tp1 := toSimplePoint(getByID(\"point1\"))\n\tp2 := toSimplePoint(getByID(\"point2\"))\n\tif p1.Intersects(p2) {\n\t\tt.Fatal(\"expected false\")\n\t}\n\tif !p1.Intersects(p1) {\n\t\tt.Fatal(\"expected true\")\n\t}\n\tif p1.Within(p2) {\n\t\tt.Fatal(\"expected false\")\n\t}\n\tif !p1.Within(p1) {\n\t\tt.Fatal(\"expected true\")\n\t}\n}", "func (x *Secp256k1N) Eq(y *Secp256k1N) bool {\n\t// TODO: More efficient implementation/\n\tvar xNorm, yNorm = *x, *y\n\txNorm.Normalize()\n\tyNorm.Normalize()\n\treturn xNorm.limbs[0] == yNorm.limbs[0] &&\n\t\txNorm.limbs[1] == yNorm.limbs[1] &&\n\t\txNorm.limbs[2] == yNorm.limbs[2] &&\n\t\txNorm.limbs[3] == yNorm.limbs[3] &&\n\t\txNorm.limbs[4] == yNorm.limbs[4]\n}", "func (g *G1) IsEqual(p *G1) bool {\n\tvar lx, rx, ly, ry ff.Fp\n\tlx.Mul(&g.x, &p.z) // lx = x1*z2\n\trx.Mul(&p.x, &g.z) // rx = x2*z1\n\tlx.Sub(&lx, &rx) // lx = lx-rx\n\tly.Mul(&g.y, &p.z) // ly = y1*z2\n\try.Mul(&p.y, &g.z) // ry = y2*z1\n\tly.Sub(&ly, &ry) // ly = ly-ry\n\treturn g.isValidProjective() && p.isValidProjective() && lx.IsZero() == 1 && ly.IsZero() == 1\n}", "func equal(x, y float32, tol float64) bool {\n\tavg := (math.Abs(float64(x+y)) / 2.0)\n\tsErr := math.Abs(float64(x-y)) / (avg + 1)\n\tif sErr > tol {\n\t\treturn false\n\t}\n\treturn true\n}", "func isApproximatelyEqual(x, y, epsilon float64) bool {\n\t// Check absolute precision.\n\tif -epsilon <= x-y && x-y <= epsilon {\n\t\treturn true\n\t}\n\n\t// Is x or y too close to zero?\n\tif (-epsilon <= x && x <= epsilon) || (-epsilon <= y && y <= epsilon) {\n\t\treturn false\n\t}\n\n\t// Check relative precision.\n\treturn (-epsilon <= (x-y)/x && (x-y)/x <= epsilon) ||\n\t\t(-epsilon <= (x-y)/y && (x-y)/y <= epsilon)\n}", "func AssertPointsEqual(t *testing.T, expected, actual []Point) {\n\tif assert.Equal(t, len(expected), len(actual)) {\n\t\tfor _, point := range expected {\n\t\t\tassert.Contains(t, actual, point)\n\t\t}\n\t}\n}", "func TestNewPoint(t *testing.T) {\n\tp := NewPoint(1, 1, 1)\n\tif (p.X != 1) || (p.X != 1) || (p.X != 1) {\n\t\tt.Log(\"Wrong assignment of the coordinates!\")\n\t\tt.Fail()\n\t}\n}", "func eq(o1, o2 interface{}) bool {\n\n\tf1, ok1 := ToFloat(o1)\n\tf2, ok2 := ToFloat(o2)\n\tif ok1 && ok2 {\n\t\treturn f1 == f2\n\t}\n\n\tb1, ok1 := ToBool(o1)\n\tb2, ok1 := ToBool(o2)\n\tif ok1 && ok2 {\n\t\treturn b1 == b2\n\t}\n\n\treturn o1 == o2\n}", "func (uview *UtreexoViewpoint) Equal(compRoots []*chainhash.Hash) bool {\n\tuViewRoots := uview.accumulator.GetRoots()\n\tif len(uViewRoots) != len(compRoots) {\n\t\tlog.Criticalf(\"Length of the given roots differs from the one\" +\n\t\t\t\"fetched from the utreexoViewpoint.\")\n\t\treturn false\n\t}\n\n\tpassedInRoots := make([]accumulator.Hash, len(compRoots))\n\n\tfor i, compRoot := range compRoots {\n\t\tpassedInRoots[i] = accumulator.Hash(*compRoot)\n\t}\n\n\tfor i, root := range passedInRoots {\n\t\tif !bytes.Equal(root[:], uViewRoots[i][:]) {\n\t\t\tlog.Criticalf(\"The compared Utreexo roots differ.\"+\n\t\t\t\t\"Passed in root:%x\\nRoot from utreexoViewpoint:%x\\n\", uViewRoots[i], root)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func (np *vpoint) sameLoc(x, y float64) bool {\n\treturn np.x == x && np.y == y\n}", "func Eql(v1, v2 Vect) bool { return v1.X == v2.X && v1.Y == v2.Y }", "func (p Point) Is(p2 Point) bool {\n\treturn p.X == p2.X && p.Y == p2.Y\n}", "func _v2dEquals(v1 *Vec2d, v2 *Vec2d) bool {\n\treturn floatEqual(v1.x, v2.x) && floatEqual(v1.y, v2.y)\n}", "func equal(a, b float64) bool {\n\treturn math.Abs(a-b) <= equalityThreshold\n}", "func (eps Accuracy) Equal(a, b float64) bool {\n\treturn math.Abs(a-b) < eps()\n}", "func (p Params) Equal(p2 Params) bool {\n\treturn reflect.DeepEqual(p, p2)\n}", "func (e Edge) IsPoint(p Pointer) bool {\n\treturn PointerEq(p, e.A) || PointerEq(p, e.B)\n}", "func (p *G2Affine) Equal(a *G2Affine) bool {\n\treturn p.X.Equal(&a.X) && p.Y.Equal(&a.Y)\n}", "func equal(a, b float64) bool {\n\tif math.IsNaN(a) && math.IsNaN(b) {\n\t\treturn true\n\t}\n\tif !math.IsNaN(a) && !math.IsNaN(b) {\n\t\treturn math.Abs(a-b) < eps\n\t}\n\treturn false\n}", "func (a Vec2) AlmostEquals(b Vec2, epsilon float64) bool {\n\treturn AlmostEqual(a.X, b.X, epsilon) && AlmostEqual(a.Y, b.Y, epsilon)\n}", "func (k *PublicKey) Equal(x crypto.PublicKey) bool {\n\txx, ok := x.(*PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn k.curve == xx.curve &&\n\t\tsubtle.ConstantTimeCompare(k.publicKey, xx.publicKey) == 1\n}", "func (z *Perplex) Equals(y *Perplex) bool {\n\tif z.l.Cmp(&y.l) != 0 || z.r.Cmp(&y.r) != 0 {\n\t\treturn false\n\t}\n\treturn true\n}", "func (p Params) Equal(p2 Params) bool {\n\tbz1 := MsgCdc.MustMarshalBinary(&p)\n\tbz2 := MsgCdc.MustMarshalBinary(&p2)\n\treturn bytes.Equal(bz1, bz2)\n}", "func (d Degrees) EqualWithin(o Degrees, eps Epsilon) bool {\n\treturn round(float64(d)/float64(eps))-round(float64(o)/float64(eps)) == 0\n}", "func (p *G1Affine) Equal(a *G1Affine) bool {\n\treturn p.X.Equal(&a.X) && p.Y.Equal(&a.Y)\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase int:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase int:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase int64:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase int64:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase int:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase int64:\n\t\t\t\tif int64(x) == int64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase float32:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase float32:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase float64:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tswitch y := y.(type) {\n\t\t\tcase float32:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\tcase float64:\n\t\t\t\tif float64(x) == float64(y) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn false\n\n\tcase string, byte:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (v PublicKey) Equal(o PublicKey) bool {\n\treturn string(v.Bytes) == string(o.Bytes) &&\n\t\tv.CurveType == o.CurveType\n}", "func (k *PublicKey) Equals(pub *PublicKey) bool {\n\tif subtle.ConstantTimeCompare(k.X.Bytes(), pub.X.Bytes()) == 1 &&\n\t\tsubtle.ConstantTimeCompare(k.Y.Bytes(), pub.Y.Bytes()) == 1 {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func Eq(one, other interface{}) bool {\n\treturn reflect.DeepEqual(one, other)\n}", "func CurveParamsIsOnCurve(curve *elliptic.CurveParams, x, y *big.Int) bool", "func (a Vec2) Equals(b Vec2) bool {\n\treturn a.AlmostEquals(b, EPSILON)\n}", "func EQ(x float64, y float64) bool {\n\treturn (y-e < x) && (x < y+e)\n}", "func (v Vect) Equals(other Vect) bool {\n\treturn int(C.cpveql(toC(v), toC(other))) == 1\n}", "func equalish(a, b, tolerance float64) bool {\n\tif a == b {\n\t\treturn true\n\t}\n\n\tdiff := math.Abs(a - b)\n\n\tif diff <= tolerance {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (p *point) can_exist_when(another_point *point) bool {\r\n\tif p.x == another_point.x && p.y == another_point.y {\r\n\t\treturn false\r\n\t}\r\n\treturn true\r\n}", "func float64equals(x, y float64) bool {\n\treturn math.Abs(x-y) < EPSILON\n}", "func (recv *ParamSpecPointer) Equals(other *ParamSpecPointer) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (c *curve) validPoint(P point) bool {\n\n\t// Check on-curve\n\tx, y := P.getXY()\n\tif !c.onCurve(x, y) {\n\t\treturn false\n\t}\n\n\t// Check in-subgroup by multiplying by subgroup order\n\tQ := c.self.Point()\n\tQ.Mul(&c.order, P)\n\tif !Q.Equal(c.null) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func eq(args ...interface{}) bool {\n\tif len(args) == 0 {\n\t\treturn false\n\t}\n\tx := args[0]\n\tswitch x := x.(type) {\n\tcase string, int, int64, byte, float32, float64:\n\t\tfor _, y := range args[1:] {\n\t\t\tif x == y {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\t}\n\tfor _, y := range args[1:] {\n\t\tif reflect.DeepEqual(x, y) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func EqualMapFloat32BoolP(map1, map2 map[float32]bool) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (d Angle) EqualWithin(o Angle, eps Epsilon) bool {\n\treturn round(float64(d)/float64(eps))-round(float64(o)/float64(eps)) == 0\n}", "func EqualMapInt32Float64P(map1, map2 map[int32]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (sig Signature) Verify(X curve.Point, hash []byte) bool {\n\tgroup := X.Curve()\n\n\tm := curve.FromHash(group, hash)\n\tsInv := group.NewScalar().Set(sig.S).Invert()\n\tmG := m.ActOnBase()\n\tr := sig.R.XScalar()\n\trX := r.Act(X)\n\tR2 := mG.Add(rX)\n\tR2 = sInv.Act(R2)\n\treturn R2.Equal(sig.R)\n}", "func (e Edge) Eq(o Edge) bool {\n\treturn (PointerEq(e.A, o.A) && PointerEq(e.B, o.B)) || (PointerEq(e.A, o.B) && PointerEq(e.B, o.A))\n}", "func (d *Datapoint) EqualTo(q *Datapoint) bool {\n\tif len(d.set) != len(q.set) {\n\t\treturn false\n\t}\n\tfor i := range d.set {\n\t\tif d.set[i] != q.set[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isSecretEqual(x, y *PGPSigningSecret) bool {\n\tif x == nil || y == nil {\n\t\treturn x == y\n\t} else {\n\t\tpx := x.PgpKey.privateKey\n\t\tpy := y.PgpKey.privateKey\n\t\treturn reflect.DeepEqual(x.PgpKey.publicKey, y.PgpKey.publicKey) &&\n\t\t\treflect.DeepEqual(px.PrivateKey, py.PrivateKey) &&\n\t\t\treflect.DeepEqual(px.Encrypted, py.Encrypted) &&\n\t\t\treflect.DeepEqual(px.PublicKey, py.PublicKey)\n\t}\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (d Decimal) Equal(d2 Decimal) bool {\n\treturn d.Cmp(d2) == 0\n}", "func (p PublicKey) Equal(x crypto.PublicKey) bool {\n\txx, ok := x.(PublicKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn bytes.Equal(p, xx)\n}", "func EqualMapFloat32Int64P(map1, map2 map[float32]int64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqFn(a interface{}, b interface{}) bool {\n\treturn a == b\n}", "func IsPoint(t Tuplelike) bool {\n\treturn t.At(3) == pointW\n}", "func EqualMapFloat32P(map1, map2 map[float32]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (q Quat) EqualsEps(other Quat, epsilon float32) bool {\n\treturn EqualEps(q.W, other.W, epsilon) &&\n\t\tEqualEps(q.X, other.X, epsilon) && EqualEps(q.Y, other.Y, epsilon) && EqualEps(q.Z, other.Z, epsilon)\n}", "func equalClosed(ctx *OpContext, x, y *Vertex, flags Flag) bool {\n\treturn verifyStructs(x, y, flags) && verifyStructs(y, x, flags)\n}", "func EqualMapIntFloat64P(map1, map2 map[int]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (recv *ParamSpecPool) Equals(other *ParamSpecPool) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (q1 Quat) ApproxEqual(q2 Quat) bool {\n\treturn FloatEqual(q1.W, q2.W) && q1.V.ApproxEqual(q2.V)\n}", "func EqualMapFloat32Float64P(map1, map2 map[float32]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isEqual(g1 types.GeometryValue, g2 types.GeometryValue) bool {\n\treturn isWithin(g1, g2) && isWithin(g2, g1)\n}", "func (ec *EC) Add(p, q *Point) *Point {\n\tif ec.Infinite(p) {\n\t\treturn &Point{new(big.Int).SetBytes(q.X.Bytes()), new(big.Int).SetBytes(q.Y.Bytes())}\n\t}\n\tif ec.Infinite(q) {\n\t\treturn &Point{new(big.Int).SetBytes(p.X.Bytes()), new(big.Int).SetBytes(p.Y.Bytes())}\n\t}\n\tif p.X.Cmp(q.X) == 0 && p.Y.Cmp(q.Y) != 0 {\n\t\treturn &Point{}\n\t}\n\tvar s *big.Int\n\t// https://ja.wikipedia.org/wiki/%E6%A5%95%E5%86%86%E6%9B%B2%E7%B7%9A#%E7%BE%A4%E6%A7%8B%E9%80%A0\n\tif p.X.Cmp(q.X) == 0 && p.Y.Cmp(q.Y) == 0 {\n\t\t// s = ( 3*Xp*Xp + a ) * ( 2*Yp ) ^ ( P - 2 ) mod P\n\t\ts = new(big.Int).Mod(\n\t\t\tnew(big.Int).Mul(\n\t\t\t\tnew(big.Int).Add(new(big.Int).Mul(new(big.Int).Mul(big.NewInt(3), p.X), p.X), ec.a),\n\t\t\t\tnew(big.Int).Exp(\n\t\t\t\t\tnew(big.Int).Mul(big.NewInt(2), p.Y),\n\t\t\t\t\tnew(big.Int).Sub(ec.P, big.NewInt(2)),\n\t\t\t\t\tec.P)),\n\t\t\tec.P)\n\t} else {\n\t\t// s = ( Yp - Yq ) * ( Xp - Xq ) ^ ( P - 2 ) mod P\n\t\ts = new(big.Int).Mod(\n\t\t\tnew(big.Int).Mul(\n\t\t\t\tnew(big.Int).Sub(p.Y, q.Y),\n\t\t\t\tnew(big.Int).Exp(\n\t\t\t\t\tnew(big.Int).Sub(p.X, q.X),\n\t\t\t\t\tnew(big.Int).Sub(ec.P, big.NewInt(2)),\n\t\t\t\t\tec.P)),\n\t\t\tec.P)\n\t}\n\tr := &Point{}\n\t// Xr = s*s - Xp - Xq mod P\n\tr.X = new(big.Int).Mod(new(big.Int).Sub(new(big.Int).Mul(s, s), new(big.Int).Add(p.X, q.X)), ec.P)\n\t// Yr = s*( Xp - Xr ) - Yp mod P\n\tr.Y = new(big.Int).Mod(new(big.Int).Sub(new(big.Int).Mul(s, new(big.Int).Sub(p.X, r.X)), p.Y), ec.P)\n\treturn r\n}", "func EqualMapInt64Float32P(map1, map2 map[int64]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EndPointEquality(left, right *pb.EndPoint) bool {\n\tif left.Uid != right.Uid {\n\t\treturn false\n\t}\n\tif left.Host != right.Host {\n\t\treturn false\n\t}\n\tif len(left.PortMap) != len(right.PortMap) {\n\t\treturn false\n\t}\n\tfor key, lvalue := range left.PortMap {\n\t\trvalue, ok := right.PortMap[key]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif lvalue != rvalue {\n\t\t\treturn false\n\t\t}\n\t}\n\tif len(left.HealthMap) != len(right.HealthMap) {\n\t\treturn false\n\t}\n\tfor key, lvalue := range left.HealthMap {\n\t\trvalue, ok := right.HealthMap[key]\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\tif lvalue != rvalue {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Float64P(map1, map2 map[int8]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (r Rect) Eq(q Rect, tol float64) bool {\n\treturn r.Min.Eq(q.Min, tol) && r.Max.Eq(q.Max, tol)\n}", "func EqualMapFloat64P(map1, map2 map[float64]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (t *Tuple) IsPoint() bool {\n\treturn t.w == 1.0\n}", "func SamePointer(t testing.TB, expected, actual interface{}, msgAndArgs ...interface{}) bool {\n\tif !IsPointerSame(expected, actual) {\n\t\treturn failTest(t, 1, fmt.Sprintf(\"SamePointer: expected `%#v` (%p), actual `%#v` (%p)\", expected, expected, actual, actual), msgAndArgs...)\n\t}\n\n\treturn true\n}", "func geoAlmostEqual(p1 *GeoCoord, p2 *GeoCoord) bool {\n\treturn geoAlmostEqualThreshold(p1, p2, EPSILON_RAD)\n}", "func EqualMapFloat64BoolP(map1, map2 map[float64]bool) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equals(t types.Type, x, y value) bool {\n\tswitch x := x.(type) {\n\tcase bool:\n\t\treturn x == y.(bool)\n\tcase int:\n\t\treturn x == y.(int)\n\tcase int8:\n\t\treturn x == y.(int8)\n\tcase int16:\n\t\treturn x == y.(int16)\n\tcase int32:\n\t\treturn x == y.(int32)\n\tcase int64:\n\t\treturn x == y.(int64)\n\tcase uint:\n\t\treturn x == y.(uint)\n\tcase uint8:\n\t\treturn x == y.(uint8)\n\tcase uint16:\n\t\treturn x == y.(uint16)\n\tcase uint32:\n\t\treturn x == y.(uint32)\n\tcase uint64:\n\t\treturn x == y.(uint64)\n\tcase uintptr:\n\t\treturn x == y.(uintptr)\n\tcase float32:\n\t\treturn x == y.(float32)\n\tcase float64:\n\t\treturn x == y.(float64)\n\tcase complex64:\n\t\treturn x == y.(complex64)\n\tcase complex128:\n\t\treturn x == y.(complex128)\n\tcase string:\n\t\treturn x == y.(string)\n\tcase *value:\n\t\treturn x == y.(*value)\n\tcase chan value:\n\t\treturn x == y.(chan value)\n\tcase structure:\n\t\treturn x.eq(t, y)\n\tcase array:\n\t\treturn x.eq(t, y)\n\tcase iface:\n\t\treturn x.eq(t, y)\n\tcase rtype:\n\t\treturn x.eq(t, y)\n\t}\n\n\t// Since map, func and slice don't support comparison, this\n\t// case is only reachable if one of x or y is literally nil\n\t// (handled in eqnil) or via interface{} values.\n\tpanic(fmt.Sprintf(\"comparing uncomparable type %s\", t))\n}", "func EqualMapBoolFloat32P(map1, map2 map[bool]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (k *PrivateKey) Equal(x crypto.PrivateKey) bool {\n\txx, ok := x.(*PrivateKey)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn k.curve == xx.curve &&\n\t\tsubtle.ConstantTimeCompare(k.privateKey, xx.privateKey) == 1\n}", "func EqualMapInt16Float32P(map1, map2 map[int16]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt8Float32P(map1, map2 map[int8]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapInt64Float64P(map1, map2 map[int64]float64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (recv *ParamSpecFloat) Equals(other *ParamSpecFloat) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func (recv *ParamSpecParam) Equals(other *ParamSpecParam) bool {\n\treturn other.ToC() == recv.ToC()\n}", "func EqualMapFloat32Uint64P(map1, map2 map[float32]uint64) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func equal(lhsV, rhsV reflect.Value) bool {\n\tlhsNotValid, rhsVNotValid := !lhsV.IsValid(), !rhsV.IsValid()\n\tif lhsNotValid && rhsVNotValid {\n\t\treturn true\n\t}\n\tif (!lhsNotValid && rhsVNotValid) || (lhsNotValid && !rhsVNotValid) {\n\t\treturn false\n\t}\n\n\tlhsIsNil, rhsIsNil := isNil(lhsV), isNil(rhsV)\n\tif lhsIsNil && rhsIsNil {\n\t\treturn true\n\t}\n\tif (!lhsIsNil && rhsIsNil) || (lhsIsNil && !rhsIsNil) {\n\t\treturn false\n\t}\n\tif lhsV.Kind() == reflect.Interface || lhsV.Kind() == reflect.Ptr {\n\t\tlhsV = lhsV.Elem()\n\t}\n\tif rhsV.Kind() == reflect.Interface || rhsV.Kind() == reflect.Ptr {\n\t\trhsV = rhsV.Elem()\n\t}\n\n\t// Compare a string and a number.\n\t// This will attempt to convert the string to a number,\n\t// while leaving the other side alone. Code further\n\t// down takes care of converting ints and floats as needed.\n\tif isNum(lhsV) && rhsV.Kind() == reflect.String {\n\t\trhsF, err := tryToFloat64(rhsV)\n\t\tif err != nil {\n\t\t\t// Couldn't convert RHS to a float, they can't be compared.\n\t\t\treturn false\n\t\t}\n\t\trhsV = reflect.ValueOf(rhsF)\n\t} else if lhsV.Kind() == reflect.String && isNum(rhsV) {\n\t\t// If the LHS is a string formatted as an int, try that before trying float\n\t\tlhsI, err := tryToInt64(lhsV)\n\t\tif err != nil {\n\t\t\t// if LHS is a float, e.g. \"1.2\", we need to set lhsV to a float64\n\t\t\tlhsF, err := tryToFloat64(lhsV)\n\t\t\tif err != nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tlhsV = reflect.ValueOf(lhsF)\n\t\t} else {\n\t\t\tlhsV = reflect.ValueOf(lhsI)\n\t\t}\n\t}\n\n\tif isNum(lhsV) && isNum(rhsV) {\n\t\treturn fmt.Sprintf(\"%v\", lhsV) == fmt.Sprintf(\"%v\", rhsV)\n\t}\n\n\t// Try to compare bools to strings and numbers\n\tif lhsV.Kind() == reflect.Bool || rhsV.Kind() == reflect.Bool {\n\t\tlhsB, err := tryToBool(lhsV)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\trhsB, err := tryToBool(rhsV)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\treturn lhsB == rhsB\n\t}\n\n\tif lhsV.CanInterface() && rhsV.CanInterface() {\n\t\treturn reflect.DeepEqual(lhsV.Interface(), rhsV.Interface())\n\t}\n\treturn reflect.DeepEqual(lhsV, rhsV)\n}", "func EqualMapInt32Float32P(map1, map2 map[int32]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Eq(a, b interface{}, f Func) bool {\n\treturn f(a, b) == 0\n}", "func EqualMapFloat64IntP(map1, map2 map[float64]int) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapIntFloat32P(map1, map2 map[int]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func EqualMapFloat64Float32P(map1, map2 map[float64]float32) bool {\n\tlen1 := len(map1)\n\tlen2 := len(map2)\n\n\tif len1 == 0 || len2 == 0 || len1 != len2 {\n\t\treturn false\n\t}\n\n\tfor k1, v1 := range map1 {\n\t\tfound := false\n\t\tfor k2, v2 := range map2 {\n\t\t\tif k1 == k2 && v1 == v2 {\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (ec *EC) On(p *Point) bool {\n\tif ec.Infinite(p) {\n\t\treturn false\n\t}\n\t// y^2\n\ty2 := new(big.Int).Exp(p.Y, big.NewInt(2), ec.P)\n\t// x^3 + ax + b\n\tx3axb := new(big.Int).Mod(new(big.Int).Add(new(big.Int).Add(\n\t\tnew(big.Int).Exp(p.X, big.NewInt(3), ec.P), new(big.Int).Mul(ec.a, p.X)), ec.b), ec.P)\n\t// y^2 =? x^3 + ax + b\n\treturn y2.Cmp(x3axb) == 0\n}", "func (m Mat2f) EqualEps(other Mat2f, epsilon float32) bool {\n\treturn EqualEps(m[0], other[0], epsilon) &&\n\t\tEqualEps(m[1], other[1], epsilon) &&\n\t\tEqualEps(m[2], other[2], epsilon) &&\n\t\tEqualEps(m[3], other[3], epsilon)\n}" ]
[ "0.7732651", "0.74181086", "0.7325745", "0.727985", "0.7089502", "0.70879567", "0.70108104", "0.68559086", "0.6771776", "0.64858735", "0.64129037", "0.6389725", "0.61977386", "0.61949164", "0.6058847", "0.5936546", "0.5934917", "0.5868981", "0.5789859", "0.57296324", "0.5725722", "0.5673213", "0.5638901", "0.56232834", "0.55746424", "0.55274475", "0.54845804", "0.54389614", "0.54352534", "0.5402107", "0.53885174", "0.5373712", "0.53509694", "0.5332852", "0.53320277", "0.53259236", "0.5318291", "0.5292031", "0.5284474", "0.52818143", "0.5281804", "0.5264198", "0.5263746", "0.52612", "0.5214048", "0.51975465", "0.51839495", "0.51786643", "0.51675385", "0.5155834", "0.51538813", "0.51538813", "0.5148918", "0.51472455", "0.5123293", "0.51159006", "0.51090837", "0.5107628", "0.51025605", "0.50990605", "0.50990605", "0.5097646", "0.509268", "0.509031", "0.5088768", "0.5087665", "0.5083641", "0.5077462", "0.50768864", "0.5073357", "0.50728804", "0.5066649", "0.50555784", "0.50553733", "0.5053671", "0.50513196", "0.504802", "0.50381076", "0.50370276", "0.5032447", "0.5032346", "0.5025519", "0.5022097", "0.499958", "0.49986413", "0.49972972", "0.49957284", "0.49924248", "0.4983341", "0.49825132", "0.49769774", "0.49758375", "0.4975025", "0.49718305", "0.49715656", "0.496538", "0.4958534", "0.49564004", "0.49508694", "0.4947428" ]
0.7558922
1
Infinity returns the point at infinity, i.e. with w = 0.
func Infinity() Point { return Point{1, 0} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (d Direction) Infinity() string { return infty[d] }", "func (p *PointProj) setInfinity() *PointProj {\n\tp.X.SetZero()\n\tp.Y.SetOne()\n\tp.Z.SetOne()\n\treturn p\n}", "func (space RealIntervalSpace) Inf() float64 {\n\treturn space.Min\n}", "func (sp positiveRealSpace) Inf() float64 {\n\treturn 0\n}", "func posInf() float64 {\n\treturn math.Inf(1) // argument specifies positive infinity\n}", "func (p *g1JacExtended) setInfinity() *g1JacExtended {\n\tp.X.SetOne()\n\tp.Y.SetOne()\n\tp.ZZ = fp.Element{}\n\tp.ZZZ = fp.Element{}\n\treturn p\n}", "func (sp booleanSpace) Inf() float64 {\n\treturn 0\n}", "func (p *G1Affine) IsInfinity() bool {\n\treturn p.X.IsZero() && p.Y.IsZero()\n}", "func (p *G2Affine) IsInfinity() bool {\n\treturn p.X.IsZero() && p.Y.IsZero()\n}", "func NewInfinityValue() InfinityValue {\n\treturn infinityValue\n}", "func (c curve) IsAtInfinity(X, Y *big.Int) bool {\n\treturn X.Sign() == 0 && Y.Sign() == 0\n}", "func (x *Float) IsInf() bool {}", "func (z *Float) SetInf(signbit bool) *Float {}", "func Inf(sign int) float32 {\n\tvar v uint32\n\tif sign >= 0 {\n\t\tv = uvinf\n\t} else {\n\t\tv = uvneginf\n\t}\n\treturn Float32frombits(v)\n}", "func Inf() complex128 {\n\tinf := math.Inf(1)\n\treturn complex(inf, inf)\n}", "func (v *Vertex) Abs() float64 {\n return math.Sqrt(v.X * v.X + v.Y * v.Y)\n}", "func ZeroSmall(x, y, epsilon float64) float64 {\n\tif Abs(x)/y < epsilon {\n\t\treturn 0\n\t}\n\treturn x\n}", "func FloatSetInf(z *big.Float, signbit bool) *big.Float", "func f(t float64, w float64) float64 {\n\treturn (-1 - 0.02*w + (acc * t))\n}", "func NilPoint() Point {\n\treturn Point{physics.NewVector(0, 0), nil}\n}", "func (ec *EC) Infinite(p *Point) bool {\n\tif p.X == nil || p.Y == nil {\n\t\treturn true\n\t}\n\treturn false\n}", "func (p *Point) Abs() float64 {\n return math.Sqrt(p.x*p.x + p.y*p.y)\n}", "func FloatIsInf(x *big.Float,) bool", "func dorthInfty(p0, p2 Point) Point {\n\treturn Point{signf(p2.X - p0.X), -signf(p2.Y - p0.Y)}\n}", "func (p Point) W() float64 {\n\treturn p[3]\n}", "func (v *vertex) Abs() float64 {\n\treturn math.Sqrt(v.x*v.x + v.y*v.y)\n}", "func (x *Float) MinPrec() uint {}", "func Minf(a, b float32) float32", "func (vl InfinityValue) GetType() int {\n\tpanic(\"Invalid particle type: INF\")\n}", "func (me XsdGoPkgHasElems_MinFadeExtent) MinFadeExtentDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (me XsdGoPkgHasElem_MinFadeExtent) MinFadeExtentDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (v *Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.x*v.x + v.y*v.y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X * v.X + v.Y * v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X * v.X + v.Y * v.Y)\n}", "func NaN() float32 { return Float32frombits(uvnan) }", "func (v *Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func inf() {\n\tfor {\n\n\t}\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func West(value float64) *SimpleElement { return newSEFloat(\"west\", value) }", "func Minimum(values ...float64) float64 {\n\t// initialized with positive infinity, all finite numbers are smaller than it\n\tcurMin := math.Inf(1)\n\tfor _, v := range values {\n\t\tif v < curMin {\n\t\t\tcurMin = v\n\t\t}\n\t}\n\treturn curMin\n}", "func (z *Float) Neg(x *Float) *Float {}", "func (b *Bound) West() float64 {\n\treturn b.sw[0]\n}", "func main() {\n\tv := &Vertex{3, 4}\n\tfmt.Println(v.Abs())\n\n\tf := MyFloat(-math.Sqrt2)\n\tfmt.Println(f.Abs())\n}", "func firstNegSlidingWindows(arr []int, k int) {\n\tsize := len(arr)\n\tque := new(Queue)\n\ti := 0\n\tfor i < size {\n\t\t// Remove out of range elements\n\t\tif que.Len() > 0 && que.Front().(int) <= i-k {\n\t\t\tque.Remove()\n\t\t}\n\t\tif arr[i] < 0 {\n\t\t\tque.Add(i)\n\t\t}\n\t\t// window of size k\n\t\tif i >= (k - 1) {\n\t\t\tif que.Len() > 0 {\n\t\t\t\tfmt.Print(arr[que.Front().(int)], \" \")\n\t\t\t} else {\n\t\t\t\tfmt.Print(\"NAN \")\n\t\t\t}\n\t\t}\n\t\ti += 1\n\t}\n}", "func Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.X * v.X + v.Y * v.Y)\n}", "func Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.x*v.x + v.y*v.y)\n}", "func Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func Abs(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func AbsFunc(v Vertex) float64 {\n return math.Sqrt(v.X * v.X + v.Y * v.Y)\n}", "func (v Vertex) Abs() float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (p Point) Minus(v Point) Point {\n\treturn NewPoint(p.X-v.X, p.Y-v.Y)\n}", "func (me XsdGoPkgHasElem_Near) NearDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (b *Bound) North() float64 {\n\treturn b.ne[1]\n}", "func ( v Vertex ) Abs() float64 {\n\t// Return the Euclidean distance of the vert from the origin\n\treturn math.Sqrt( math.Pow(v.x,2) + math.Pow(v.y,2) )\n}", "func Min(values []float64) float64 {\n\tif len(values) == 0 {\n\t\treturn math.NaN()\n\t}\n\treturnValue := math.Inf(1)\n\tfor _, d := range values {\n\t\treturnValue = math.Min(returnValue, d)\n\t}\n\treturn returnValue\n}", "func Zero() Vect { return Vect{} }", "func fritsch(w, x float64) float64 {\n\tz := math.Log(x/w) - w\n\tw1 := w + 1\n\tq := 2 * w1 * (w1 + 2*z/3)\n\teps := z / w1 * (q - z) / (q - 2*z)\n\treturn w * (1 + eps)\n}", "func NilFloat() Float {\n\treturn Float{0, false}\n}", "func (s *CountMinSketch) W() uint {\n\treturn s.w\n}", "func (m *Matrix) WAbs() int {\n\treturn int(m.x)\n}", "func (me XsdGoPkgHasElems_Near) NearDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (v vertex) abs () float64 {\n\treturn math.Sqrt(v.x*v.x+v.y*v.y)\n}", "func (z *Float) Abs(x *Float) *Float {}", "func (v Vector) W() float64 {\n\treturn v[3]\n}", "func VPSIGNW(mxy, xy, xy1 operand.Op) { ctx.VPSIGNW(mxy, xy, xy1) }", "func North(value float64) *SimpleElement { return newSEFloat(\"north\", value) }", "func (g Graph) FullWeight() float64 {\n count := 0;\n weight := 0.0\n for count < len(*g.full) {\n weight = weight + (*g.full)[count].weight \n count = count + 1\n }\n return weight\n}", "func (u UDim) Neg() UDim {\n\treturn UDim{\n\t\tScale: -u.Scale,\n\t\tOffset: -u.Offset,\n\t}\n}", "func min(x, y float64) float64 {\n\tswitch {\n\tcase math.IsNaN(x) || math.IsNaN(y):\n\t\treturn math.NaN()\n\tcase math.IsInf(x, -1) || math.IsInf(y, -1):\n\t\treturn math.Inf(-1)\n\tcase x == 0 && x == y:\n\t\tif math.Signbit(x) {\n\t\t\treturn x\n\t\t}\n\t\treturn y\n\t}\n\tif x < y {\n\t\treturn x\n\t}\n\treturn y\n}", "func Sinf(a float64) float64 {\n\treturn float64(math.Sin(float64(a)))\n}", "func NuclearWinterTemp(L, alpha, epsilon float64) float64 {\n\treturn NakedPlanetTemp(L, alpha, epsilon) // in this case, ground temperature equlibrates with the temperature of the atmosphere.\n}", "func (v *parameter) ExclusiveMinimum() float64 {\n\tif !v.HasExclusiveMinimum() {\n\t\treturn 0\n\t}\n\treturn *v.exclusiveMinimum\n}", "func (sp positiveRealSpace) Sup() float64 {\n\treturn math.Inf(+1)\n}", "func IsInf(f float32, sign int) bool {\n\t// Test for infinity by comparing against maximum float.\n\t// To avoid the floating-point hardware, could use:\n\t//\t`x := Float32bits(f)`\n\t//\t`return sign >= 0 && x == uvinf || sign <= 0 && x == uvneginf`\n\treturn sign >= 0 && f > MaxFloat32 || sign <= 0 && f < -MaxFloat32\n}", "func (bng *binningP1D) xMin() float64 {\n\treturn bng.xrange.Min\n}", "func (me XsdGoPkgHasElem_MaxFadeExtent) MaxFadeExtentDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (w WeibullMin) CDF(x float64) float64 {\n\tif x < w.Loc {\n\t\treturn 0\n\t}\n\treturn 1 - math.Exp(-math.Pow((x-w.Loc)/w.Scale, w.Shape))\n}", "func nelderMeadOptimize(f func([]float64) float64, start [][]float64, cf func([]float64)) ([]float64, int, int) {\n\tconst (\n\t\tkMax = 1000 // arbitrarily chosen value for now\n\t\tε = 0.000001 // Stopping criterion point\n\t\tα = 1.0\n\t\tβ = 0.5\n\t\tγ = 2.0\n\t)\n\n\t// point is the type of points in ℝ^n\n\ttype point []float64\n\n\t// simplex is the type used to represent a simplex\n\ttype simplex []point\n\n\tevaluations := 0\n\teval := func(f func([]float64) float64, p point) float64 {\n\t\tevaluations++\n\t\treturn f(p)\n\t}\n\n\t// sub perform point subtraction\n\tsub := func(x point, y point) point {\n\t\tr := make(point, len(x))\n\t\tfor i := range y {\n\t\t\tr[i] = x[i] - y[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// add perform point addition\n\tadd := func(x point, y point) point {\n\t\tr := make(point, len(x))\n\t\tfor i := range y {\n\t\t\tr[i] = x[i] + y[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// scale multiplies a point by a scalar\n\tscale := func(p point, scalar float64) point {\n\t\tr := make(point, len(p))\n\t\tfor i := range r {\n\t\t\tr[i] = scalar * p[i]\n\t\t}\n\t\treturn r\n\t}\n\n\t// centroid calculates the centroid of a simplex of one dimensionality lower by omitting a point\n\tcentroid := func(s simplex, omit int) point {\n\t\tr := make(point, len(s[0]))\n\t\tfor i := range r {\n\t\t\tc := 0.0\n\t\t\tfor j := range s {\n\t\t\t\tif j == omit {\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\tc += s[j][i]\n\t\t\t\t}\n\t\t\t}\n\t\t\tr[i] = c / float64((len(s) - 1))\n\t\t}\n\t\treturn r\n\t}\n\n\tn := len(start)\n\tc := len(start[0])\n\tpoints := make([]point, 0)\n\tfv := make([]float64, n)\n\n\tfor _, p := range start {\n\t\tpoints = append(points, point(p))\n\t}\n\tsx := simplex(points)\n\tif n != c+1 {\n\t\tpanic(\"Can't optimize with too few starting points\")\n\t}\n\n\t// Set up initial values\n\tfor i := range fv {\n\t\tif cf != nil {\n\t\t\tcf(sx[i])\n\t\t}\n\t\tfv[i] = eval(f, sx[i])\n\t}\n\n\tk := 0\n\tfor ; k < kMax; k++ {\n\t\t// Find the largest index\n\t\tvg := 0\n\t\tfor i := range fv {\n\t\t\tif fv[i] > fv[vg] {\n\t\t\t\tvg = i\n\t\t\t}\n\t\t}\n\n\t\t// Find the smallest index\n\t\tvs := 0\n\t\tfor i := range fv {\n\t\t\tif fv[i] < fv[vs] {\n\t\t\t\tvs = i\n\t\t\t}\n\t\t}\n\n\t\t// Second largest index\n\t\tvh := vs\n\t\tfor i := range fv {\n\t\t\tif fv[i] > fv[vh] && fv[i] < fv[vg] {\n\t\t\t\tvh = i\n\t\t\t}\n\t\t}\n\n\t\tvm := centroid(sx, vg)\n\n\t\tvr := add(vm, scale(sub(vm, sx[vg]), α))\n\t\tif cf != nil {\n\t\t\tcf(vr)\n\t\t}\n\t\tfr := eval(f, vr)\n\n\t\tif fr < fv[vh] && fr >= fv[vs] {\n\t\t\t// Replace\n\t\t\tfv[vg] = fr\n\t\t\tsx[vg] = vr\n\t\t}\n\n\t\t// Investigate a step further\n\t\tif fr < fv[vs] {\n\t\t\tve := add(vm, scale(sub(vr, vm), γ))\n\t\t\tif cf != nil {\n\t\t\t\tcf(ve)\n\t\t\t}\n\n\t\t\tfe := eval(f, ve)\n\n\t\t\tif fe < fr {\n\t\t\t\tsx[vg] = ve\n\t\t\t\tfv[vg] = fe\n\t\t\t} else {\n\t\t\t\tsx[vg] = vr\n\t\t\t\tfv[vg] = fr\n\t\t\t}\n\t\t}\n\n\t\t// Check contraction\n\t\tif fr >= fv[vh] {\n\t\t\tvar vc point\n\t\t\tvar fc float64\n\t\t\tif fr < fv[vg] && fr >= fv[vh] {\n\t\t\t\t// Outside contraction\n\t\t\t\tvc = add(vm, scale(sub(vr, vm), β))\n\t\t\t} else {\n\t\t\t\t// Inside contraction\n\t\t\t\tvc = sub(vm, scale(sub(vm, sx[vg]), β))\n\t\t\t}\n\n\t\t\tif cf != nil {\n\t\t\t\tcf(vc)\n\t\t\t}\n\t\t\tfc = eval(f, vc)\n\n\t\t\tif fc < fv[vg] {\n\t\t\t\tsx[vg] = vc\n\t\t\t\tfv[vg] = fc\n\t\t\t} else {\n\t\t\t\tfor i := range sx {\n\t\t\t\t\tif i != vs {\n\t\t\t\t\t\tsx[i] = add(sx[vs], scale(sub(sx[i], sx[vs]), β))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif cf != nil {\n\t\t\t\t\tcf(sx[vg])\n\t\t\t\t}\n\t\t\t\tfv[vg] = eval(f, sx[vg])\n\n\t\t\t\tif cf != nil {\n\t\t\t\t\tcf(sx[vh])\n\t\t\t\t}\n\t\t\t\tfv[vh] = eval(f, sx[vh])\n\t\t\t}\n\t\t}\n\n\t\tfsum := 0.0\n\t\tfor _, v := range fv {\n\t\t\tfsum += v\n\t\t}\n\n\t\tfavg := fsum / float64(len(fv))\n\n\t\ts := 0.0\n\t\tfor _, v := range fv {\n\t\t\ts += math.Pow(v-favg, 2.0)\n\t\t}\n\n\t\ts = s * (1.0 / (float64(len(fv)) + 1.0))\n\t\ts = math.Sqrt(s)\n\t\tif s < ε {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvs := 0\n\tfor i := range fv {\n\t\tif fv[i] < fv[vs] {\n\t\t\tvs = i\n\t\t}\n\t}\n\n\treturn sx[vs], k, evaluations\n}", "func (g Graph) FullEdgesTo0ForVertex(v int) {\n count := 0;\n for count < len(*g.full) {\n v1temp := (*g.full)[count].v1_index\n v2temp := (*g.full)[count].v2_index\n if (v == v1temp || v == v2temp){\n //fmt.Printf(\"%d ---- %d\\n\", v1temp, v2temp)\n (*g.full)[count].weight = 0.0\n }\n \n count = count + 1\n }\n}", "func (me XsdGoPkgHasElems_MaxFadeExtent) MaxFadeExtentDefault() xsdt.Double {\r\n\tvar x = new(xsdt.Double)\r\n\tx.Set(\"0.0\")\r\n\treturn *x\r\n}", "func (z nat) divW(x nat, y Word) (q nat, r Word) {\n\tm := len(x)\n\tswitch {\n\tcase y == 0:\n\t\tpanic(\"division by zero\")\n\tcase y == 1:\n\t\tq = z.set(x) // result is x\n\t\treturn\n\tcase m == 0:\n\t\tq = z.make(0) // result is 0\n\t\treturn\n\t}\n\t// m > 0\n\tz = z.make(m)\n\tr = divWVW(z, 0, x, y)\n\tq = z.norm()\n\treturn\n}", "func (s *ClampDirectionOffset) Min() float64 {\n\treturn s.min\n}", "func IsInf(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"IsInf\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func Abs1(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func (o *Object) Min_V(j int) float32 {\n\tx := float32(0)\n\tif len(o.v_list) != 0 {\n\t\t// initial value\n\t\tx = o.v_list[0].x[j]\n\t\tfor i := 0; i < len(o.v_list); i++ {\n\t\t\tif o.v_list[i].x[j] < x {\n\t\t\t\tx = o.v_list[i].x[j]\n\t\t\t}\n\t\t}\n\t}\n\treturn x\n}", "func (s TriangleSection) Wx() (j float64) {\n\tvar zmax float64\n\tzc := s.centerMassZ()\n\tfor _, tr := range s.Elements {\n\t\tfor _, c := range tr.P {\n\t\t\tzmax = math.Max(zmax, c.Z-zc)\n\t\t}\n\t}\n\treturn s.Jx() / zmax\n}", "func (f *Feature) StartZero() uint64 {\n\tif f.Pos == 0 {\n\t\treturn 0\n\t}\n\treturn f.Pos - 1\n}", "func (*BigInt) IsPosInf() bool {\n\treturn false\n}", "func wisNaiveRecursive(vertices []vertex) int {\r\n\tvar maxWIS int\r\n\tif len(vertices) == 0 {\r\n\t\treturn 0\r\n\t} else if len(vertices) == 1 {\r\n\t\treturn vertices[0].weight\r\n\t}\r\n\ts1 := wisNaiveRecursive(vertices[:len(vertices)-1])\r\n\ts2 := wisNaiveRecursive(vertices[:len(vertices)-2])\r\n\tif s1 >= s2+vertices[len(vertices)-1].weight {\r\n\t\tmaxWIS = s1\r\n\t} else {\r\n\t\tmaxWIS = s2+vertices[len(vertices)-1].weight\r\n\t}\r\n\treturn maxWIS\r\n}", "func wind(x, y, w, h openvg.VGfloat, bg, color string) {\n\topenvg.FillColor(bg, 0)\n\topenvg.StrokeWidth(w / 25)\n\topenvg.StrokeColor(color)\n\topenvg.Qbezier(x+w*0.10, y+h*0.8, x+w*0.50, y+h*0.60, x+w*0.9, y+h*0.85)\n\topenvg.Qbezier(x+w*0.10, y+h*0.5, x+w*0.55, y+h*0.30, x+w*0.9, y+h*0.55)\n\topenvg.Qbezier(x+w*0.10, y+h*0.2, x+w*0.60, y+h*0.10, x+w*0.9, y+h*0.35)\n\topenvg.StrokeWidth(0)\n}", "func (p *P1D) XMin() float64 {\n\treturn p.bng.xMin()\n}", "func (b *BinP1D) XFocus() float64 {\n\tif b.SumW() == 0 {\n\t\treturn b.XMid()\n\t}\n\treturn b.XMean()\n}", "func (Integer) IsPosInf() bool {\n\treturn false\n}" ]
[ "0.68027264", "0.66541743", "0.65953475", "0.65390503", "0.65321726", "0.62718815", "0.62357014", "0.6062471", "0.6039281", "0.5973202", "0.58086175", "0.55933356", "0.5577524", "0.55248314", "0.5512503", "0.53914815", "0.5282354", "0.5256853", "0.5216981", "0.51698047", "0.5140126", "0.5124626", "0.5104712", "0.5098392", "0.5097218", "0.5083476", "0.5029377", "0.5028", "0.5018345", "0.5013797", "0.50128335", "0.49942687", "0.4981237", "0.49709654", "0.49709654", "0.4969353", "0.49656162", "0.49576396", "0.4951359", "0.4951359", "0.4951359", "0.4951359", "0.4951359", "0.4951359", "0.4951359", "0.4906164", "0.48897058", "0.488343", "0.48806065", "0.4858375", "0.48547828", "0.4852594", "0.48501816", "0.48314375", "0.48314375", "0.47856343", "0.47459343", "0.47452387", "0.47447312", "0.47344977", "0.47269827", "0.47268483", "0.47179118", "0.47091037", "0.47034112", "0.46997264", "0.4696162", "0.46944854", "0.46902928", "0.46887884", "0.46811754", "0.46676874", "0.4666344", "0.4655699", "0.4653212", "0.4622936", "0.46222657", "0.46125093", "0.46082556", "0.460292", "0.45990026", "0.45913917", "0.4587691", "0.4587028", "0.4583395", "0.45825228", "0.45675984", "0.4561533", "0.4553041", "0.45506442", "0.45468998", "0.45430517", "0.45322108", "0.45076767", "0.45039764", "0.4494475", "0.44912535", "0.44893178", "0.44887474", "0.44856846" ]
0.78651977
0
Inv implements inversion respect to a circle.
func (p *Point) Inv(c Circle) { var A = -c.C var B = complex(-c.D, 0) var C = complex(c.A, 0) var D = cmplx.Conj(c.C) var Z = p.Z var W = p.W p.Z = A*Z + B*W p.W = C*Z + D*W }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Circle) Inv(i Circle) {\n\tvar transform = m2c.NewMatrix(complex(i.D, 0), -conj(i.C), -i.C, complex(i.A, 0))\n\tvar circle = m2c.NewMatrix(complex(c.A, 0), conj(c.C), c.C, complex(c.D, 0))\n\n\tvar invertedCircle = m2c.Mul(m2c.Mul(m2c.T(m2c.Conj(transform)), m2c.T(circle)), transform)\n\tc.A = real(invertedCircle.A)\n\tc.C = invertedCircle.C\n\tc.D = real(invertedCircle.D)\n}", "func (z *Rat) Inv(x *Rat) *Rat {\n\t// possible: panic(\"division by zero\")\n}", "func RatInv(z *big.Rat, x *big.Rat,) *big.Rat", "func (e *Ellipsoid) Inverse(\n\tlat1, lon1, lat2, lon2 float64,\n\ts12, azi1, azi2 *float64,\n) {\n\tC.geod_inverse(&e.g,\n\t\tC.double(lat1), C.double(lon1), C.double(lat2), C.double(lon2),\n\t\t(*C.double)(s12), (*C.double)(azi1), (*C.double)(azi2))\n}", "func (z *Float64) Inv(y *Float64) *Float64 {\n\tif y.IsZeroDivisor() {\n\t\tpanic(zeroDivisorInverse)\n\t}\n\treturn z.Divide(z.Conj(y), y.Quad())\n}", "func (z *BiComplex) Inv(y *BiComplex) *BiComplex {\n\tif y.IsZeroDivisor() {\n\t\tpanic(\"inverse of zero divisor\")\n\t}\n\tquad := y.Quad()\n\tquad.Inv(quad)\n\tz.Conj(y)\n\tz.l.Mul(&z.l, quad)\n\tz.r.Mul(&z.r, quad)\n\treturn z\n}", "func (s VectOp) Inv() VectOp {\n\treturn fs.Idivl(s, 1)\n}", "func (ch *CholFactors) Inv(out *Dense) *Dense {\n\tl := ch.l\n\tif l == nil {\n\t\tpanic(errInNil)\n\t}\n\n\tn := l.Rows()\n\n\tif out == nil {\n\t\tout = NewDense(n, n)\n\t} else {\n\t\tif out.Rows() != n || out.cols != n {\n\t\t\tpanic(errOutShape)\n\t\t}\n\t\tout.Fill(0.0)\n\t}\n\tout.FillDiag(1.0)\n\n\treturn ch.Solve(out)\n}", "func (x *Secp256k1N) Inv(y *Secp256k1N) {\n\tC.secp256k1n_inv((*C.secp256k1n)(unsafe.Pointer(x)), (*C.secp256k1n)(unsafe.Pointer(y)))\n}", "func (z *InfraHamilton) Inv(y *InfraHamilton) *InfraHamilton {\n\tif y.IsZeroDivisor() {\n\t\tpanic(\"inverse of zero divisor\")\n\t}\n\ta := y.Quad()\n\ta.Inv(a)\n\treturn z.Scal(z.Conj(y), a)\n}", "func Inv(proj *Proj, x, y float64) (long, lat float64, err error) {\n\tif !proj.opened {\n\t\treturn math.NaN(), math.NaN(), errors.New(\"projection is closed\")\n\t}\n\tx2 := C.double(x)\n\ty2 := C.double(y)\n\te := C.inv(proj.pj, &x2, &y2)\n\tif e != nil {\n\t\treturn math.NaN(), math.NaN(), errors.New(C.GoString(e))\n\t}\n\treturn float64(x2), float64(y2), nil\n}", "func (c *Clac) Inv() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn unary(\"/\", vals[0])\n\t})\n}", "func (group *QRRSA) Inv(x *big.Int) *big.Int {\n\treturn new(big.Int).ModInverse(x, group.N)\n}", "func InverseNuttal(input VectorComplex) VectorComplex {\n\tvih := input.Copy()\n\ttheta := 2.0 * math.Pi / float64(len(vih)-1)\n\ta0 := complex(0.355768, 0.0)\n\ta1 := complex(0.487396, 0.0)\n\ta2 := complex(0.144232, 0.0)\n\ta3 := complex(0.012604, 0.0)\n\n\tfor i := 0; i < len(vih); i++ {\n\t\tx := complex(theta*float64(i), 0)\n\t\tvih[i] /= a0 - a1*cmplx.Cos(x) + a2*cmplx.Cos(2.0*x) + a3*cmplx.Cos(3.0*x)\n\t}\n\treturn vih\n}", "func (a Vec2) Inverse() Vec2 {\n\treturn Vec2{-a.X, -a.Y}\n}", "func (v *Vector) Inverse() *Vector {\n\treturn &Vector{\n\t\tX: -v.X,\n\t\tY: -v.Y,\n\t}\n}", "func (u Unit) Inv() Unit {\n\treturn Unit(Vec(u).Inv())\n}", "func inverse(c color.RGBA) color.RGBA {\n\tc.R = ^c.R - 147\n\tc.G = ^c.G - 147\n\tc.B = ^c.B - 147\n\treturn c\n}", "func InverseHann(input VectorComplex) VectorComplex {\n\tvih := input.Copy()\n\ttheta := 2.0 * math.Pi / float64(len(vih)-1)\n\tfor i := 0; i < len(vih); i++ {\n\t\tx := complex(theta*float64(i), 0)\n\t\tvih[i] /= (1.0 - cmplx.Cos(x)) / 2.0\n\t}\n\treturn vih\n}", "func (t Target) Inverse() *big.Rat {\n\treturn new(big.Rat).Inv(t.Rat())\n}", "func (d *GF255e) Inv(a *GF255e) *GF255e {\n\tgf_inv_scaled((*[4]uint64)(d), (*[4]uint64)(a), mq255e)\n\tgf_mul((*[4]uint64)(d), (*[4]uint64)(d), (*[4]uint64)(&GF255e_INVT508), mq255e)\n\treturn d\n}", "func Inv(z *Elt, x *Elt) {\n\t// Inversion computation is derived from the addition chain:\n\t//\n\t// _10 = 2*1\n\t// _11 = 1 + _10\n\t// _1100 = _11 << 2\n\t// _1111 = _11 + _1100\n\t// _11110000 = _1111 << 4\n\t// _11111111 = _1111 + _11110000\n\t// x10 = _11111111 << 2 + _11\n\t// x20 = x10 << 10 + x10\n\t// x30 = x20 << 10 + x10\n\t// x60 = x30 << 30 + x30\n\t// x120 = x60 << 60 + x60\n\t// x240 = x120 << 120 + x120\n\t// x250 = x240 << 10 + x10\n\t// return (x250 << 2 + 1) << 3 + _11\n\t//\n\t// Operations: 254 squares 12 multiplies\n\n\t// Allocate 3 temporaries.\n\tvar t [3]Elt\n\n\t// Step 1: z = x^0x2.\n\tSqr(z, x)\n\n\t// Step 2: z = x^0x3.\n\tMul(z, x, z)\n\n\t// Step 4: &t[0] = x^0xc.\n\tSqr(&t[0], z)\n\tfor s := 1; s < 2; s++ {\n\t\tSqr(&t[0], &t[0])\n\t}\n\n\t// Step 5: &t[0] = x^0xf.\n\tMul(&t[0], z, &t[0])\n\n\t// Step 9: &t[1] = x^0xf0.\n\tSqr(&t[1], &t[0])\n\tfor s := 1; s < 4; s++ {\n\t\tSqr(&t[1], &t[1])\n\t}\n\n\t// Step 10: &t[0] = x^0xff.\n\tMul(&t[0], &t[0], &t[1])\n\n\t// Step 12: &t[0] = x^0x3fc.\n\tfor s := 0; s < 2; s++ {\n\t\tSqr(&t[0], &t[0])\n\t}\n\n\t// Step 13: &t[0] = x^0x3ff.\n\tMul(&t[0], z, &t[0])\n\n\t// Step 23: &t[1] = x^0xffc00.\n\tSqr(&t[1], &t[0])\n\tfor s := 1; s < 10; s++ {\n\t\tSqr(&t[1], &t[1])\n\t}\n\n\t// Step 24: &t[1] = x^0xfffff.\n\tMul(&t[1], &t[0], &t[1])\n\n\t// Step 34: &t[1] = x^0x3ffffc00.\n\tfor s := 0; s < 10; s++ {\n\t\tSqr(&t[1], &t[1])\n\t}\n\n\t// Step 35: &t[1] = x^0x3fffffff.\n\tMul(&t[1], &t[0], &t[1])\n\n\t// Step 65: &t[2] = x^0xfffffffc0000000.\n\tSqr(&t[2], &t[1])\n\tfor s := 1; s < 30; s++ {\n\t\tSqr(&t[2], &t[2])\n\t}\n\n\t// Step 66: &t[1] = x^0xfffffffffffffff.\n\tMul(&t[1], &t[1], &t[2])\n\n\t// Step 126: &t[2] = x^0xfffffffffffffff000000000000000.\n\tSqr(&t[2], &t[1])\n\tfor s := 1; s < 60; s++ {\n\t\tSqr(&t[2], &t[2])\n\t}\n\n\t// Step 127: &t[1] = x^0xffffffffffffffffffffffffffffff.\n\tMul(&t[1], &t[1], &t[2])\n\n\t// Step 247: &t[2] = x^0xffffffffffffffffffffffffffffff000000000000000000000000000000.\n\tSqr(&t[2], &t[1])\n\tfor s := 1; s < 120; s++ {\n\t\tSqr(&t[2], &t[2])\n\t}\n\n\t// Step 248: &t[1] = x^0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.\n\tMul(&t[1], &t[1], &t[2])\n\n\t// Step 258: &t[1] = x^0x3fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc00.\n\tfor s := 0; s < 10; s++ {\n\t\tSqr(&t[1], &t[1])\n\t}\n\n\t// Step 259: &t[0] = x^0x3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.\n\tMul(&t[0], &t[0], &t[1])\n\n\t// Step 261: &t[0] = x^0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc.\n\tfor s := 0; s < 2; s++ {\n\t\tSqr(&t[0], &t[0])\n\t}\n\n\t// Step 262: &t[0] = x^0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffd.\n\tMul(&t[0], x, &t[0])\n\n\t// Step 265: &t[0] = x^0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe8.\n\tfor s := 0; s < 3; s++ {\n\t\tSqr(&t[0], &t[0])\n\t}\n\n\t// Step 266: z = x^0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeb.\n\tMul(z, z, &t[0])\n}", "func NewINV(i, o *Wire) *Gate {\n\tgate := &Gate{\n\t\tOp: circuit.INV,\n\t\tA: i,\n\t\tO: o,\n\t}\n\ti.AddOutput(gate)\n\to.SetInput(gate)\n\n\treturn gate\n}", "func (z *E12) Inverse(x *E12) *E12 {\n\t// Algorithm 23 from https://eprint.iacr.org/2010/354.pdf\n\n\tvar t0, t1, tmp E6\n\tt0.Square(&x.C0)\n\tt1.Square(&x.C1)\n\ttmp.MulByNonResidue(&t1)\n\tt0.Sub(&t0, &tmp)\n\tt1.Inverse(&t0)\n\tz.C0.Mul(&x.C0, &t1)\n\tz.C1.Mul(&x.C1, &t1).Neg(&z.C1)\n\n\treturn z\n}", "func (gdt *Vector3) Inverse() Vector3 {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_inverse(GDNative.api, arg0)\n\n\treturn Vector3{base: &ret}\n\n}", "func Inv(z, x *Elt) {\n\tx0, x1, x2 := &Elt{}, &Elt{}, &Elt{}\n\tSqr(x1, x)\n\tSqr(x0, x1)\n\tSqr(x0, x0)\n\tMul(x0, x0, x)\n\tMul(z, x0, x1)\n\tSqr(x1, z)\n\tMul(x0, x0, x1)\n\tSqr(x1, x0)\n\tfor i := 0; i < 4; i++ {\n\t\tSqr(x1, x1)\n\t}\n\tMul(x0, x0, x1)\n\tSqr(x1, x0)\n\tfor i := 0; i < 9; i++ {\n\t\tSqr(x1, x1)\n\t}\n\tMul(x1, x1, x0)\n\tSqr(x2, x1)\n\tfor i := 0; i < 19; i++ {\n\t\tSqr(x2, x2)\n\t}\n\tMul(x2, x2, x1)\n\tfor i := 0; i < 10; i++ {\n\t\tSqr(x2, x2)\n\t}\n\tMul(x2, x2, x0)\n\tSqr(x0, x2)\n\tfor i := 0; i < 49; i++ {\n\t\tSqr(x0, x0)\n\t}\n\tMul(x0, x0, x2)\n\tSqr(x1, x0)\n\tfor i := 0; i < 99; i++ {\n\t\tSqr(x1, x1)\n\t}\n\tMul(x1, x1, x0)\n\tfor i := 0; i < 50; i++ {\n\t\tSqr(x1, x1)\n\t}\n\tMul(x1, x1, x2)\n\tfor i := 0; i < 5; i++ {\n\t\tSqr(x1, x1)\n\t}\n\tMul(z, z, x1)\n}", "func Inv(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Inv\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (d Decimal) Sin() Decimal {\n\tPI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts\n\tPI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,\n\tPI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,\n\tM4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi\n\n\tif d.Equal(NewFromFloat(0.0)) {\n\t\treturn d\n\t}\n\t// make argument positive but save the sign\n\tsign := false\n\tif d.LessThan(NewFromFloat(0.0)) {\n\t\td = d.Neg()\n\t\tsign = true\n\t}\n\n\tj := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle\n\ty := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float\n\n\t// map zeros to origin\n\tif j&1 == 1 {\n\t\tj++\n\t\ty = y.Add(NewFromFloat(1.0))\n\t}\n\tj &= 7 // octant modulo 2Pi radians (360 degrees)\n\t// reflect in x axis\n\tif j > 3 {\n\t\tsign = !sign\n\t\tj -= 4\n\t}\n\tz := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic\n\tzz := z.Mul(z)\n\n\tif j == 1 || j == 2 {\n\t\tw := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))\n\t\ty = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)\n\t} else {\n\t\ty = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))\n\t}\n\tif sign {\n\t\ty = y.Neg()\n\t}\n\treturn y\n}", "func ForAngle(a f.Float) Vect { return Vect{f.Cos(a), f.Sin(a)} }", "func (a Vec4) Inverse() Vec4 {\n\treturn Vec4{-a.X, -a.Y, -a.Z, -a.W}\n}", "func Asin(value gcv.Value) gcv.Value {\n\tif value.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Asin(value.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Asin(value.Real()))\n}", "func Invert(m []gl.Float) ([]gl.Float, error) {\n\n\t//double inv[16], det;\n\t//int i;\n\tinv := make([]gl.Float, 16)\n\tinvOut := make([]gl.Float, 16)\n\tif len(m) != 16 {\n\t\treturn nil, errors.New(\"Not a 4x4 matrix, needs 16 elements\")\n\t}\n\n\tinv[0] = m[5]*m[10]*m[15] -\n\t\tm[5]*m[11]*m[14] -\n\t\tm[9]*m[6]*m[15] +\n\t\tm[9]*m[7]*m[14] +\n\t\tm[13]*m[6]*m[11] -\n\t\tm[13]*m[7]*m[10]\n\n\tinv[4] = -m[4]*m[10]*m[15] +\n\t\tm[4]*m[11]*m[14] +\n\t\tm[8]*m[6]*m[15] -\n\t\tm[8]*m[7]*m[14] -\n\t\tm[12]*m[6]*m[11] +\n\t\tm[12]*m[7]*m[10]\n\n\tinv[8] = m[4]*m[9]*m[15] -\n\t\tm[4]*m[11]*m[13] -\n\t\tm[8]*m[5]*m[15] +\n\t\tm[8]*m[7]*m[13] +\n\t\tm[12]*m[5]*m[11] -\n\t\tm[12]*m[7]*m[9]\n\n\tinv[12] = -m[4]*m[9]*m[14] +\n\t\tm[4]*m[10]*m[13] +\n\t\tm[8]*m[5]*m[14] -\n\t\tm[8]*m[6]*m[13] -\n\t\tm[12]*m[5]*m[10] +\n\t\tm[12]*m[6]*m[9]\n\n\tinv[1] = -m[1]*m[10]*m[15] +\n\t\tm[1]*m[11]*m[14] +\n\t\tm[9]*m[2]*m[15] -\n\t\tm[9]*m[3]*m[14] -\n\t\tm[13]*m[2]*m[11] +\n\t\tm[13]*m[3]*m[10]\n\n\tinv[5] = m[0]*m[10]*m[15] -\n\t\tm[0]*m[11]*m[14] -\n\t\tm[8]*m[2]*m[15] +\n\t\tm[8]*m[3]*m[14] +\n\t\tm[12]*m[2]*m[11] -\n\t\tm[12]*m[3]*m[10]\n\n\tinv[9] = -m[0]*m[9]*m[15] +\n\t\tm[0]*m[11]*m[13] +\n\t\tm[8]*m[1]*m[15] -\n\t\tm[8]*m[3]*m[13] -\n\t\tm[12]*m[1]*m[11] +\n\t\tm[12]*m[3]*m[9]\n\n\tinv[13] = m[0]*m[9]*m[14] -\n\t\tm[0]*m[10]*m[13] -\n\t\tm[8]*m[1]*m[14] +\n\t\tm[8]*m[2]*m[13] +\n\t\tm[12]*m[1]*m[10] -\n\t\tm[12]*m[2]*m[9]\n\n\tinv[2] = m[1]*m[6]*m[15] -\n\t\tm[1]*m[7]*m[14] -\n\t\tm[5]*m[2]*m[15] +\n\t\tm[5]*m[3]*m[14] +\n\t\tm[13]*m[2]*m[7] -\n\t\tm[13]*m[3]*m[6]\n\n\tinv[6] = -m[0]*m[6]*m[15] +\n\t\tm[0]*m[7]*m[14] +\n\t\tm[4]*m[2]*m[15] -\n\t\tm[4]*m[3]*m[14] -\n\t\tm[12]*m[2]*m[7] +\n\t\tm[12]*m[3]*m[6]\n\n\tinv[10] = m[0]*m[5]*m[15] -\n\t\tm[0]*m[7]*m[13] -\n\t\tm[4]*m[1]*m[15] +\n\t\tm[4]*m[3]*m[13] +\n\t\tm[12]*m[1]*m[7] -\n\t\tm[12]*m[3]*m[5]\n\n\tinv[14] = -m[0]*m[5]*m[14] +\n\t\tm[0]*m[6]*m[13] +\n\t\tm[4]*m[1]*m[14] -\n\t\tm[4]*m[2]*m[13] -\n\t\tm[12]*m[1]*m[6] +\n\t\tm[12]*m[2]*m[5]\n\n\tinv[3] = -m[1]*m[6]*m[11] +\n\t\tm[1]*m[7]*m[10] +\n\t\tm[5]*m[2]*m[11] -\n\t\tm[5]*m[3]*m[10] -\n\t\tm[9]*m[2]*m[7] +\n\t\tm[9]*m[3]*m[6]\n\n\tinv[7] = m[0]*m[6]*m[11] -\n\t\tm[0]*m[7]*m[10] -\n\t\tm[4]*m[2]*m[11] +\n\t\tm[4]*m[3]*m[10] +\n\t\tm[8]*m[2]*m[7] -\n\t\tm[8]*m[3]*m[6]\n\n\tinv[11] = -m[0]*m[5]*m[11] +\n\t\tm[0]*m[7]*m[9] +\n\t\tm[4]*m[1]*m[11] -\n\t\tm[4]*m[3]*m[9] -\n\t\tm[8]*m[1]*m[7] +\n\t\tm[8]*m[3]*m[5]\n\n\tinv[15] = m[0]*m[5]*m[10] -\n\t\tm[0]*m[6]*m[9] -\n\t\tm[4]*m[1]*m[10] +\n\t\tm[4]*m[2]*m[9] +\n\t\tm[8]*m[1]*m[6] -\n\t\tm[8]*m[2]*m[5]\n\n\tdet := m[0]*inv[0] + m[1]*inv[4] + m[2]*inv[8] + m[3]*inv[12]\n\n\tif det == 0 {\n\t\treturn nil, errors.New(\"No inverse for this matrix!\")\n\t}\n\n\tdet = 1.0 / det\n\n\tfor i := 0; i < 16; i++ {\n\t\tinvOut[i] = inv[i] * det\n\t}\n\n\treturn invOut, nil\n}", "func involuteXY(\n\tr float64, // base radius\n\ttheta float64, // involute angle\n) v2.Vec {\n\tc := math.Cos(theta)\n\ts := math.Sin(theta)\n\treturn v2.Vec{\n\t\tr * (c + theta*s),\n\t\tr * (s - theta*c),\n\t}\n}", "func Sin(in Res) Res {\n\tout := in.Output().Copy()\n\tanyvec.Sin(out)\n\treturn &sinRes{\n\t\tIn: in,\n\t\tOutVec: out,\n\t}\n}", "func (a *Vec4) Invert() {\n\ta.X = -a.X\n\ta.Y = -a.Y\n\ta.Z = -a.Z\n\ta.W = -a.W\n}", "func (s *Scalar) Invert(x *Scalar) *Scalar {\n\ts.s.Inv(&x.s)\n\treturn s\n}", "func (m *ModFactorial) CalcInv(n int) int {\n\tl := len(m.invs)\n\tif n < l {\n\t\treturn m.invs[n]\n\t}\n\ttmp := make([]int, n+1-l)\n\tm.invs = append(m.invs, tmp...)\n\tm.invs[n] = ModInv(m.Calc(n), m.mod)\n\tfor i := n - 1; i >= l; i-- {\n\t\tm.invs[i] = m.invs[i+1] * (i + 1) % m.mod\n\t}\n\treturn m.invs[n]\n\n}", "func (c Color) Inverse() Color {\n\treturn Color{255 - c.R, 255 - c.G, 255 - c.B, c.A}\n}", "func iCircle(x, y, r int, color color.RGBA) *canvas.Circle {\n\tfx, fy, fr := float32(x), float32(y), float32(r)\n\tp1 := fyne.Position{X: fx - fr, Y: fy - fr}\n\tp2 := fyne.Position{X: fx + fr, Y: fy + fr}\n\tc := &canvas.Circle{FillColor: color, Position1: p1, Position2: p2}\n\treturn c\n}", "func (s VectOp) Minv(v []float64) VectOp {\n\treturn fs.Minv(s, v)\n}", "func CircInOut(t, b, c, d float64) float64 {\n\tif t > d {\n\t\treturn c\n\t}\n\n\tt /= d / 2\n\n\tif t < 1 {\n\t\treturn -c/2*(math.Sqrt(1-t*t)-1) + b\n\t}\n\n\tt -= 2\n\n\treturn c/2*(math.Sqrt(1-t*t)+1) + b\n}", "func norminv(p float64) (float64, error) {\n\ta := map[int]float64{\n\t\t1: -3.969683028665376e+01, 2: 2.209460984245205e+02, 3: -2.759285104469687e+02,\n\t\t4: 1.383577518672690e+02, 5: -3.066479806614716e+01, 6: 2.506628277459239e+00,\n\t}\n\tb := map[int]float64{\n\t\t1: -5.447609879822406e+01, 2: 1.615858368580409e+02, 3: -1.556989798598866e+02,\n\t\t4: 6.680131188771972e+01, 5: -1.328068155288572e+01,\n\t}\n\tc := map[int]float64{\n\t\t1: -7.784894002430293e-03, 2: -3.223964580411365e-01, 3: -2.400758277161838e+00,\n\t\t4: -2.549732539343734e+00, 5: 4.374664141464968e+00, 6: 2.938163982698783e+00,\n\t}\n\td := map[int]float64{\n\t\t1: 7.784695709041462e-03, 2: 3.224671290700398e-01, 3: 2.445134137142996e+00,\n\t\t4: 3.754408661907416e+00,\n\t}\n\tpLow := 0.02425 // Use lower region approx. below this\n\tpHigh := 1 - pLow // Use upper region approx. above this\n\tif 0 < p && p < pLow {\n\t\t// Rational approximation for lower region.\n\t\tq := math.Sqrt(-2 * math.Log(p))\n\t\treturn (((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /\n\t\t\t((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil\n\t} else if pLow <= p && p <= pHigh {\n\t\t// Rational approximation for central region.\n\t\tq := p - 0.5\n\t\tr := q * q\n\t\tf1 := ((((a[1]*r+a[2])*r+a[3])*r+a[4])*r + a[5]) * r\n\t\tf2 := (b[1]*r + b[2]) * r\n\t\tf3 := ((math.Nextafter(f2, f2)+b[3])*r + b[4]) * r\n\t\tf4 := (math.Nextafter(f3, f3) + b[5]) * r\n\t\treturn (math.Nextafter(f1, f1) + a[6]) * q /\n\t\t\t(math.Nextafter(f4, f4) + 1), nil\n\t} else if pHigh < p && p < 1 {\n\t\t// Rational approximation for upper region.\n\t\tq := math.Sqrt(-2 * math.Log(1-p))\n\t\treturn -(((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /\n\t\t\t((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil\n\t}\n\treturn 0, errors.New(formulaErrorNUM)\n}", "func (a Scalar) Invert() { \n\tC.crypto_core_ed25519_scalar_invert((*C.uchar)(&a.Val[0]),(*C.uchar)(&a.Val[0]));\n\ta.Refresh_bint()\n}", "func CircIn(t, b, c, d float64) float64 {\n\tif t > d {\n\t\treturn c\n\t}\n\n\tt /= d\n\n\treturn -c*(math.Sqrt(1-t*t)-1) + b\n}", "func (v Vec3i) Negate() Vec3i {\n\treturn Vec3i{-v.X, -v.Y, -v.Z}\n}", "func (mPointer *GF8Matrix) Inv() (*GF8Matrix, error) {\n\tm := NewMatrix(mPointer.numRow, mPointer.numCol)\n\tcopy(m.Matrix, mPointer.Matrix)\n\tif m.numCol != m.numRow {\n\t\tlog.Fatal(ErrNotSquareMatrix)\n\t}\n\t// extend identity matrix to right half\n\tfor r := 0; r < m.numRow; r++ {\n\t\tprepandArray := make([]byte, m.numCol)\n\t\tprepandArray[r] = 1\n\t\tm.Matrix[r] = append(m.Matrix[r], prepandArray...)\n\t}\n\toriginalNumCol := m.numCol\n\tm.numCol += originalNumCol\n\t// make left half identity\n\tfor r := 0; r < m.numRow; r++ {\n\t\t// find head\n\t\tsingularFlag := true\n\t\tfor iFindHead := r; iFindHead < m.numRow; iFindHead++ {\n\t\t\tif m.Matrix[iFindHead][r] != 0 {\n\t\t\t\tif iFindHead != r {\n\t\t\t\t\tm.swapRow(iFindHead, r)\n\t\t\t\t}\n\t\t\t\tsingularFlag = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif singularFlag {\n\t\t\treturn nil, ErrSingularMatrix\n\t\t}\n\t\t// make this diagnal unit\n\t\thead := m.Matrix[r][r]\n\t\tm.multRow(r, inverseTbl[head])\n\t\t// erase other rows\n\t\tfor rFollow := 0; rFollow < m.numRow; rFollow++ {\n\t\t\tif rFollow == r || m.Matrix[rFollow][r] == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tm.mulAddToRow(r, m.Matrix[rFollow][r], rFollow)\n\t\t}\n\t}\n\t//remove left half\n\tfor r := 0; r < m.numRow; r++ {\n\t\tm.Matrix[r] = m.Matrix[r][originalNumCol:]\n\t}\n\tm.numCol = originalNumCol\n\n\tif SanityCheck {\n\t\tshouldBeIdentity := m.Mul(mPointer)\n\t\tshouldBeIdentity.ShowMatrix(SanityCheck)\n\t\tfor r := 0; r < m.numRow; r++ {\n\t\t\tfor c := 0; c < m.numCol; c++ {\n\t\t\t\tif r == c && shouldBeIdentity.Matrix[r][c] != 1 {\n\t\t\t\t\tlog.Fatalf(\"Fail the sanity check, %v != 1\", shouldBeIdentity.Matrix[r][c])\n\t\t\t\t} else if r != c && shouldBeIdentity.Matrix[r][c] != 0 {\n\t\t\t\t\tlog.Fatalf(\"Fail the sanity check, %v != 0\", shouldBeIdentity.Matrix[r][c])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn m, nil\n}", "func (a *Mtx) Inverse() *Mtx {\n\tif a.inv != nil {\n\t\treturn a.inv\n\t}\n\ti := Identity()\n\te := a.el\n\ti.el[0][0] = e[1][1]*e[2][2]*e[3][3] - e[1][1]*e[2][3]*e[3][2] - e[2][1]*e[1][2]*e[3][3] + e[2][1]*e[1][3]*e[3][2] + e[3][1]*e[1][2]*e[2][3] - e[3][1]*e[1][3]*e[2][2]\n\ti.el[1][0] = e[1][0]*e[2][3]*e[3][2] - e[1][0]*e[2][2]*e[3][3] + e[2][0]*e[1][2]*e[3][3] - e[2][0]*e[1][3]*e[3][2] - e[3][0]*e[1][2]*e[2][3] + e[3][0]*e[1][3]*e[2][2]\n\ti.el[2][0] = e[1][0]*e[2][1]*e[3][3] - e[1][0]*e[2][3]*e[3][1] - e[2][0]*e[1][1]*e[3][3] + e[2][0]*e[1][3]*e[3][1] + e[3][0]*e[1][1]*e[2][3] - e[3][0]*e[1][3]*e[2][1]\n\ti.el[3][0] = e[1][0]*e[2][2]*e[3][1] - e[1][0]*e[2][1]*e[3][2] + e[2][0]*e[1][1]*e[3][2] - e[2][0]*e[1][2]*e[3][1] - e[3][0]*e[1][1]*e[2][2] + e[3][0]*e[1][2]*e[2][1]\n\ti.el[0][1] = e[0][1]*e[2][3]*e[3][2] - e[0][1]*e[2][2]*e[3][3] + e[2][1]*e[0][2]*e[3][3] - e[2][1]*e[0][3]*e[3][2] - e[3][1]*e[0][2]*e[2][3] + e[3][1]*e[0][3]*e[2][2]\n\ti.el[1][1] = e[0][0]*e[2][2]*e[3][3] - e[0][0]*e[2][3]*e[3][2] - e[2][0]*e[0][2]*e[3][3] + e[2][0]*e[0][3]*e[3][2] + e[3][0]*e[0][2]*e[2][3] - e[3][0]*e[0][3]*e[2][2]\n\ti.el[2][1] = e[0][0]*e[2][3]*e[3][1] - e[0][0]*e[2][1]*e[3][3] + e[2][0]*e[0][1]*e[3][3] - e[2][0]*e[0][3]*e[3][1] - e[3][0]*e[0][1]*e[2][3] + e[3][0]*e[0][3]*e[2][1]\n\ti.el[3][1] = e[0][0]*e[2][1]*e[3][2] - e[0][0]*e[2][2]*e[3][1] - e[2][0]*e[0][1]*e[3][2] + e[2][0]*e[0][2]*e[3][1] + e[3][0]*e[0][1]*e[2][2] - e[3][0]*e[0][2]*e[2][1]\n\ti.el[0][2] = e[0][1]*e[1][2]*e[3][3] - e[0][1]*e[1][3]*e[3][2] - e[1][1]*e[0][2]*e[3][3] + e[1][1]*e[0][3]*e[3][2] + e[3][1]*e[0][2]*e[1][3] - e[3][1]*e[0][3]*e[1][2]\n\ti.el[1][2] = e[0][0]*e[1][3]*e[3][2] - e[0][0]*e[1][2]*e[3][3] + e[1][0]*e[0][2]*e[3][3] - e[1][0]*e[0][3]*e[3][2] - e[3][0]*e[0][2]*e[1][3] + e[3][0]*e[0][3]*e[1][2]\n\ti.el[2][2] = e[0][0]*e[1][1]*e[3][3] - e[0][0]*e[1][3]*e[3][1] - e[1][0]*e[0][1]*e[3][3] + e[1][0]*e[0][3]*e[3][1] + e[3][0]*e[0][1]*e[1][3] - e[3][0]*e[0][3]*e[1][1]\n\ti.el[3][2] = e[0][0]*e[1][2]*e[3][1] - e[0][0]*e[1][1]*e[3][2] + e[1][0]*e[0][1]*e[3][2] - e[1][0]*e[0][2]*e[3][1] - e[3][0]*e[0][1]*e[1][2] + e[3][0]*e[0][2]*e[1][1]\n\ti.el[0][3] = e[0][1]*e[1][3]*e[2][2] - e[0][1]*e[1][2]*e[2][3] + e[1][1]*e[0][2]*e[2][3] - e[1][1]*e[0][3]*e[2][2] - e[2][1]*e[0][2]*e[1][3] + e[2][1]*e[0][3]*e[1][2]\n\ti.el[1][3] = e[0][0]*e[1][2]*e[2][3] - e[0][0]*e[1][3]*e[2][2] - e[1][0]*e[0][2]*e[2][3] + e[1][0]*e[0][3]*e[2][2] + e[2][0]*e[0][2]*e[1][3] - e[2][0]*e[0][3]*e[1][2]\n\ti.el[2][3] = e[0][0]*e[1][3]*e[2][1] - e[0][0]*e[1][1]*e[2][3] + e[1][0]*e[0][1]*e[2][3] - e[1][0]*e[0][3]*e[2][1] - e[2][0]*e[0][1]*e[1][3] + e[2][0]*e[0][3]*e[1][1]\n\ti.el[3][3] = e[0][0]*e[1][1]*e[2][2] - e[0][0]*e[1][2]*e[2][1] - e[1][0]*e[0][1]*e[2][2] + e[1][0]*e[0][2]*e[2][1] + e[2][0]*e[0][1]*e[1][2] - e[2][0]*e[0][2]*e[1][1]\n\tdet := 1.0 / (e[0][0]*i.el[0][0] + e[0][1]*i.el[1][0] + e[0][2]*i.el[2][0] + e[0][3]*i.el[3][0])\n\tfor j := 0; j < 4; j++ {\n\t\tfor k := 0; k < 4; k++ {\n\t\t\ti.el[j][k] *= det\n\t\t}\n\t}\n\ta.inv, i.inv = i, a\n\treturn i\n}", "func calcIterateInverse(iterator calcInverseIterator, fAx, fBx float64) float64 {\n\tfAy, fBy := iterator.callBack(fAx), iterator.callBack(fBx)\n\tvar fTemp float64\n\tvar nCount int\n\tfor nCount = 0; nCount < 1000 && !hasChangeOfSign(fAy, fBy); nCount++ {\n\t\tif math.Abs(fAy) <= math.Abs(fBy) {\n\t\t\tfTemp = fAx\n\t\t\tfAx += 2 * (fAx - fBx)\n\t\t\tif fAx < 0 {\n\t\t\t\tfAx = 0\n\t\t\t}\n\t\t\tfBx = fTemp\n\t\t\tfBy = fAy\n\t\t\tfAy = iterator.callBack(fAx)\n\t\t} else {\n\t\t\tfTemp = fBx\n\t\t\tfBx += 2 * (fBx - fAx)\n\t\t\tfAx = fTemp\n\t\t\tfAy = fBy\n\t\t\tfBy = iterator.callBack(fBx)\n\t\t}\n\t}\n\tif fAy == 0 || fBy == 0 {\n\t\treturn 0\n\t}\n\treturn inverseQuadraticInterpolation(iterator, fAx, fAy, fBx, fBy)\n}", "func Sin(value gcv.Value) gcv.Value {\n\tif value.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Sin(value.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Sin(value.Real()))\n}", "func Asinh(value gcv.Value) gcv.Value {\n\tif value.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(cmplx.Asinh(value.Complex()))\n\t}\n\treturn gcv.MakeValue(math.Asinh(value.Real()))\n}", "func (r *ImageRef) Invert() error {\n\tout, err := vipsInvert(r.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (r Ray) LineIntersectCircle(c Circ) (g, h Vec) {\n\t/*\n\t\t(X - c.C.X)^2 + (Y - c.C.Y)^2 = c.R*c.R\n\t\tr.V.Y*X - r.V.X*Y - r.V.Y*r.O.X + r.V.X*r.O.Y = 0\n\n\t\tX*X - 2*c.C.X*X + c.C.X*c.C.X + Y*Y - 2*c.C.Y*Y + c.C.Y*c.C.Y = c.R*c.R\n\t\t(r.V.X*Y + r.V.Y*r.O.X - r.V.X*r.O.Y) / r.V.Y = X\n\n\t\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\t\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\n\t\tX*X - 2*c.C.X*X + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t(r.V.X*Y + b) / r.V.Y = X\n\n\t\t(r.V.X*Y + b)^2 / r.V.Y*r.V.Y - 2*c.C.X * (r.V.X*Y + b) / r.V.Y + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t// * r.V.Y*r.V.Y\n\t\t(r.V.X*Y + b)^2 - 2*c.C.X*r.V.Y * (r.V.X*Y + b) + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// brackets\n\t\tr.V.X*r.V.X*Y*Y + 2*b*r.V.X*Y + b*b - 2*c.C.X*r.V.Y*r.V.X*Y - 2*c.C.X*r.V.Y*b + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// simplify\n\t\tY*Y * (r.V.X*r.V.X + r.V.Y*r.V.Y) + Y * (2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y) + b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y = 0\n\n\t\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\t\te := 2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y\n\t\tf := b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y\n\n\t\te := 2 * (b*r.V.X - r.V.Y * (c.C.X*r.V.X + c.C.Y*r.V.Y))\n\t*/\n\n\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\te := 2 * (b*r.V.X - r.V.Y*(c.C.X*r.V.X+c.C.Y*r.V.Y))\n\tf := b*b - r.V.Y*(2*c.C.X*b-a*r.V.Y)\n\n\tg.Y, h.Y = Polynomial(d, e, f)\n\tif r.V.Y == 0 {\n\t\tg.X, h.X = c.ProjectY(g.Y)\n\t} else {\n\t\tg.X = r.ProjectY(g.Y)\n\t\th.X = r.ProjectY(h.Y)\n\t}\n\n\treturn\n}", "func (r Rect) IntersectCircle(c Circle) Vec {\n\treturn c.IntersectRect(r).Scaled(-1)\n}", "func ModInv(a, mod int) int {\n\treturn ModPow(a, mod-2, mod)\n}", "func (o *Shape) InvMap(r, y []float64, x [][]float64) (err error) {\n\n\t// check\n\tif o.Gndim == 1 {\n\t\treturn chk.Err(\"Inverse mapping is not implemented in 1D\\n\")\n\t}\n\n\tvar δRnorm float64\n\te := make([]float64, o.Gndim) // residual\n\tδr := make([]float64, o.Gndim) // corrector\n\tr[0], r[1], r[2] = 0, 0, 0 // first trial\n\tit := 0\n\tderivs := true\n\tfor it = 0; it < INVMAP_NIT; it++ {\n\n\t\t// shape functions and derivatives\n\t\to.Func(o.S, o.DSdR, r, derivs, -1)\n\n\t\t// residual: e = y - x * S\n\t\tfor i := 0; i < o.Gndim; i++ {\n\t\t\te[i] = y[i]\n\t\t\tfor j := 0; j < o.Nverts; j++ {\n\t\t\t\te[i] -= x[i][j] * o.S[j]\n\t\t\t}\n\t\t}\n\n\t\t// Jmat == dxdR = x * dSdR;\n\t\tfor i := 0; i < len(x); i++ {\n\t\t\tfor j := 0; j < o.Gndim; j++ {\n\t\t\t\to.DxdR[i][j] = 0.0\n\t\t\t\tfor k := 0; k < o.Nverts; k++ {\n\t\t\t\t\to.DxdR[i][j] += x[i][k] * o.DSdR[k][j] // dxdR := x * dSdR\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Jimat == dRdx = Jmat.inverse();\n\t\to.J, err = la.MatInv(o.DRdx, o.DxdR, MINDET)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t// corrector: dR = Jimat * e\n\t\tfor i := 0; i < o.Gndim; i++ {\n\t\t\tδr[i] = 0.0\n\t\t\tfor j := 0; j < o.Gndim; j++ {\n\t\t\t\tδr[i] += o.DRdx[i][j] * e[j]\n\t\t\t}\n\t\t}\n\n\t\t// converged?\n\t\tδRnorm = 0.0\n\t\tfor i := 0; i < o.Gndim; i++ {\n\t\t\tr[i] += δr[i]\n\t\t\tδRnorm += δr[i] * δr[i]\n\t\t\t// fix r outside range\n\t\t\tif r[i] < -1.0 || r[i] > 1.0 {\n\t\t\t\tif math.Abs(r[i]-(-1.0)) < INVMAP_TOL {\n\t\t\t\t\tr[i] = -1.0\n\t\t\t\t}\n\t\t\t\tif math.Abs(r[i]-1.0) < INVMAP_TOL {\n\t\t\t\t\tr[i] = 1.0\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tif math.Sqrt(δRnorm) < INVMAP_TOL {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// check\n\tif it == INVMAP_NIT {\n\t\treturn\n\t}\n\treturn\n}", "func (v Vec3) Negate() Vec3 {\n\treturn Vec3{-v.X, -v.Y, -v.Z}\n}", "func (tx *PercentileTransform) inverse(v float64) float64 {\n\treturn 1 - math.Pow(tx.base, v)\n}", "func (c *Circle) IntersectCircle(c2 *Circle) *Intersection {\n\t// center same, return no intersection\n\tif c.center.Equal(c2.center) {\n\t\treturn NewIntersection()\n\t}\n\tdist := NewSegment(c.center, c2.center).Length()\n\t// tangent circles with tolerance\n\tif math.Abs(dist-c.r-c2.r) < configs.Tolerance {\n\t\t// vector from c to c2\n\t\tv := NewVector2DFromTwoPoints(c.center, c2.center)\n\t\tv.SetLength(c.r)\n\t\tpt := NewPoint(c.center.x+v.x, c.center.y+v.y)\n\t\treturn NewIntersection(pt)\n\t}\n\t// separated circles\n\tif dist > c.r+c2.r {\n\t\treturn NewIntersection()\n\t}\n\t// one circle inside another\n\tif math.Abs(c.r-c2.r) > dist {\n\t\treturn NewIntersection()\n\t}\n\t// Implements a nice looking formula\n\t//https://math.stackexchange.com/a/1367732\n\tR2 := dist * dist\n\tcoeff1 := (c.r*c.r - c2.r*c2.r) / R2\n\tcoeff2 := math.Sqrt(2*(c.r*c.r+c2.r*c2.r)/R2 - coeff1*coeff1 - 1)\n\tpt1x := (c.center.x+c2.center.x)/2 + (c2.center.x-c.center.x)*coeff1/2 + (c2.center.y-c.center.y)*coeff2/2\n\tpt2x := (c.center.x+c2.center.x)/2 + (c2.center.x-c.center.x)*coeff1/2 - (c2.center.y-c.center.y)*coeff2/2\n\tpt1y := (c.center.y+c2.center.y)/2 + (c2.center.y-c.center.y)*coeff1/2 - (c2.center.x-c.center.x)*coeff2/2\n\tpt2y := (c.center.y+c2.center.y)/2 + (c2.center.y-c.center.y)*coeff1/2 + (c2.center.x-c.center.x)*coeff2/2\n\treturn NewIntersection(NewPoint(pt1x, pt1y), NewPoint(pt2x, pt2y))\n}", "func (p *Plan) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(p.position)\n\tdefer eye.Add(p.position)\n\n\tif v.Z == 0 {\n\t\treturn 0\n\t}\n\treturn -float64(eye.Z) / v.Z\n}", "func Inf() complex128 {\n\tinf := math.Inf(1)\n\treturn complex(inf, inf)\n}", "func (m *Mask) GetInv() bool {\n\tif m == nil || m.Inv == nil {\n\t\treturn false\n\t}\n\treturn *m.Inv\n}", "func (l Line) IntersectCircle(c Circle) Vec {\n\t// Get the point on the line closest to the center of the circle.\n\tclosest := l.Closest(c.Center)\n\tcirToClosest := c.Center.To(closest)\n\n\tif cirToClosest.Len() >= c.Radius {\n\t\treturn ZV\n\t}\n\n\treturn cirToClosest.Scaled(cirToClosest.Len() - c.Radius)\n}", "func Inverse(m M) (M, error) {\n\tm = CopyMatrix(m)\n\n\tif m.Rows() != m.Cols() {\n\t\treturn m, errors.New(\"non-square matrices have no inverse\")\n\t}\n\n\tm, _ = Augment(m, Identity(m.r)) // ignore error because Identity will always match m row size\n\n\tm = Rref(m)\n\n\tfor c := 1; c <= m.Rows(); c++ { // must be square, so m.Rows() works here\n\t\tfound := false\n\t\tfor r := 1; r <= m.Rows(); r++ {\n\t\t\tif isLeadingEntry(m, r, c) && m.Get(r, c).Numerator() == 1 && m.Get(r, c).Denominator() == 1 { //Leading entry that is one\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif !found { //no leading entry that is one... not the identity, not invertible :(\n\t\t\treturn m, errors.New(\"matrix has no inverse\")\n\t\t}\n\t}\n\n\trm := M{r: m.r, c: m.r, values: make([]Frac, m.r*m.r)}\n\n\tfor r := 1; r <= rm.Rows(); r++ {\n\t\tfor c := 1; c <= rm.Cols(); c++ {\n\t\t\trm.Set(r, c, m.Get(r, rm.Cols()+c))\n\t\t}\n\t}\n\n\treturn rm, nil\n}", "func (i I) InvIdx(idx int) I {\n\tx := idx % i.X\n\tidx -= x\n\treturn I{x, idx / i.X}\n}", "func inverseQuadraticInterpolation(iterator calcInverseIterator, fAx, fAy, fBx, fBy float64) float64 {\n\tfYEps := 1.0e-307\n\tfXEps := 2.22045e-016\n\tfPx, fPy, fQx, fQy, fRx, fRy := fAx, fAy, fBx, fBy, fAx, fAy\n\tfSx := 0.5 * (fAx + fBx)\n\tbHasToInterpolate := true\n\tnCount := 0\n\tfor nCount < 500 && math.Abs(fRy) > fYEps && (fBx-fAx) > math.Max(math.Abs(fAx), math.Abs(fBx))*fXEps {\n\t\tif bHasToInterpolate {\n\t\t\tif fPy != fQy && fQy != fRy && fRy != fPy {\n\t\t\t\tfSx = fPx*fRy*fQy/(fRy-fPy)/(fQy-fPy) + fRx*fQy*fPy/(fQy-fRy)/(fPy-fRy) +\n\t\t\t\t\tfQx*fPy*fRy/(fPy-fQy)/(fRy-fQy)\n\t\t\t\tbHasToInterpolate = (fAx < fSx) && (fSx < fBx)\n\t\t\t} else {\n\t\t\t\tbHasToInterpolate = false\n\t\t\t}\n\t\t}\n\t\tif !bHasToInterpolate {\n\t\t\tfSx = 0.5 * (fAx + fBx)\n\t\t\tfQx, fQy = fBx, fBy\n\t\t\tbHasToInterpolate = true\n\t\t}\n\t\tfPx, fQx, fRx, fPy, fQy = fQx, fRx, fSx, fQy, fRy\n\t\tfRy = iterator.callBack(fSx)\n\t\tif hasChangeOfSign(fAy, fRy) {\n\t\t\tfBx, fBy = fRx, fRy\n\t\t} else {\n\t\t\tfAx, fAy = fRx, fRy\n\t\t}\n\t\tbHasToInterpolate = bHasToInterpolate && (math.Abs(fRy)*2 <= math.Abs(fQy))\n\t\tnCount++\n\t}\n\treturn fRx\n}", "func (cv *Canvas) Ellipse(x, y, radiusX, radiusY, rotation, startAngle, endAngle float64, anticlockwise bool) {\n\ttf := cv.tf(vec{x, y})\n\tax, ay := math.Sincos(startAngle)\n\tstartAngle2 := vec{ay, ax}.mulMat2(cv.state.transform.mat2()).atan2()\n\tendAngle2 := startAngle2 + (endAngle - startAngle)\n\tcv.path.Ellipse(tf[0], tf[1], radiusX, radiusY, rotation, startAngle2, endAngle2, anticlockwise)\n}", "func (curve p256Curve) Inverse(k *big.Int) *big.Int {\r\n\tif k.Sign() < 0 {\r\n\t\t// This should never happen.\r\n\t\tk = new(big.Int).Neg(k)\r\n\t}\r\n\r\n\tif k.Cmp(p256.N) >= 0 {\r\n\t\t// This should never happen.\r\n\t\tk = new(big.Int).Mod(k, p256.N)\r\n\t}\r\n\r\n\t// table will store precomputed powers of x.\r\n\tvar table [4 * 10]uint64\r\n\tvar (\r\n\t\t_1 = table[4*0 : 4*1]\r\n\t\t_11 = table[4*1 : 4*2]\r\n\t\t_101 = table[4*2 : 4*3]\r\n\t\t_111 = table[4*3 : 4*4]\r\n\t\t_1111 = table[4*4 : 4*5]\r\n\t\t_10101 = table[4*5 : 4*6]\r\n\t\t_101111 = table[4*6 : 4*7]\r\n\t\tx = table[4*7 : 4*8]\r\n\t\tt = table[4*8 : 4*9]\r\n\t\tm = table[4*9 : 4*10]\r\n\t)\r\n\r\n\tfromBig(x[:], k)\r\n\t// This code operates in the Montgomery domain where R = 2^256 mod n\r\n\t// and n is the order of the scalar field. (See initP256 for the\r\n\t// value.) Elements in the Montgomery domain take the form a×R and\r\n\t// multiplication of x and y in the calculates (x × y × R^-1) mod n. RR\r\n\t// is R×R mod n thus the Montgomery multiplication x and RR gives x×R,\r\n\t// i.e. converts x into the Montgomery domain.\r\n\t// Window values borrowed from https://briansmith.org/ecc-inversion-addition-chains-01#p256_scalar_inversion\r\n\tRR := []uint64{0x901192af7c114f20, 0x3464504ade6fa2fa, 0x620fc84c3affe0d4, 0x1eb5e412a22b3d3b}\r\n\r\n\tp256OrdMul(_1, x, RR) // _1 , 2^0\r\n\tp256OrdSqr(m, _1, 1) // _10, 2^1\r\n\tp256OrdMul(_11, m, _1) // _11, 2^1 + 2^0\r\n\tp256OrdMul(_101, m, _11) // _101, 2^2 + 2^0\r\n\tp256OrdMul(_111, m, _101) // _111, 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(x, _101, 1) // _1010, 2^3 + 2^1\r\n\tp256OrdMul(_1111, _101, x) // _1111, 2^3 + 2^2 + 2^1 + 2^0\r\n\r\n\tp256OrdSqr(t, x, 1) // _10100, 2^4 + 2^2\r\n\tp256OrdMul(_10101, t, _1) // _10101, 2^4 + 2^2 + 2^0\r\n\tp256OrdSqr(x, _10101, 1) // _101010, 2^5 + 2^3 + 2^1\r\n\tp256OrdMul(_101111, _101, x) // _101111, 2^5 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdMul(x, _10101, x) // _111111 = x6, 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(t, x, 2) // _11111100, 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2\r\n\r\n\tp256OrdMul(m, t, m) // _11111110 = x8, , 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1\r\n\tp256OrdMul(t, t, _11) // _11111111 = x8, , 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\tp256OrdSqr(x, t, 8) // _ff00, 2^15 + 2^14 + 2^13 + 2^12 + 2^11 + 2^10 + 2^9 + 2^8\r\n\tp256OrdMul(m, x, m) // _fffe\r\n\tp256OrdMul(x, x, t) // _ffff = x16, 2^15 + 2^14 + 2^13 + 2^12 + 2^11 + 2^10 + 2^9 + 2^8 + 2^7 + 2^6 + 2^5 + 2^4 + 2^3 + 2^2 + 2^1 + 2^0\r\n\r\n\tp256OrdSqr(t, x, 16) // _ffff0000, 2^31 + 2^30 + 2^29 + 2^28 + 2^27 + 2^26 + 2^25 + 2^24 + 2^23 + 2^22 + 2^21 + 2^20 + 2^19 + 2^18 + 2^17 + 2^16\r\n\tp256OrdMul(m, t, m) // _fffffffe\r\n\tp256OrdMul(t, t, x) // _ffffffff = x32\r\n\r\n\tp256OrdSqr(x, m, 32) // _fffffffe00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffff\r\n\tp256OrdSqr(x, x, 32) // _fffffffeffffffff00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffffffffffff\r\n\tp256OrdSqr(x, x, 32) // _fffffffeffffffffffffffff00000000\r\n\tp256OrdMul(x, x, t) // _fffffffeffffffffffffffffffffffff\r\n\r\n\tsqrs := []uint8{\r\n\t\t4, 3, 11, 5, 3, 5, 1,\r\n\t\t3, 7, 5, 9, 7, 5, 5,\r\n\t\t4, 5, 2, 2, 7, 3, 5,\r\n\t\t5, 6, 2, 6, 3, 5,\r\n\t}\r\n\tmuls := [][]uint64{\r\n\t\t_111, _1, _1111, _1111, _101, _10101, _1,\r\n\t\t_1, _111, _11, _101, _10101, _10101, _111,\r\n\t\t_111, _1111, _11, _1, _1, _1, _111,\r\n\t\t_111, _10101, _1, _1, _1, _1}\r\n\r\n\tfor i, s := range sqrs {\r\n\t\tp256OrdSqr(x, x, int(s))\r\n\t\tp256OrdMul(x, x, muls[i])\r\n\t}\r\n\r\n\t// Multiplying by one in the Montgomery domain converts a Montgomery\r\n\t// value out of the domain.\r\n\tone := []uint64{1, 0, 0, 0}\r\n\tp256OrdMul(x, x, one)\r\n\r\n\txOut := make([]byte, 32)\r\n\tp256LittleToBig(xOut, x)\r\n\treturn new(big.Int).SetBytes(xOut)\r\n}", "func Sin(x complex128) complex128 {\n\tswitch re, im := real(x), imag(x); {\n\tcase im == 0 && (math.IsInf(re, 0) || math.IsNaN(re)):\n\t\treturn complex(math.NaN(), im)\n\tcase math.IsInf(im, 0):\n\t\tswitch {\n\t\tcase re == 0:\n\t\t\treturn x\n\t\tcase math.IsInf(re, 0) || math.IsNaN(re):\n\t\t\treturn complex(math.NaN(), im)\n\t\t}\n\tcase re == 0 && math.IsNaN(im):\n\t\treturn x\n\t}\n\ts, c := math.Sincos(real(x))\n\tsh, ch := sinhcosh(imag(x))\n\treturn complex(s*ch, c*sh)\n}", "func (v Vec3) Negate() Vec3 {\n\treturn Vec3{-v[0], -v[1], -v[2]}\n}", "func (o *Shape) Extrapolator(E [][]float64, ips []Ipoint) (err error) {\n\tla.MatFill(E, 0)\n\tnip := len(ips)\n\tN := o.GetShapeMatAtIps(ips)\n\tif nip < o.Nverts {\n\t\tξ := o.GetNodesNatCoordsMat()\n\t\tξh := o.GetIpsNatCoordsMat(ips)\n\t\tξhi := la.MatAlloc(o.Gndim+1, nip)\n\t\tNi := la.MatAlloc(o.Nverts, nip)\n\t\terr = la.MatInvG(Ni, N, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = la.MatInvG(ξhi, ξh, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tξhξhI := la.MatAlloc(nip, nip) // ξh * inv(ξh)\n\t\tfor k := 0; k < o.Gndim+1; k++ {\n\t\t\tfor j := 0; j < nip; j++ {\n\t\t\t\tfor i := 0; i < nip; i++ {\n\t\t\t\t\tξhξhI[i][j] += ξh[i][k] * ξhi[k][j]\n\t\t\t\t}\n\t\t\t\tfor i := 0; i < o.Nverts; i++ {\n\t\t\t\t\tE[i][j] += ξ[i][k] * ξhi[k][j] // ξ * inv(ξh)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tfor i := 0; i < o.Nverts; i++ {\n\t\t\tfor j := 0; j < nip; j++ {\n\t\t\t\tfor k := 0; k < nip; k++ {\n\t\t\t\t\tI_kj := 0.0\n\t\t\t\t\tif j == k {\n\t\t\t\t\t\tI_kj = 1.0\n\t\t\t\t\t}\n\t\t\t\t\tE[i][j] += Ni[i][k] * (I_kj - ξhξhI[k][j])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\terr = la.MatInvG(E, N, 1e-10)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t}\n\treturn\n}", "func AbsCircle(cont *fyne.Container, x, y, r int, color color.RGBA) {\n\tfx, fy, fr := float32(x), float32(y), float32(r)\n\tp1 := fyne.Position{X: fx - fr, Y: fy - fr}\n\tp2 := fyne.Position{X: fx + fr, Y: fy + fr}\n\tcont.AddObject(&canvas.Circle{FillColor: color, Position1: p1, Position2: p2})\n}", "func (d Decimal) Cos() Decimal {\n\n\tPI4A := NewFromFloat(7.85398125648498535156e-1) // 0x3fe921fb40000000, Pi/4 split into three parts\n\tPI4B := NewFromFloat(3.77489470793079817668e-8) // 0x3e64442d00000000,\n\tPI4C := NewFromFloat(2.69515142907905952645e-15) // 0x3ce8469898cc5170,\n\tM4PI := NewFromFloat(1.273239544735162542821171882678754627704620361328125) // 4/pi\n\n\t// make argument positive\n\tsign := false\n\tif d.LessThan(NewFromFloat(0.0)) {\n\t\td = d.Neg()\n\t}\n\n\tj := d.Mul(M4PI).IntPart() // integer part of x/(Pi/4), as integer for tests on the phase angle\n\ty := NewFromFloat(float64(j)) // integer part of x/(Pi/4), as float\n\n\t// map zeros to origin\n\tif j&1 == 1 {\n\t\tj++\n\t\ty = y.Add(NewFromFloat(1.0))\n\t}\n\tj &= 7 // octant modulo 2Pi radians (360 degrees)\n\t// reflect in x axis\n\tif j > 3 {\n\t\tsign = !sign\n\t\tj -= 4\n\t}\n\tif j > 1 {\n\t\tsign = !sign\n\t}\n\n\tz := d.Sub(y.Mul(PI4A)).Sub(y.Mul(PI4B)).Sub(y.Mul(PI4C)) // Extended precision modular arithmetic\n\tzz := z.Mul(z)\n\n\tif j == 1 || j == 2 {\n\t\ty = z.Add(z.Mul(zz).Mul(_sin[0].Mul(zz).Add(_sin[1]).Mul(zz).Add(_sin[2]).Mul(zz).Add(_sin[3]).Mul(zz).Add(_sin[4]).Mul(zz).Add(_sin[5])))\n\t} else {\n\t\tw := zz.Mul(zz).Mul(_cos[0].Mul(zz).Add(_cos[1]).Mul(zz).Add(_cos[2]).Mul(zz).Add(_cos[3]).Mul(zz).Add(_cos[4]).Mul(zz).Add(_cos[5]))\n\t\ty = NewFromFloat(1.0).Sub(NewFromFloat(0.5).Mul(zz)).Add(w)\n\t}\n\tif sign {\n\t\ty = y.Neg()\n\t}\n\treturn y\n}", "func (e *Engine) AddPairInv(g1 *PointG1, g2 *PointG2) *Engine {\n\tng1 := e.G1.New().Set(g1)\n\te.G1.Neg(ng1, g1)\n\te.AddPair(ng1, g2)\n\treturn e\n}", "func (self *State)Sin(a any)any{\n self.IncOperations(self.coeff[\"sin\"]+self.off[\"sin\"])\n return wrap1(a,math.Sin)\n}", "func Sin(d decimal.Decimal) decimal.Decimal {\n\trad, _ := d.Mul(decPi).Div(dec180).Float64()\n\treturn decimal.NewFromFloat(math.Sin(rad))\n}", "func (s *Sphere) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(s.position)\n\tdefer eye.Add(s.position)\n\n\tvar (\n\t\ta = v.X*v.X + v.Y*v.Y + v.Z*v.Z\n\t\tb = 2*float64(eye.X)*v.X + float64(eye.Y)*v.Y + float64(eye.Z)*v.Z\n\t\tc = float64(eye.X*eye.X + eye.Y*eye.Y + eye.Z*eye.Z - s.R*s.R)\n\t)\n\treturn utils.SecondDegree(a, b, c)\n}", "func Inverse(arg interface{}) Value {\n\treturn Reverse(arg)\n}", "func inverseStart(sbet1, cbet1, sbet2, cbet2, lam12, _salp2, _calp2 float64, C1a, C2a []float64) (sig12, salp1, calp1, salp2, calp2 float64) {\n\n\tsig12 = -1.\n\tsalp2, calp2 = _salp2, _calp2\n\t// bet12 = bet2 - bet1 in [0, pi); bet12a = bet2 + bet1 in (-pi, 0]\n\tsbet12 := sbet2*cbet1 - cbet2*sbet1\n\tcbet12 := cbet2*cbet1 + sbet2*sbet1\n\tsbet12a := sbet2*cbet1 + cbet2*sbet1\n\n\tshortline := cbet12 >= 0 && sbet12 < 0.5 && lam12 <= math.Pi/6\n\n\tomg12 := lam12\n\tif shortline {\n\t\tomg12 = lam12 / math.Sqrt(1-_e2*cbet1*cbet1)\n\t}\n\tsomg12, comg12 := math.Sincos(omg12)\n\n\tsalp1 = cbet2 * somg12\n\tif comg12 >= 0 {\n\t\tcalp1 = sbet12 + cbet2*sbet1*somg12*somg12/(1.+comg12)\n\t} else {\n\t\tcalp1 = sbet12a - cbet2*sbet1*somg12*somg12/(1.-comg12)\n\t}\n\n\tssig12 := math.Hypot(salp1, calp1)\n\tcsig12 := sbet1*sbet2 + cbet1*cbet2*comg12\n\n\tif shortline && ssig12 < _etol2 {\n\t\t// really short lines\n\t\tsalp2 = cbet1 * somg12\n\t\tcalp2 = sbet12 - cbet1*sbet2*somg12*somg12/(1+comg12)\n\t\tsalp2, calp2 = sinCosNorm(salp2, calp2)\n\t\t// Set return value\n\t\tsig12 = math.Atan2(ssig12, csig12)\n\t} else if csig12 >= 0 || ssig12 >= 3*math.Abs(_f)*math.Pi*cbet1*cbet1 {\n\t\t// Nothing to do, zeroth order spherical approximation is OK\n\t} else {\n\t\t// Scale lam12 and bet2 to x, y coordinate system where antipodal point\n\t\t// is at origin and singular point is at y = 0, x = -1.\n\t\tvar x, y, lamscale, betscale float64\n\t\tif _f >= 0 { // In fact f == 0 does not get here\n\t\t\t// x = dlong, y = dlat\n\t\t\tk2 := sbet1 * sbet1 * _ep2\n\t\t\teps := k2 / (2*(1+math.Sqrt(1+k2)) + k2)\n\t\t\tlamscale = _f * cbet1 * a3f(eps) * math.Pi\n\t\t\tbetscale = lamscale * cbet1\n\n\t\t\tx = (lam12 - math.Pi) / lamscale\n\t\t\ty = sbet12a / betscale\n\t\t} else { // _f < 0\n\t\t\t// x = dlat, y = dlong\n\t\t\tcbet12a := cbet2*cbet1 - sbet2*sbet1\n\t\t\tbet12a := math.Atan2(sbet12a, cbet12a)\n\n\t\t\t// In the case of lon12 = 180, this repeats a calculation made in\n\t\t\t// Inverse.\n\t\t\t_, m12a, m0 := lengths(_n, math.Pi+bet12a, sbet1, -cbet1, sbet2, cbet2, cbet1, cbet2, C1a, C2a)\n\n\t\t\tx = -1 + m12a/(_f1*cbet1*cbet2*m0*math.Pi)\n\t\t\tif x < -0.01 {\n\t\t\t\tbetscale = sbet12a / x\n\t\t\t} else {\n\t\t\t\tbetscale = -_f * cbet1 * cbet1 * math.Pi\n\t\t\t}\n\t\t\tlamscale = betscale / cbet1\n\t\t\ty = (lam12 - math.Pi) / lamscale\n\t\t}\n\n\t\tif y > -_tol1 && x > -1-_xthresh {\n\t\t\t// strip near cut\n\t\t\tif _f >= 0 {\n\t\t\t\tsalp1 = min(1, -x)\n\t\t\t\tcalp1 = -math.Sqrt(1 - salp1*salp1)\n\t\t\t} else {\n\t\t\t\tif x > -_tol1 {\n\t\t\t\t\tcalp1 = max(0, x)\n\t\t\t\t} else {\n\t\t\t\t\tcalp1 = max(-1, x)\n\t\t\t\t}\n\t\t\t\tsalp1 = math.Sqrt(1 - calp1*calp1)\n\t\t\t}\n\t\t} else {\n\t\t\tk := astroid(x, y)\n\n\t\t\tomg12a := lamscale\n\t\t\tif _f >= 0 {\n\t\t\t\tomg12a *= -x * k / (1 + k)\n\t\t\t} else {\n\t\t\t\tomg12a *= -y * (1 + k) / k\n\t\t\t}\n\n\t\t\tsomg12, comg12 := math.Sincos(omg12a)\n\t\t\tcomg12 = -comg12\n\n\t\t\t// Update spherical estimate of alp1 using omg12 instead of lam12\n\t\t\tsalp1 = cbet2 * somg12\n\t\t\tcalp1 = sbet12a - cbet2*sbet1*somg12*somg12/(1-comg12)\n\t\t}\n\t}\n\n\tsalp1, calp1 = sinCosNorm(salp1, calp1)\n\treturn\n}", "func (z *E12) InverseUnitary(x *E12) *E12 {\n\treturn z.Conjugate(x)\n}", "func Invert() Filter {\n\treturn &colorchanFilter{\n\t\tfn: func(x float32) float32 {\n\t\t\treturn 1 - x\n\t\t},\n\t\tlut: false,\n\t}\n}", "func InvSqrt(x float32) float32 {\n\txhalf := float32(0.5) * x\n\ti := *(*int32)(unsafe.Pointer(&x))\n\ti = int32(0x5f3759df) - int32(i>>1)\n\tx = *(*float32)(unsafe.Pointer(&i))\n\tx = x * (1.5 - (xhalf * x * x))\n\treturn x\n}", "func InvSqrt(x float32) float32 {\n\txhalf := float32(0.5) * x\n\ti := *(*int32)(unsafe.Pointer(&x))\n\ti = int32(0x5f3759df) - int32(i>>1)\n\tx = *(*float32)(unsafe.Pointer(&i))\n\tx = x * (1.5 - (xhalf * x * x))\n\treturn x\n}", "func Invert(scope *Scope, x tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"Invert\",\n\t\tInput: []tf.Input{\n\t\t\tx,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func ForCircle(c v.Vect, r f.Float) AABB {\n\treturn AABB{c.X - r, c.Y - r, c.X + r, c.Y + r}\n}", "func Asin(arg float64) float64 {\n\treturn math.Asin(arg)\n}", "func (q Quat) Inverse() Quat {\n\treturn Quat{-q.W, q.X, q.Y, q.Z}\n}", "func (z *E6) Inverse(x *E6) *E6 {\n\t// Algorithm 17 from https://eprint.iacr.org/2010/354.pdf\n\t// step 9 is wrong in the paper it's t1-t4\n\tvar t0, t1, t2, t3, t4, t5, t6, c0, c1, c2, d1, d2 E2\n\tt0.Square(&x.B0)\n\tt1.Square(&x.B1)\n\tt2.Square(&x.B2)\n\tt3.Mul(&x.B0, &x.B1)\n\tt4.Mul(&x.B0, &x.B2)\n\tt5.Mul(&x.B1, &x.B2)\n\tc0.MulByNonResidue(&t5).Neg(&c0).Add(&c0, &t0)\n\tc1.MulByNonResidue(&t2).Sub(&c1, &t3)\n\tc2.Sub(&t1, &t4)\n\tt6.Mul(&x.B0, &c0)\n\td1.Mul(&x.B2, &c1)\n\td2.Mul(&x.B1, &c2)\n\td1.Add(&d1, &d2).MulByNonResidue(&d1)\n\tt6.Add(&t6, &d1)\n\tt6.Inverse(&t6)\n\tz.B0.Mul(&c0, &t6)\n\tz.B1.Mul(&c1, &t6)\n\tz.B2.Mul(&c2, &t6)\n\n\treturn z\n}", "func get_arc_center(x1, y1, x2, y2, fa, fs, rx, ry, sin_phi, cos_phi float64) []float64 {\n\t// Step 1.\n\t//\n\t// Moving an ellipse so origin will be the middlepoint between our two\n\t// points. After that, rotate it to line up ellipse axes with coordinate\n\t// axes.\n\t//\n\tx1p := cos_phi*(x1-x2)/2 + sin_phi*(y1-y2)/2\n\ty1p := -sin_phi*(x1-x2)/2 + cos_phi*(y1-y2)/2\n\n\trx_sq := rx * rx\n\try_sq := ry * ry\n\tx1p_sq := x1p * x1p\n\ty1p_sq := y1p * y1p\n\n\t// Step 2.\n\t//\n\t// Compute coordinates of the centre of this ellipse (cx', cy')\n\t// in the new coordinate system.\n\t//\n\tradicant := (rx_sq * ry_sq) - (rx_sq * y1p_sq) - (ry_sq * x1p_sq)\n\n\tif radicant < 0 {\n\t\t// due to rounding errors it might be e.g. -1.3877787807814457e-17\n\t\tradicant = 0\n\t}\n\n\tradicant /= (rx_sq * y1p_sq) + (ry_sq * x1p_sq)\n\tsign := 1.0\n\tif fa == fs {\n\t\tsign = -1.0\n\t}\n\tradicant = math.Sqrt(radicant) * sign\n\n\tcxp := radicant * rx / ry * y1p\n\tcyp := radicant * -ry / rx * x1p\n\n\t// Step 3.\n\t//\n\t// Transform back to get centre coordinates (cx, cy) in the original\n\t// coordinate system.\n\t//\n\tcx := cos_phi*cxp - sin_phi*cyp + (x1+x2)/2\n\tcy := sin_phi*cxp + cos_phi*cyp + (y1+y2)/2\n\n\t// Step 4.\n\t//\n\t// Compute angles (theta1, delta_theta).\n\t//\n\tv1x := (x1p - cxp) / rx\n\tv1y := (y1p - cyp) / ry\n\tv2x := (-x1p - cxp) / rx\n\tv2y := (-y1p - cyp) / ry\n\n\ttheta1 := unit_vector_angle(1, 0, v1x, v1y)\n\tdelta_theta := unit_vector_angle(v1x, v1y, v2x, v2y)\n\n\tif fs == 0 && delta_theta > 0 {\n\t\tdelta_theta -= TAU\n\t}\n\tif fs == 1 && delta_theta < 0 {\n\t\tdelta_theta += TAU\n\t}\n\n\treturn []float64{cx, cy, theta1, delta_theta}\n}", "func MatInv(ai, a [][]float64, tol float64) (det float64, err error) {\n\tif len(a) < 1 {\n\t\treturn 0, chk.Err(_matinv_err1)\n\t}\n\tm, n := len(a), len(a[0])\n\tswitch {\n\tcase m == 1 && n == 1:\n\t\tdet = a[0][0]\n\t\tif math.Abs(det) < tol {\n\t\t\treturn 0, chk.Err(_matinv_err2, m, n, det, tol)\n\t\t}\n\t\tai[0][0] = 1.0 / det\n\tcase m == 2 && n == 2:\n\t\tdet = a[0][0]*a[1][1] - a[0][1]*a[1][0]\n\t\tif math.Abs(det) < tol {\n\t\t\treturn 0, chk.Err(_matinv_err2, m, n, det, tol)\n\t\t}\n\t\tai[0][0] = a[1][1] / det\n\t\tai[0][1] = -a[0][1] / det\n\t\tai[1][0] = -a[1][0] / det\n\t\tai[1][1] = a[0][0] / det\n\tcase m == 3 && n == 3:\n\t\tdet = a[0][0]*(a[1][1]*a[2][2]-a[1][2]*a[2][1]) - a[0][1]*(a[1][0]*a[2][2]-a[1][2]*a[2][0]) + a[0][2]*(a[1][0]*a[2][1]-a[1][1]*a[2][0])\n\t\tif math.Abs(det) < tol {\n\t\t\treturn 0, chk.Err(_matinv_err2, m, n, det, tol)\n\t\t}\n\n\t\tai[0][0] = (a[1][1]*a[2][2] - a[1][2]*a[2][1]) / det\n\t\tai[0][1] = (a[0][2]*a[2][1] - a[0][1]*a[2][2]) / det\n\t\tai[0][2] = (a[0][1]*a[1][2] - a[0][2]*a[1][1]) / det\n\n\t\tai[1][0] = (a[1][2]*a[2][0] - a[1][0]*a[2][2]) / det\n\t\tai[1][1] = (a[0][0]*a[2][2] - a[0][2]*a[2][0]) / det\n\t\tai[1][2] = (a[0][2]*a[1][0] - a[0][0]*a[1][2]) / det\n\n\t\tai[2][0] = (a[1][0]*a[2][1] - a[1][1]*a[2][0]) / det\n\t\tai[2][1] = (a[0][1]*a[2][0] - a[0][0]*a[2][1]) / det\n\t\tai[2][2] = (a[0][0]*a[1][1] - a[0][1]*a[1][0]) / det\n\tdefault:\n\t\treturn 0, chk.Err(_matinv_err3, m, n)\n\t}\n\treturn\n}", "func Nuttal(input VectorComplex) VectorComplex {\n\tvh := input.Copy()\n\ttheta := 2.0 * math.Pi / float64(len(vh)-1)\n\ta0 := complex(0.355768, 0.0)\n\ta1 := complex(0.487396, 0.0)\n\ta2 := complex(0.144232, 0.0)\n\ta3 := complex(0.012604, 0.0)\n\n\tfor i := 0; i < len(vh); i++ {\n\t\tx := complex(theta*float64(i), 0)\n\t\tvh[i] *= a0 - a1*cmplx.Cos(x) + a2*cmplx.Cos(2.0*x) + a3*cmplx.Cos(3.0*x)\n\t}\n\treturn vh\n}", "func (o *Orbit) Elements() (a, e, i, Ω, ω, ν, λ, tildeω, u float64) {\n\tif o.hashValid() {\n\t\treturn o.ccha, o.cche, o.cchi, o.cchΩ, o.cchω, o.cchν, o.cchλ, o.cchtildeω, o.cchu\n\t}\n\t// Algorithm from Vallado, 4th edition, page 113 (RV2COE).\n\thVec := Cross(o.rVec, o.vVec)\n\tn := Cross([]float64{0, 0, 1}, hVec)\n\tv := Norm(o.vVec)\n\tr := Norm(o.rVec)\n\tξ := (v*v)/2 - o.Origin.μ/r\n\ta = -o.Origin.μ / (2 * ξ)\n\teVec := make([]float64, 3, 3)\n\tfor i := 0; i < 3; i++ {\n\t\teVec[i] = ((v*v-o.Origin.μ/r)*o.rVec[i] - Dot(o.rVec, o.vVec)*o.vVec[i]) / o.Origin.μ\n\t}\n\te = Norm(eVec)\n\t// Prevent nil values for e\n\tif e < eccentricityε {\n\t\te = eccentricityε\n\t}\n\ti = math.Acos(hVec[2] / Norm(hVec))\n\tif i < angleε {\n\t\ti = angleε\n\t}\n\tω = math.Acos(Dot(n, eVec) / (Norm(n) * e))\n\tif math.IsNaN(ω) {\n\t\tω = 0\n\t}\n\tif eVec[2] < 0 {\n\t\tω = 2*math.Pi - ω\n\t}\n\tΩ = math.Acos(n[0] / Norm(n))\n\tif math.IsNaN(Ω) {\n\t\tΩ = angleε\n\t}\n\tif n[1] < 0 {\n\t\tΩ = 2*math.Pi - Ω\n\t}\n\tcosν := Dot(eVec, o.rVec) / (e * r)\n\tif abscosν := math.Abs(cosν); abscosν > 1 && floats.EqualWithinAbs(abscosν, 1, 1e-12) {\n\t\t// Welcome to the edge case which took about 1.5 hours of my time.\n\t\tcosν = Sign(cosν) // GTFO NaN!\n\t}\n\tν = math.Acos(cosν)\n\tif math.IsNaN(ν) {\n\t\tν = 0\n\t}\n\tif Dot(o.rVec, o.vVec) < 0 {\n\t\tν = 2*math.Pi - ν\n\t}\n\t// Fix rounding errors.\n\ti = math.Mod(i, 2*math.Pi)\n\tΩ = math.Mod(Ω, 2*math.Pi)\n\tω = math.Mod(ω, 2*math.Pi)\n\tν = math.Mod(ν, 2*math.Pi)\n\tλ = math.Mod(ω+Ω+ν, 2*math.Pi)\n\ttildeω = math.Mod(ω+Ω, 2*math.Pi)\n\tif e < eccentricityε {\n\t\t// Circular\n\t\tu = math.Acos(Dot(n, o.rVec) / (Norm(n) * r))\n\t} else {\n\t\tu = math.Mod(ν+ω, 2*math.Pi)\n\t}\n\t// Cache values\n\to.ccha = a\n\to.cche = e\n\to.cchi = i\n\to.cchΩ = Ω\n\to.cchω = ω\n\to.cchν = ν\n\to.cchλ = λ\n\to.cchtildeω = tildeω\n\to.cchu = u\n\to.computeHash()\n\treturn\n}", "func (self *Graphics) ArcI(args ...interface{}) *Graphics{\n return &Graphics{self.Object.Call(\"arc\", args)}\n}", "func CircOut(t, b, c, d float64) float64 {\n\tif t > d {\n\t\treturn c\n\t}\n\n\tt /= d\n\tt--\n\n\treturn c*math.Sqrt(1-t*t) + b\n}", "func (g *Graph) Sin(x Node) Node {\n\treturn g.NewOperator(fn.NewSin(x), x)\n}", "func (fn *formulaFuncs) BETAdotINV(argsList *list.List) formulaArg {\n\treturn fn.betainv(\"BETA.INV\", argsList)\n}", "func C(center Vec, radius float64) Circle {\n\treturn Circle{\n\t\tCenter: center,\n\t\tRadius: radius,\n\t}\n}", "func (e *E6) Inverse(cs *frontend.ConstraintSystem, e1 *E6, ext Extension) *E6 {\n\n\tvar t [7]E2\n\tvar c [3]E2\n\tvar buf E2\n\n\tt[0].Mul(cs, &e1.B0, &e1.B0, ext)\n\tt[1].Mul(cs, &e1.B1, &e1.B1, ext)\n\tt[2].Mul(cs, &e1.B2, &e1.B2, ext)\n\tt[3].Mul(cs, &e1.B0, &e1.B1, ext)\n\tt[4].Mul(cs, &e1.B0, &e1.B2, ext)\n\tt[5].Mul(cs, &e1.B1, &e1.B2, ext)\n\n\tc[0].MulByIm(cs, &t[5], ext)\n\n\tc[0].Neg(cs, &c[0]).Add(cs, &c[0], &t[0])\n\n\tc[1].MulByIm(cs, &t[2], ext)\n\n\tc[1].Sub(cs, &c[1], &t[3])\n\tc[2].Sub(cs, &t[1], &t[4])\n\tt[6].Mul(cs, &e1.B2, &c[1], ext)\n\tbuf.Mul(cs, &e1.B1, &c[2], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].MulByIm(cs, &t[6], ext)\n\n\tbuf.Mul(cs, &e1.B0, &c[0], ext)\n\tt[6].Add(cs, &t[6], &buf)\n\n\tt[6].Inverse(cs, &t[6], ext)\n\te.B0.Mul(cs, &c[0], &t[6], ext)\n\te.B1.Mul(cs, &c[1], &t[6], ext)\n\te.B2.Mul(cs, &c[2], &t[6], ext)\n\n\treturn e\n\n}", "func V(x, y f.Float) Vect { return Vect{x, y} }", "func Invert(c color.Color) color.Color {\n\t// FIXME: safe colors\n\tr, g, b, a := c.RGBA()\n\tcc := color.RGBA64{\n\t\tR: uint16(65535 - r),\n\t\tG: uint16(65535 - g),\n\t\tB: uint16(65535 - b),\n\t\tA: uint16(a),\n\t}\n\treturn cc\n}", "func ThresholdInv(src, dst *image.Gray, level uint8) error {\n\tif src.Bounds() != dst.Bounds() {\n\t\treturn errors.New(\"src and dst should have the same bounds\")\n\t}\n\n\tfor y := src.Bounds().Min.Y; y < src.Bounds().Max.Y; y++ {\n\t\tfor x := src.Bounds().Min.X; x < src.Bounds().Max.X; x++ {\n\t\t\tif src.GrayAt(x, y).Y > level {\n\t\t\t\tdst.SetGray(x, y, Black)\n\t\t\t} else {\n\t\t\t\tdst.SetGray(x, y, White)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.76996166", "0.6200599", "0.6169844", "0.6041996", "0.6020256", "0.6012203", "0.60035485", "0.592195", "0.59038144", "0.5831999", "0.5749896", "0.57390594", "0.5698347", "0.5594108", "0.55541444", "0.55193657", "0.55168456", "0.5473326", "0.5462184", "0.5440428", "0.54085994", "0.5386049", "0.5341476", "0.52941394", "0.52866024", "0.52785784", "0.5264056", "0.51391417", "0.50978434", "0.5002852", "0.4975933", "0.49627012", "0.4944928", "0.49411696", "0.49176547", "0.4909383", "0.48468703", "0.4823172", "0.48203108", "0.4817472", "0.4816839", "0.48167667", "0.48150605", "0.4797096", "0.47574136", "0.47531968", "0.47509697", "0.4723471", "0.471306", "0.46981078", "0.46961606", "0.46912932", "0.46773517", "0.46708614", "0.46460584", "0.46254623", "0.46110567", "0.4610574", "0.4589657", "0.45870104", "0.45619166", "0.4559922", "0.455684", "0.45530528", "0.45527098", "0.45524535", "0.45155752", "0.45025313", "0.44965276", "0.44933715", "0.4493167", "0.4488771", "0.44780704", "0.4471591", "0.44680274", "0.44575676", "0.44519565", "0.44482264", "0.44331452", "0.44276565", "0.44274044", "0.44274044", "0.44209373", "0.44200996", "0.44121844", "0.44019455", "0.43926233", "0.43906572", "0.43894172", "0.4385137", "0.43840635", "0.43760023", "0.4368899", "0.43665227", "0.43625894", "0.43570203", "0.43565702", "0.4347534", "0.43466434", "0.4340363" ]
0.7494496
1
LFT computes a Linear fractional transformation (
func LFT(p Point, m m2c.Matrix) Point { return Point{m.A*p.Z + m.B*p.W, m.C*p.Z + m.D*p.W} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Rdft(n int, isgn int, a []float64, ip []int, w []float64) {\n\tvar nw, nc int\n\tvar xi float64\n\n\tnw = ip[0]\n\tif n > (nw << 2) {\n\t\tnw = n >> 2\n\t\tmakewt(nw, ip, w)\n\t}\n\tnc = ip[1]\n\tif n > (nc << 2) {\n\t\tnc = n >> 2\n\t\tmakect(nc, ip, w[nw:])\n\t}\n\tif isgn >= 0 {\n\t\tif n > 4 {\n\t\t\tcftfsub(n, a, ip, nw, w)\n\t\t\trftfsub(n, a, nc, w[nw:])\n\t\t} else if n == 4 {\n\t\t\tcftfsub(n, a, ip, nw, w)\n\t\t}\n\t\txi = a[0] - a[1]\n\t\ta[0] += a[1]\n\t\ta[1] = xi\n\t} else {\n\t\ta[1] = 0.5 * (a[0] - a[1])\n\t\ta[0] -= a[1]\n\t\tif n > 4 {\n\t\t\trftbsub(n, a, nc, w[nw:])\n\t\t\tcftbsub(n, a, ip, nw, w)\n\t\t} else if n == 4 {\n\t\t\tcftbsub(n, a, ip, nw, w)\n\t\t}\n\t}\n}", "func (mp *MatrixParams) LrnFactor(act float32) float32 {\n\tif !mp.Deriv {\n\t\treturn act\n\t}\n\treturn 2 * act * (1 - act)\n}", "func LDL(a Const) (*LDLFact, error) {\n\tif err := errNonPosDims(a); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := errNonSquare(a); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := errNonSymm(a); err != nil {\n\t\treturn nil, err\n\t}\n\treturn ldl(cloneMat(a), DefaultTri)\n}", "func lmulFR(w *wideFr, a, b *Fr) {\n\t// Handbook of Applied Cryptography\n\t// Hankerson, Menezes, Vanstone\n\t// 14.12 Algorithm Multiple-precision multiplication\n\n\tvar w0, w1, w2, w3, w4, w5, w6, w7 uint64\n\tvar a0 = a[0]\n\tvar a1 = a[1]\n\tvar a2 = a[2]\n\tvar a3 = a[3]\n\tvar b0 = b[0]\n\tvar b1 = b[1]\n\tvar b2 = b[2]\n\tvar b3 = b[3]\n\tvar u, v, c, t uint64\n\n\t// i = 0, j = 0\n\tc, w0 = bits.Mul64(a0, b0)\n\n\t// i = 0, j = 1\n\tu, v = bits.Mul64(a1, b0)\n\tw1 = v + c\n\tc = u + (v&c|(v|c)&^w1)>>63\n\n\t// i = 0, j = 2\n\tu, v = bits.Mul64(a2, b0)\n\tw2 = v + c\n\tc = u + (v&c|(v|c)&^w2)>>63\n\n\t// i = 0, j = 3\n\tu, v = bits.Mul64(a3, b0)\n\tw3 = v + c\n\tw4 = u + (v&c|(v|c)&^w3)>>63\n\n\t//\n\t// i = 1, j = 0\n\tc, v = bits.Mul64(a0, b1)\n\tt = v + w1\n\tc += (v&w1 | (v|w1)&^t) >> 63\n\tw1 = t\n\n\t// i = 1, j = 1\n\tu, v = bits.Mul64(a1, b1)\n\tt = v + w2\n\tu += (v&w2 | (v|w2)&^t) >> 63\n\tw2 = t + c\n\tc = u + (t&c|(t|c)&^w2)>>63\n\n\t// i = 1, j = 2\n\tu, v = bits.Mul64(a2, b1)\n\tt = v + w3\n\tu += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t + c\n\tc = u + (t&c|(t|c)&^w3)>>63\n\n\t// i = 1, j = 3\n\tu, v = bits.Mul64(a3, b1)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tw5 = u + (t&c|(t|c)&^w4)>>63\n\n\t//\n\t// i = 2, j = 0\n\tc, v = bits.Mul64(a0, b2)\n\tt = v + w2\n\tc += (v&w2 | (v|w2)&^t) >> 63\n\tw2 = t\n\n\t// i = 2, j = 1\n\tu, v = bits.Mul64(a1, b2)\n\tt = v + w3\n\tu += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t + c\n\tc = u + (t&c|(t|c)&^w3)>>63\n\n\t// i = 2, j = 2\n\tu, v = bits.Mul64(a2, b2)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tc = u + (t&c|(t|c)&^w4)>>63\n\n\t// i = 2, j = 3\n\tu, v = bits.Mul64(a3, b2)\n\tt = v + w5\n\tu += (v&w5 | (v|w5)&^t) >> 63\n\tw5 = t + c\n\tw6 = u + (t&c|(t|c)&^w5)>>63\n\n\t//\n\t// i = 3, j = 0\n\tc, v = bits.Mul64(a0, b3)\n\tt = v + w3\n\tc += (v&w3 | (v|w3)&^t) >> 63\n\tw3 = t\n\n\t// i = 3, j = 1\n\tu, v = bits.Mul64(a1, b3)\n\tt = v + w4\n\tu += (v&w4 | (v|w4)&^t) >> 63\n\tw4 = t + c\n\tc = u + (t&c|(t|c)&^w4)>>63\n\n\t// i = 3, j = 2\n\tu, v = bits.Mul64(a2, b3)\n\tt = v + w5\n\tu += (v&w5 | (v|w5)&^t) >> 63\n\tw5 = t + c\n\tc = u + (t&c|(t|c)&^w5)>>63\n\n\t// i = 3, j = 3\n\tu, v = bits.Mul64(a3, b3)\n\tt = v + w6\n\tu += (v&w6 | (v|w6)&^t) >> 63\n\tw6 = t + c\n\tw7 = u + (t&c|(t|c)&^w6)>>63\n\n\tw[0] = w0\n\tw[1] = w1\n\tw[2] = w2\n\tw[3] = w3\n\tw[4] = w4\n\tw[5] = w5\n\tw[6] = w6\n\tw[7] = w7\n}", "func Dlarf(side mat.MatSide, m, n int, v *mat.Vector, incv int, tau float64, c *mat.Matrix, work *mat.Vector) {\n\tvar applyleft bool\n\tvar one, zero float64\n\tvar i, lastc, lastv int\n\tvar err error\n\n\tone = 1.0\n\tzero = 0.0\n\n\tapplyleft = side == Left\n\tlastv = 0\n\tlastc = 0\n\tif tau != zero {\n\t\t//! Set up variables for scanning V. LASTV begins pointing to the end\n\t\t//! of V.\n\t\tif applyleft {\n\t\t\tlastv = m\n\t\t} else {\n\t\t\tlastv = n\n\t\t}\n\t\tif incv > 0 {\n\t\t\ti = 1 + (lastv-1)*incv\n\t\t} else {\n\t\t\ti = 1\n\t\t}\n\t\t//! Look for the last non-zero row in V.\n\n\t\tfor lastv > 0 && v.Get(i-1) == zero {\n\t\t\tlastv = lastv - 1\n\t\t\ti = i - incv\n\t\t}\n\t\tif applyleft {\n\t\t\t//! Scan for the last non-zero column in C(1:lastv,:).\n\n\t\t\tlastc = Iladlc(lastv, n, c)\n\t\t} else {\n\t\t\t//! Scan for the last non-zero row in C(:,1:lastv).\n\n\t\t\tlastc = Iladlr(m, lastv, c)\n\t\t}\n\t}\n\t//! Note that lastc.eq.0 renders the BLAS operations null; no special\n\t//! case is needed at this level.\n\tif applyleft {\n\t\t// Form H * C\n\t\tif lastv > 0 {\n\t\t\t// w(1:lastc,1) := C(1:lastv,1:lastc)**T * v(1:lastv,1)\n\t\t\tif err = work.Gemv(Trans, lastv, lastc, one, c, v, incv, zero, 1); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t// C(1:lastv,1:lastc) := C(...) - v(1:lastv,1) * w(1:lastc,1)**T\n\t\t\tif err = c.Ger(lastv, lastc, -tau, v, incv, work, 1); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// Form C * H\n\t\tif lastv > 0 {\n\t\t\t// w(1:lastc,1) := C(1:lastc,1:lastv) * v(1:lastv,1)\n\t\t\tif err = work.Gemv(NoTrans, lastc, lastv, one, c, v, incv, zero, 1); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\n\t\t\t// C(1:lastc,1:lastv) := C(...) - w(1:lastc,1) * v(1:lastv,1)**T\n\t\t\tif err = c.Ger(lastc, lastv, -tau, work, 1, v, incv); err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func TestLambertVallado(t *testing.T) {\n\t// From Vallado 4th edition, page 497\n\tRi := mat64.NewVector(3, []float64{15945.34, 0, 0})\n\tRf := mat64.NewVector(3, []float64{12214.83899, 10249.46731, 0})\n\tViExp := mat64.NewVector(3, []float64{2.058913, 2.915965, 0})\n\tVfExp := mat64.NewVector(3, []float64{-3.451565, 0.910315, 0})\n\tfor _, dm := range []TransferType{TTypeAuto, TType1} {\n\t\tVi, Vf, ψ, err := Lambert(Ri, Rf, 76.0*time.Minute, dm, Earth)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"err %s\", err)\n\t\t}\n\t\tif !mat64.EqualApprox(Vi, ViExp, 1e-6) {\n\t\t\tt.Logf(\"ψ=%f\", ψ)\n\t\t\tt.Logf(\"\\nGot %+v\\nExp %+v\\n\", mat64.Formatted(Vi.T()), mat64.Formatted(ViExp.T()))\n\t\t\tt.Fatalf(\"[%s] incorrect Vi computed\", dm)\n\t\t}\n\t\tif !mat64.EqualApprox(Vf, VfExp, 1e-6) {\n\t\t\tt.Logf(\"ψ=%f\", ψ)\n\t\t\tt.Logf(\"\\nGot %+v\\nExp %+v\\n\", mat64.Formatted(Vf.T()), mat64.Formatted(VfExp.T()))\n\t\t\tt.Fatalf(\"[%s] incorrect Vf computed\", dm)\n\t\t}\n\t\tt.Logf(\"[OK] %s\", dm)\n\t}\n\t// Test with dm=-1\n\tViExp = mat64.NewVector(3, []float64{-3.811158, -2.003854, 0})\n\tVfExp = mat64.NewVector(3, []float64{4.207569, 0.914724, 0})\n\n\tVi, Vf, ψ, err := Lambert(Ri, Rf, 76.0*time.Minute, TType2, Earth)\n\tif err != nil {\n\t\tt.Fatalf(\"err %s\", err)\n\t}\n\tif !mat64.EqualApprox(Vi, ViExp, 1e-6) {\n\t\tt.Logf(\"ψ=%f\", ψ)\n\t\tt.Logf(\"\\nGot %+v\\nExp %+v\\n\", mat64.Formatted(Vi.T()), mat64.Formatted(ViExp.T()))\n\t\tt.Fatalf(\"[%s] incorrect Vi computed\", TType2)\n\t}\n\tif !mat64.EqualApprox(Vf, VfExp, 1e-6) {\n\t\tt.Logf(\"ψ=%f\", ψ)\n\t\tt.Logf(\"\\nGot %+v\\nExp %+v\\n\", mat64.Formatted(Vf.T()), mat64.Formatted(VfExp.T()))\n\t\tt.Fatalf(\"[%s] incorrect Vf computed\", TType2)\n\t}\n\tt.Logf(\"[OK] %s\", TType2)\n}", "func lexFloat(l *lexer) stateFn {\r\nLoop:\r\n\tfor {\r\n\t\tswitch r := l.next(); {\r\n\t\tcase isDigit(r):\r\n\t\tdefault:\r\n\t\t\tl.backup()\r\n\t\t\tl.emit(TokFloat)\r\n\t\t\tbreak Loop\r\n\t\t}\r\n\t}\r\n\treturn lexAny\r\n}", "func mpaddfltflt(a *Mpflt, b *Mpflt) {\n\tif Mpdebug != 0 /*TypeKind(100016)*/ {\n\t\tfmt.Printf(\"\\n%v + %v\", Fconv(a, 0), Fconv(b, 0))\n\t}\n\n\tsa := sigfig(a)\n\tvar s int\n\tvar sb int\n\tif sa == 0 {\n\t\tmpmovefltflt(a, b)\n\t\tgoto out\n\t}\n\n\tsb = sigfig(b)\n\tif sb == 0 {\n\t\tgoto out\n\t}\n\n\ts = int(a.Exp) - int(b.Exp)\n\tif s > 0 {\n\t\t// a is larger, shift b right\n\t\tvar c Mpflt\n\t\tmpmovefltflt(&c, b)\n\n\t\t_Mpshiftfix(&c.Val, -s)\n\t\t_mpaddfixfix(&a.Val, &c.Val, 0)\n\t\tgoto out\n\t}\n\n\tif s < 0 {\n\t\t// b is larger, shift a right\n\t\t_Mpshiftfix(&a.Val, s)\n\n\t\tmpsetexp(a, int(a.Exp)-s)\n\t\t_mpaddfixfix(&a.Val, &b.Val, 0)\n\t\tgoto out\n\t}\n\n\t_mpaddfixfix(&a.Val, &b.Val, 0)\n\nout:\n\tmpnorm(a)\n\tif Mpdebug != 0 /*TypeKind(100016)*/ {\n\t\tfmt.Printf(\" = %v\\n\\n\", Fconv(a, 0))\n\t}\n}", "func Lerp(value0, value1 *Vector3D.Vector3D, f float64) *Vector3D.Vector3D {\n\n\ta := 1 - f\n\tb := value0.Multiply(a)\n\tc := value1.Multiply(f)\n\td := b.Add(c)\n\n\treturn d\n}", "func LaguerreAL(n int, a, x float64) float64 {\n\tswitch {\n\tcase math.IsNaN(a) || math.IsNaN(x) || n < 0:\n\t\treturn math.NaN()\n\tcase n == 0:\n\t\treturn 1\n\tcase n == 1:\n\t\treturn 1 + a - x\n\t}\n\n\tscale := 1.0\n\tif a < 0 && a == math.Trunc(a) {\n\t\t// scale = Gamma(-n+|a|) / Gamma(-n)\n\t\tif -float64(n)-a <= 0 {\n\t\t\t// scale = (-1)**|a| n! / (n-|a|)!\n\t\t\tscale *= float64(1 - 2*(int(a)&1))\n\t\t\tlnfac, snfac := math.Lgamma(float64(n + 1))\n\t\t\tlanfac, sanfac := math.Lgamma(float64(n) + a + 1)\n\t\t\tscale *= float64(snfac*sanfac) * math.Exp(lanfac-lnfac)\n\t\t} else {\n\t\t\treturn math.NaN()\n\t\t}\n\t\tn, a = n+int(a), -a\n\t\tscale *= math.Pow(x, a)\n\t}\n\n\ttmp := 1.0\n\tres := 1 + a - x\n\tfor k := 1; k < n; k++ {\n\t\tp := a + float64(2*k) + 1 - x\n\t\tq := a + float64(k)\n\t\tr := float64(k + 1)\n\t\tres, tmp = (p*res-q*tmp)/r, res\n\t}\n\treturn scale * res\n}", "func LDivide(a, b Matrix) Matrix {\n\tvar x mat64.Dense\n\terr := x.Solve(ToMat64(a), ToMat64(b))\n\tif err != nil {\n\t\treturn WithValue(math.NaN(), a.Shape()[0], b.Shape()[1]).M()\n\t}\n\treturn ToMatrix(&x)\n}", "func lorentzFactor(v float64) float64 {\n\n\t// ensure that the velocity is not equal to c\n\tif v == c {\n\t\treturn 0.0\n\t}\n\n\t// determine the square factor\n\tsquareFactor := 1 - ((v * v) / (c * c))\n\n\t// take the square root of the factor\n\tsqrtFactor := math.Sqrt(squareFactor)\n\n\t// safety check, ensure that that factor is not zero\n\tif sqrtFactor == 0.0 {\n\t\treturn 0.0\n\t}\n\n\t// go ahead and return the inverse square root\n\treturn 1 / sqrtFactor\n}", "func LtFn(a interface{}, b interface{}) bool {\n\treturn a.(float64) < b.(float64)\n}", "func Fp2f(x *float64) float64 {\n\tif x == nil {\n\t\t// this is not initialized yet - return NaN\n\t\treturn math.Log(-1.0)\n\t} else {\n\t\treturn *x\n\t}\n}", "func Lt(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.ltDD(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.ltDS(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.gtDS(a, opts...)\n\t}\n\n\tpanic(\"unreachable\")\n}", "func (f RatingFilter) Lt(value float64) (exp Filter) {\n\treturn Filter{\n\t\texpression: \"rating < ?\",\n\t\targs: []interface{}{value},\n\t}\n}", "func LU(V float64) float64 {\n\tconst V0 = 0.7746\n\treturn 20 * math.Log10(V/V0)\n}", "func zerrlqt(path string, _t *testing.T) {\n\tvar i, j, nmax int\n\tvar err error\n\n\tw := cvf(2)\n\ta := cmf(2, 2, opts)\n\tc := cmf(2, 2, opts)\n\tt := cmf(2, 2, opts)\n\n\tnmax = 2\n\terrt := &gltest.Common.Infoc.Errt\n\tok := &gltest.Common.Infoc.Ok\n\tsrnamt := &gltest.Common.Srnamc.Srnamt\n\n\t// Set the variables to innocuous values.\n\tfor j = 1; j <= nmax; j++ {\n\t\tfor i = 1; i <= nmax; i++ {\n\t\t\ta.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tc.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tt.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t}\n\t\tw.Set(j-1, 0.)\n\t}\n\t(*ok) = true\n\n\t// Error exits for LQT factorization\n\t//\n\t// Zgelqt\n\t*srnamt = \"Zgelqt\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgelqt(-1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Zgelqt(0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > min(m, n) && min(m, n) > 0): mb=0, m=0, n=0\")\n\terr = golapack.Zgelqt(0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Zgelqt(2, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Zgelqt(2, 2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgelqt\", err)\n\n\t// Zgelqt3\n\t*srnamt = \"Zgelqt3\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgelqt3(-1, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"n < m: m=0, n=-1\")\n\terr = golapack.Zgelqt3(0, -1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Zgelqt3(2, 2, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\t*errt = fmt.Errorf(\"t.Rows < max(1, m): t.Rows=1, m=2\")\n\terr = golapack.Zgelqt3(2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Zgelqt3\", err)\n\n\t// Zgemlqt\n\t*srnamt = \"Zgemlqt\"\n\t*errt = fmt.Errorf(\"!left && !right: side=Unrecognized: /\")\n\terr = golapack.Zgemlqt('/', NoTrans, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"!tran && !notran: trans=Unrecognized: /\")\n\terr = golapack.Zgemlqt(Left, '/', 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, -1, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, -1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > k && k > 0): mb=0, k=0\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 0, 0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < max(1, k): v.Rows=1, k=2\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 2, 2, 2, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < max(1, k): v.Rows=1, k=2\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 2, 2, 2, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Zgemlqt(Right, NoTrans, 1, 1, 2, 2, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\t*errt = fmt.Errorf(\"c.Rows < max(1, m): c.Rows=1, m=2\")\n\terr = golapack.Zgemlqt(Left, NoTrans, 2, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Zgemlqt\", err)\n\n\t// Print a summary line.\n\t// alaesm(path, *ok)\n\n\tif !(*ok) {\n\t\t_t.Fail()\n\t}\n}", "func (f LQFactor) L() *Dense {\n\tlq, lDiag := f.LQ, f.lDiag\n\tm, _ := lq.Dims()\n\tl := NewDense(m, m, nil)\n\tfor i, v := range lDiag {\n\t\tfor j := 0; j < m; j++ {\n\t\t\tif i < j {\n\t\t\t\tl.Set(j, i, lq.At(j, i))\n\t\t\t} else if i == j {\n\t\t\t\tl.Set(j, i, v)\n\t\t\t}\n\t\t}\n\t}\n\treturn l\n}", "func L3FP(inBasis Basis, delta float64) Basis {\n\tvar (\n\t\tbasis = inBasis.Copy()\n\t\tk = 1\n\t\tFc = false\n\t\tbd = make([][]float64, basis.Rank())\n\t\tmu = make([][]float64, basis.Rank())\n\t\tc = make([]float64, basis.Rank())\n\t)\n\n\tfor i := 0; i < basis.Rank(); i++ {\n\t\tbd[i] = make([]float64, basis.Dimension())\n\t\tmu[i] = make([]float64, basis.Rank())\n\t\tfor j := 0; j < basis.Dimension(); j++ {\n\t\t\tbd[i][j] = basis.FGet(i, j)\n\t\t}\n\t}\n\n\tfor k < basis.Rank() {\n\t\t// 2.\n\t\tc[k] = dot(bd[k], bd[k])\n\t\tif k == 1 {\n\t\t\tc[0] = dot(bd[0], bd[0])\n\t\t}\n\t\tfor j := 0; j < k; j++ {\n\t\t\tif abs(dot(bd[k], bd[j])) < _2_p_nh_tor*math.Sqrt(dot(bd[k], bd[k])*dot(bd[j], bd[j])) {\n\t\t\t\tmu[k][j] = basis.FDot(k, j)\n\t\t\t} else {\n\t\t\t\tmu[k][j] = dot(bd[k], bd[j])\n\t\t\t}\n\n\t\t\tfor i := 0; i < j; i++ {\n\t\t\t\tmu[k][j] -= mu[j][i] * mu[k][i] * c[i]\n\t\t\t}\n\n\t\t\tmu[k][j] /= c[j]\n\n\t\t\tc[k] -= mu[k][j] * mu[k][j] * c[j]\n\t\t}\n\n\t\t// 3.\n\t\tfor j := k - 1; j >= 0; j-- {\n\t\t\tif abs(mu[k][j]) > 0.5 {\n\t\t\t\tvar _mu = math.Floor(mu[k][j] + 0.5)\n\n\t\t\t\tif abs(_mu) > _2_p_h_tor {\n\t\t\t\t\tFc = true\n\t\t\t\t}\n\n\t\t\t\tfor i := 0; i < j; i++ {\n\t\t\t\t\tmu[k][i] -= _mu * mu[j][i]\n\t\t\t\t}\n\n\t\t\t\tmu[k][j] -= _mu\n\t\t\t\tbasis.ColumnReduceInt64(k, j, int64(_mu))\n\t\t\t\tfor i := range bd[k] {\n\t\t\t\t\tbd[k][i] = basis.FGet(k, i)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif Fc {\n\t\t\tFc = false\n\t\t\tk -= 1\n\t\t\tif k < 1 {\n\t\t\t\tk = 1\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\t// 4.\n\t\tif delta*c[k-1] > c[k]+mu[k][k-1]*mu[k][k-1]*c[k-1] {\n\n\t\t\tbasis.ColumnSwap(k, k-1)\n\t\t\tbd[k], bd[k-1] = bd[k-1], bd[k]\n\n\t\t\tk -= 1\n\t\t\tif k < 1 {\n\t\t\t\tk = 1\n\t\t\t}\n\t\t} else {\n\t\t\tk += 1\n\t\t}\n\t}\n\treturn basis\n}", "func MtoFT(d Meter) Feet {\n\treturn Feet(d / 3.28084)\n}", "func ModGL(a, b gl.Float) gl.Float {\n\treturn (gl.Float)(math.Mod((float64)(a), (float64)(b)))\n}", "func Lerp(v1, v2 Vect, t f.Float) Vect {\n\treturn Add(Mult(v1, 1.0-t), Mult(v2, t))\n}", "func (ch *CholFactors) L() *Dense {\n\treturn ch.l\n}", "func Linear(t0, t1, t Time) float32 {\n\tif t >= t1 {\n\t\treturn 1\n\t}\n\tif t <= t0 {\n\t\treturn 0\n\t}\n\treturn float32(t-t0) / float32(t1-t0)\n}", "func lxRealFrac(lx *lexer) lexerStateFn {\n\tfor {\n\t\tc, _, err := lx.input.ReadRune()\n\t\tif lx.lerror(err) {\n\t\t\treturn nil\n\t\t}\n\n\t\tif unicode.IsDigit(c) {\n\t\t\tlx.acc = append(lx.acc, c)\n\t\t} else if (c == 'e') || (c == 'E') {\n\t\t\tlx.acc = append(lx.acc, c)\n\t\t\treturn lxRealExp\n\t\t} else {\n\t\t\tlx.emit(REALTOK, string(lx.acc))\n\t\t\treturn toBase1(lx, c, false)\n\t\t}\n\t}\n\tpanic(fmt.Errorf(\"Unreachable\"))\n}", "func (e *Engine) Lt(a tensor.Tensor, b tensor.Tensor, opts ...tensor.FuncOpt) (retVal tensor.Tensor, err error) {\n\tname := constructName2(a, b, \"lt\")\n\n\tif !e.HasFunc(name) {\n\t\treturn nil, errors.Errorf(\"Unable to perform Lt(). The tensor engine does not have the function %q\", name)\n\t}\n\n\tif err = binaryCheck(a, b); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Basic checks failed for Lt\")\n\t}\n\n\tvar reuse tensor.DenseTensor\n\tvar safe, toReuse bool\n\tif reuse, safe, toReuse, _, _, err = handleFuncOpts(a.Shape(), a.Dtype(), a.DataOrder(), true, opts...); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Unable to handle funcOpts\")\n\t}\n\n\tvar mem, memB cu.DevicePtr\n\tvar size int64\n\n\tswitch {\n\tcase toReuse:\n\t\tmem = cu.DevicePtr(reuse.Uintptr())\n\t\tmemA := cu.DevicePtr(a.Uintptr())\n\t\tmemSize := int64(a.MemSize())\n\t\te.memcpy(mem, memA, memSize)\n\n\t\tsize = int64(logicalSize(reuse.Shape()))\n\t\tretVal = reuse\n\tcase !safe:\n\t\tmem = cu.DevicePtr(a.Uintptr())\n\t\tretVal = a\n\t\tsize = int64(logicalSize(a.Shape()))\n\tdefault:\n\t\treturn nil, errors.New(\"Impossible state: A reuse tensor must be passed in, or the operation must be unsafe. Incr and safe operations are not supported\")\n\t}\n\n\tmemB = cu.DevicePtr(b.Uintptr())\n\tfn := e.f[name]\n\tgridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ := e.ElemGridSize(int(size))\n\targs := []unsafe.Pointer{\n\t\tunsafe.Pointer(&mem),\n\t\tunsafe.Pointer(&memB),\n\t\tunsafe.Pointer(&size),\n\t}\n\tlogf(\"gx %d, gy %d, gz %d | bx %d by %d, bz %d\", gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ)\n\tlogf(\"CUDADO %q, Mem: %v MemB: %v size %v, args %v\", name, mem, memB, size, args)\n\tlogf(\"LaunchKernel Params. mem: %v. Size %v\", mem, size)\n\te.c.LaunchAndSync(fn, gridDimX, gridDimY, gridDimZ, blockDimX, blockDimY, blockDimZ, 0, cu.NoStream, args)\n\treturn\n}", "func mathFmod(ctx phpv.Context, args []*phpv.ZVal) (*phpv.ZVal, error) {\n\tvar x, y phpv.ZFloat\n\t_, err := core.Expand(ctx, args, &x, &y)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn phpv.ZFloat(math.Mod(float64(x), float64(y))).ZVal(), nil\n}", "func Lgamma(tk obj.Token, args []oop.VarDef) oop.Val {\n\tval := args[0].Val\n\tif val.Type != oop.Int && val.Type != oop.Float {\n\t\tval.Data = 0.0\n\t}\n\ta, b := math.Lgamma(val.Data.(float64))\n\treturn oop.Val{\n\t\tData: oop.ListType{\n\t\t\t{Data: a, Type: oop.Float},\n\t\t\t{Data: b, Type: oop.Int},\n\t\t},\n\t\tType: oop.Float,\n\t\tTag: \"function_multiple_returns\",\n\t}\n}", "func (o *FloatObject) Lt(r Object) (bool) {\n return o.Value < r.AsFloat()\n}", "func Fiore(t *terrapin.Terrapin, lung float64, liv int) {\n for i := 0; i < 3; i++ {\n if liv == 0 {\n t.Forward(lung)\n return\n }\n Fiore(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Right(math.Pi - math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Left(math.Pi / 3.0)\n Fiore(t, lung, liv - 1)\n t.Right(2.0 * math.Pi / 3.0)\n }\n\n}", "func RandomFlt(ln int) []float64 {\n\tvar numbers []float64\n\t//var array [40]float64\n\trand.Seed(time.Now().UTC().UnixNano())\n\tfor i := ln - 1; i > 0; i-- {\n\t\t//j := rand.Intn(i + 1)\n\t\tn := rand.Float64() * 90 // simulate number close to 90\n\t\t//array[i], array[j] = array[j], array[i]\n\t\tnumbers = append(numbers, n)\n\t}\n\treturn numbers\n}", "func fritsch(w, x float64) float64 {\n\tz := math.Log(x/w) - w\n\tw1 := w + 1\n\tq := 2 * w1 * (w1 + 2*z/3)\n\teps := z / w1 * (q - z) / (q - 2*z)\n\treturn w * (1 + eps)\n}", "func logF(k, eta float64, y, n []float64) []float64 {\n\tv := make([]float64, len(y))\n\tfor i, _ := range v {\n\t\tv[i] = lnB(k*eta+y[i], k*(1-eta)+n[i]-y[i]) - lnB(k*eta, k*(1-eta))\n\t}\n\treturn v\n}", "func lusolve(a [][]float64, ipvt []int, b []float64) {\n\tn := len(a)\n\n\t// find first non-zero element\n\ti := 0\n\tfor ; i != n; i++ {\n\t\tr := ipvt[i]\n\t\tb[r], b[i] = b[i], b[r]\n\t\tif b[i] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// forward substitution using lower triangular\n\tbi, i := i, i+1\n\tfor ; i < n; i++ {\n\t\tr := ipvt[i]\n\t\tt := b[r]\n\t\tb[r] = b[i]\n\t\tfor j := bi; j < i; j++ {\n\t\t\tt -= a[i][j] * b[j]\n\t\t}\n\t\tb[i] = t\n\t}\n\n\t// back substitution using upper triangular\n\tfor i := n - 1; i >= 0; i-- {\n\t\tt := b[i]\n\t\tfor j := i + 1; j != n; j++ {\n\t\t\tt -= a[i][j] * b[j]\n\t\t}\n\t\tb[i] = t / a[i][i]\n\t}\n}", "func newLfsHook(writer *rotatelogs.RotateLogs, tf *moduleFormatter) logrus.Hook {\n\tlfsHook := lfshook.NewHook(lfshook.WriterMap{\n\t\tlogrus.DebugLevel: writer,\n\t\tlogrus.InfoLevel: writer,\n\t\tlogrus.WarnLevel: writer,\n\t\tlogrus.ErrorLevel: writer,\n\t\tlogrus.FatalLevel: writer,\n\t\tlogrus.PanicLevel: writer,\n\t}, tf)\n\n\treturn lfsHook\n}", "func Vflt32(input []int32, inputStride int, output []float32, outputStride int) {\n\tC.vDSP_vflt32((*C.int)(&input[0]), C.vDSP_Stride(inputStride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), minLen(len(input)/inputStride, len(output)/outputStride))\n}", "func LQ(a *Dense) LQFactor {\n\t// Initialize.\n\tm, n := a.Dims()\n\tif m > n {\n\t\tpanic(ErrShape)\n\t}\n\n\tlq := *a\n\n\tlDiag := make([]float64, m)\n\tprojs := make(Vec, m)\n\n\t// Main loop.\n\tfor k := 0; k < m; k++ {\n\t\thh := Vec(lq.RowView(k))[k:]\n\t\tnorm := blasEngine.Dnrm2(len(hh), hh, 1)\n\t\tlDiag[k] = norm\n\n\t\tif norm != 0 {\n\t\t\thhNorm := (norm * math.Sqrt(1-hh[0]/norm))\n\t\t\tif hhNorm == 0 {\n\t\t\t\thh[0] = 0\n\t\t\t} else {\n\t\t\t\t// Form k-th Householder vector.\n\t\t\t\ts := 1 / hhNorm\n\t\t\t\thh[0] -= norm\n\t\t\t\tblasEngine.Dscal(len(hh), s, hh, 1)\n\n\t\t\t\t// Apply transformation to remaining columns.\n\t\t\t\tif k < m-1 {\n\t\t\t\t\ta.View(&lq, k+1, k, m-k-1, n-k)\n\t\t\t\t\tprojs = projs[0 : m-k-1]\n\t\t\t\t\tprojs.Mul(a, &hh)\n\n\t\t\t\t\tfor j := 0; j < m-k-1; j++ {\n\t\t\t\t\t\tdst := a.RowView(j)\n\t\t\t\t\t\tblasEngine.Daxpy(len(dst), -projs[j], hh, 1, dst, 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t*a = lq\n\n\treturn LQFactor{a, lDiag}\n}", "func BSFL(mr, r operand.Op) { ctx.BSFL(mr, r) }", "func (tvm TimeValOfMoney) LumpSumFVBigIntNum(\n\t\tpresentValue, interestRate, numOfPeriods BigIntNum,\n\t\tfutureValueMaxPrecision uint ) (BigIntNum, error) {\n\n\tePrefix := \"TimeValOfMoney.LumpSumFVBigIntNum() \"\n\n\tif numOfPeriods.GetSign() == -1 {\n\t\treturn BigIntNum{}.NewZero(0),\n\t\t\tfmt.Errorf(ePrefix +\n\t\t\t\t\"Error: Input parameter 'numOfPeriods' is a negative value. \" +\n\t\t\t\t\"numOfPeriods='%v' \", presentValue.GetNumStr())\n\t}\n\n\tbinumOne := BigIntNum{}.NewOne(0)\n\n\tonePlusI := BigIntMathAdd{}.AddBigIntNums(binumOne, interestRate)\n\n\tmaxPrecision, _ := BigIntMathPower{}.MinimumRequiredPrecision(onePlusI, numOfPeriods)\n\n\tpwrN, err := BigIntMathPower{}.Pwr(onePlusI, numOfPeriods, maxPrecision)\n\n\tif err != nil {\n\t\treturn BigIntNum{}.NewZero(0),\n\t\t\tfmt.Errorf(ePrefix +\n\t\t\t\t\"Error returned by BigIntMathPower{}.Pwr(onePlusI, numOfPeriods, maxPrecision) \" +\n\t\t\t\t\"onePlusI='%v, numOfPeriods='%v', maxPrecision='%v' Error='%v' \",\n\t\t\t\tonePlusI.GetNumStr(), numOfPeriods.GetNumStr(), maxPrecision, err.Error())\n\t}\n\n\tfutureValue := BigIntMathMultiply{}.MultiplyBigIntNums(presentValue, pwrN)\n\n\tif futureValue.GetPrecisionUint() > futureValueMaxPrecision {\n\t\tfutureValue.RoundToDecPlace(futureValueMaxPrecision)\n\t}\n\n\treturn futureValue, nil\n}", "func PSLLL(imx, x operand.Op) { ctx.PSLLL(imx, x) }", "func f(t float64, w float64) float64 {\n\treturn (-1 - 0.02*w + (acc * t))\n}", "func f11(ctx *Context, l0 int32) int32 {\n\treturn ctx.f.F11(ctx, l0)\n}", "func (v Volume) Litres() float64 {\n\treturn float64(v / Litre)\n}", "func (c *Clac) Ln() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn unary(\"log\", vals[0])\n\t})\n}", "func zerrlqtp(path string, _t *testing.T) {\n\tvar i, j, nmax int\n\tvar err error\n\n\tw := cvf(2)\n\ta := cmf(2, 2, opts)\n\tb := cmf(2, 2, opts)\n\tc := cmf(2, 2, opts)\n\tt := cmf(2, 2, opts)\n\n\tnmax = 2\n\terrt := &gltest.Common.Infoc.Errt\n\tok := &gltest.Common.Infoc.Ok\n\tsrnamt := &gltest.Common.Srnamc.Srnamt\n\n\t// Set the variables to innocuous values.\n\tfor j = 1; j <= nmax; j++ {\n\t\tfor i = 1; i <= nmax; i++ {\n\t\t\ta.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tc.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t\tt.Set(i-1, j-1, 1./complex(float64(i+j), 0))\n\t\t}\n\t\tw.Set(j-1, 0.0)\n\t}\n\t(*ok) = true\n\n\t// Error exits for TPLQT factorization\n\t//\n\t// Ztplqt\n\t*srnamt = \"Ztplqt\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztplqt(-1, 1, 0, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztplqt(1, -1, 0, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || (l > min(m, n) && min(m, n) >= 0): l=-1, m=0, n=1\")\n\terr = golapack.Ztplqt(0, 1, -1, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || (l > min(m, n) && min(m, n) >= 0): l=1, m=0, n=1\")\n\terr = golapack.Ztplqt(0, 1, 1, 1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > m && m > 0): mb=0, m=0\")\n\terr = golapack.Ztplqt(0, 1, 0, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > m && m > 0): mb=2, m=1\")\n\terr = golapack.Ztplqt(1, 1, 0, 2, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Ztplqt(2, 1, 0, 2, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztplqt(2, 1, 0, 1, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\t*errt = fmt.Errorf(\"t.Rows < mb: t.Rows=1, mb=2\")\n\terr = golapack.Ztplqt(2, 2, 1, 2, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztplqt\", err)\n\n\t// Ztplqt2\n\t*srnamt = \"Ztplqt2\"\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztplqt2(-1, 0, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztplqt2(0, -1, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"l < 0 || l > min(m, n): l=-1, m=0, n=0\")\n\terr = golapack.Ztplqt2(0, 0, -1, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"a.Rows < max(1, m): a.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(2))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(2))\n\tchkxer2(\"Ztplqt2\", err)\n\t*errt = fmt.Errorf(\"t.Rows < max(1, m): t.Rows=1, m=2\")\n\terr = golapack.Ztplqt2(2, 2, 0, a.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(1))\n\tchkxer2(\"Ztplqt2\", err)\n\n\t// Ztpmlqt\n\t*srnamt = \"Ztpmlqt\"\n\t*errt = fmt.Errorf(\"!left && !right: side=Unrecognized: /\")\n\terr = golapack.Ztpmlqt('/', NoTrans, 0, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"!tran && !notran: trans=Unrecognized: /\")\n\terr = golapack.Ztpmlqt(Left, '/', 0, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"m < 0: m=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, -1, 0, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"n < 0: n=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, -1, 0, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"k < 0: k=-1\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, -1, 0, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"l < 0 || l > k: l=-1, k=0\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, 0, -1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"mb < 1 || (mb > k && k > 0): mb=0, k=0\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 0, 0, 0, 0, 0, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"v.Rows < k: v.Rows=1, k=2\")\n\terr = golapack.Ztpmlqt(Right, NoTrans, 2, 2, 2, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\t// *errt = fmt.Errorf(\"t.Rows < mb: t.Rows=0, mb=1\")\n\t// err = golapack.Ztpmlqt(Right, NoTrans, 1, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(0), b.Off(0, 0).UpdateRows(1), c.Off(0, 0).UpdateRows(1), w)\n\t// chkxer2(\"Ztpmlqt\", err)\n\t// *errt = fmt.Errorf(\"a.Rows < ldaq: a.Rows=0, ldaq=1\")\n\t// err = golapack.Ztpmlqt(Left, NoTrans, 1, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(1), t.Off(0, 0).UpdateRows(1), b.Off(0, 0).UpdateRows(0), c.Off(0, 0).UpdateRows(1), w)\n\t// chkxer2(\"Ztpmlqt\", err)\n\t*errt = fmt.Errorf(\"b.Rows < max(1, m): b.Rows=1, m=2\")\n\terr = golapack.Ztpmlqt(Left, NoTrans, 2, 1, 1, 1, 1, a.Off(0, 0).UpdateRows(2), t.Off(0, 0).UpdateRows(2), b.Off(0, 0).UpdateRows(2), c.Off(0, 0).UpdateRows(1), w)\n\tchkxer2(\"Ztpmlqt\", err)\n\n\t// Print a summary line.\n\t// alaesm(path, *ok)\n\n\tif !(*ok) {\n\t\t_t.Fail()\n\t}\n}", "func lexFloat(l *lexer) stateFn {\n\n\tdigits := \"0123456789\"\n\tl.acceptRuneRun(digits)\n\n\tl.emit(_FLOAT)\n\n\tr := l.next()\n\n\tswitch r {\n\tcase ' ', '\\t', '\\n':\n\t\treturn lexWhitespace\n\tcase ')':\n\t\treturn lexCloseParen\n\tcase ';':\n\t\treturn lexComment\n\t}\n\n\treturn l.errorf(\"unexpected run in lexFloat: %c\", r)\n}", "func Fv(rate decimal.Decimal, nper int64, pmt decimal.Decimal, pv decimal.Decimal, when paymentperiod.Type) decimal.Decimal {\n\tone := decimal.NewFromInt(1)\n\tminusOne := decimal.NewFromInt(-1)\n\tdWhen := decimal.NewFromInt(when.Value())\n\tdRateWithWhen := rate.Mul(dWhen)\n\tdNper := decimal.NewFromInt(nper)\n\n\tfactor := one.Add(rate).Pow(dNper)\n\tsecondFactor := factor.Sub(one).Mul(one.Add(dRateWithWhen)).Div(rate)\n\n\treturn pv.Mul(factor).Add(pmt.Mul(secondFactor)).Mul(minusOne)\n}", "func TestAutoDiffLinear(t *testing.T) {\n\ta := 5.0\n\tfn := func(v vec.Vector) (float64, error) {\n\t\treturn a*v[0] + a*v[1], nil\n\t}\n\tv := []float64{1.0, 1.0}\n\th := 1e-4\n\tepsabs := 1e-8\n\tderiv, err := Derivative(fn, v, 0, h, epsabs)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tif math.Abs(deriv-a) > epsabs {\n\t\tt.Fatalf(\"linear derivative not equal to constant (got %v, expected %v)\", deriv, a)\n\t}\n}", "func Lerp(t, v1, v2 float64) float64 {\n\treturn (1.0-t)*v1 + t*v2\n}", "func PEXTL(mr, r, r1 operand.Op) { ctx.PEXTL(mr, r, r1) }", "func LPNorm(vector []float64, p float64) (float64, error) {\n\tdistance := 0.\n\tfor _, jj := range vector {\n\t\tdistance += math.Pow(math.Abs(jj), p)\n\t}\n\treturn math.Pow(distance, 1/p), nil\n}", "func Zlarfb(side mat.MatSide, trans mat.MatTrans, direct, storev byte, m, n, k int, v, t, c, work *mat.CMatrix) {\n\tvar transt mat.MatTrans\n\tvar one complex128\n\tvar i, j int\n\tvar err error\n\n\tone = (1.0 + 0.0*1i)\n\n\t// Quick return if possible\n\tif m <= 0 || n <= 0 {\n\t\treturn\n\t}\n\n\tif trans == NoTrans {\n\t\ttranst = ConjTrans\n\t} else {\n\t\ttranst = NoTrans\n\t}\n\n\tif storev == 'C' {\n\n\t\tif direct == 'F' {\n\t\t\t// Let V = ( V1 ) (first K rows)\n\t\t\t// ( V2 )\n\t\t\t// where V1 is unit lower triangular.\n\t\t\tif side == Left {\n\t\t\t\t// Form H * C or H**H * C where C = ( C1 )\n\t\t\t\t// ( C2 )\n\t\t\t\t//\n\t\t\t\t// W := C**H * V = (C1**H * V1 + C2**H * V2) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C1**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(n, c.Off(j-1, 0).CVector(), c.Rows, 1)\n\t\t\t\t\tZlacgv(n, work.Off(0, j-1).CVector(), 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1\n\t\t\t\tif err = work.Trmm(Right, Lower, NoTrans, Unit, n, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif m > k {\n\t\t\t\t\t// W := W + C2**H * V2\n\t\t\t\t\tif err = work.Gemm(ConjTrans, NoTrans, n, k, m-k, one, c.Off(k, 0), v.Off(k, 0), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T**H or W * T\n\t\t\t\tif err = work.Trmm(Right, Upper, transt, NonUnit, n, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - V * W**H\n\t\t\t\tif m > k {\n\t\t\t\t\t// C2 := C2 - V2 * W**H\n\t\t\t\t\tif err = c.Off(k, 0).Gemm(NoTrans, ConjTrans, m-k, n, k, -one, v.Off(k, 0), work, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1**H\n\t\t\t\tif err = work.Trmm(Right, Lower, ConjTrans, Unit, n, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C1 := C1 - W**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= n; i++ {\n\t\t\t\t\t\tc.Set(j-1, i-1, c.Get(j-1, i-1)-work.GetConj(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if side == Right {\n\t\t\t\t// Form C * H or C * H**H where C = ( C1 C2 )\n\t\t\t\t//\n\t\t\t\t// W := C * V = (C1*V1 + C2*V2) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C1\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(m, c.Off(0, j-1).CVector(), 1, 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1\n\t\t\t\tif err = work.Trmm(Right, Lower, NoTrans, Unit, m, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif n > k {\n\t\t\t\t\t// W := W + C2 * V2\n\t\t\t\t\tif err = work.Gemm(NoTrans, NoTrans, m, k, n-k, one, c.Off(0, k), v.Off(k, 0), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T or W * T**H\n\t\t\t\tif err = work.Trmm(Right, Upper, trans, NonUnit, m, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - W * V**H\n\t\t\t\tif n > k {\n\t\t\t\t\t// C2 := C2 - W * V2**H\n\t\t\t\t\tif err = c.Off(0, k).Gemm(NoTrans, ConjTrans, m, n-k, k, -one, work, v.Off(k, 0), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1**H\n\t\t\t\tif err = work.Trmm(Right, Lower, ConjTrans, Unit, m, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C1 := C1 - W\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= m; i++ {\n\t\t\t\t\t\tc.Set(i-1, j-1, c.Get(i-1, j-1)-work.Get(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Let V = ( V1 )\n\t\t\t// ( V2 ) (last K rows)\n\t\t\t// where V2 is unit upper triangular.\n\t\t\tif side == Left {\n\t\t\t\t// Form H * C or H**H * C where C = ( C1 )\n\t\t\t\t// ( C2 )\n\t\t\t\t//\n\t\t\t\t// W := C**H * V = (C1**H * V1 + C2**H * V2) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C2**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(n, c.Off(m-k+j-1, 0).CVector(), c.Rows, 1)\n\t\t\t\t\tZlacgv(n, work.Off(0, j-1).CVector(), 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2\n\t\t\t\tif err = work.Trmm(Right, Upper, NoTrans, Unit, n, k, one, v.Off(m-k, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif m > k {\n\t\t\t\t\t// W := W + C1**H * V1\n\t\t\t\t\tif err = work.Gemm(ConjTrans, NoTrans, n, k, m-k, one, c, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T**H or W * T\n\t\t\t\tif err = work.Trmm(Right, Lower, transt, NonUnit, n, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - V * W**H\n\t\t\t\tif m > k {\n\t\t\t\t\t// C1 := C1 - V1 * W**H\n\t\t\t\t\tif err = c.Gemm(NoTrans, ConjTrans, m-k, n, k, -one, v, work, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2**H\n\t\t\t\tif err = work.Trmm(Right, Upper, ConjTrans, Unit, n, k, one, v.Off(m-k, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C2 := C2 - W**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= n; i++ {\n\t\t\t\t\t\tc.Set(m-k+j-1, i-1, c.Get(m-k+j-1, i-1)-work.GetConj(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if side == Right {\n\t\t\t\t// Form C * H or C * H**H where C = ( C1 C2 )\n\t\t\t\t//\n\t\t\t\t// W := C * V = (C1*V1 + C2*V2) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C2\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(m, c.Off(0, n-k+j-1).CVector(), 1, 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2\n\t\t\t\tif err = work.Trmm(Right, Upper, NoTrans, Unit, m, k, one, v.Off(n-k, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif n > k {\n\t\t\t\t\t// W := W + C1 * V1\n\t\t\t\t\tif err = work.Gemm(NoTrans, NoTrans, m, k, n-k, one, c, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T or W * T**H\n\t\t\t\tif err = work.Trmm(Right, Lower, trans, NonUnit, m, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - W * V**H\n\t\t\t\tif n > k {\n\t\t\t\t\t// C1 := C1 - W * V1**H\n\t\t\t\t\tif err = c.Gemm(NoTrans, ConjTrans, m, n-k, k, -one, work, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2**H\n\t\t\t\tif err = work.Trmm(Right, Upper, ConjTrans, Unit, m, k, one, v.Off(n-k, 0)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C2 := C2 - W\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= m; i++ {\n\t\t\t\t\t\tc.Set(i-1, n-k+j-1, c.Get(i-1, n-k+j-1)-work.Get(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t} else if storev == 'R' {\n\n\t\tif direct == 'F' {\n\t\t\t// Let V = ( V1 V2 ) (V1: first K columns)\n\t\t\t// where V1 is unit upper triangular.\n\t\t\tif side == Left {\n\t\t\t\t// Form H * C or H**H * C where C = ( C1 )\n\t\t\t\t// ( C2 )\n\t\t\t\t//\n\t\t\t\t// W := C**H * V**H = (C1**H * V1**H + C2**H * V2**H) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C1**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(n, c.Off(j-1, 0).CVector(), c.Rows, 1)\n\t\t\t\t\tZlacgv(n, work.Off(0, j-1).CVector(), 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1**H\n\t\t\t\tif err = work.Trmm(Right, Upper, ConjTrans, Unit, n, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif m > k {\n\t\t\t\t\t// W := W + C2**H * V2**H\n\t\t\t\t\tif err = work.Gemm(ConjTrans, ConjTrans, n, k, m-k, one, c.Off(k, 0), v.Off(0, k), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T**H or W * T\n\t\t\t\tif err = work.Trmm(Right, Upper, transt, NonUnit, n, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - V**H * W**H\n\t\t\t\tif m > k {\n\t\t\t\t\t// C2 := C2 - V2**H * W**H\n\t\t\t\t\tif err = c.Off(k, 0).Gemm(ConjTrans, ConjTrans, m-k, n, k, -one, v.Off(0, k), work, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1\n\t\t\t\tif err = work.Trmm(Right, Upper, NoTrans, Unit, n, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C1 := C1 - W**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= n; i++ {\n\t\t\t\t\t\tc.Set(j-1, i-1, c.Get(j-1, i-1)-work.GetConj(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if side == Right {\n\t\t\t\t// Form C * H or C * H**H where C = ( C1 C2 )\n\t\t\t\t//\n\t\t\t\t// W := C * V**H = (C1*V1**H + C2*V2**H) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C1\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(m, c.Off(0, j-1).CVector(), 1, 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1**H\n\t\t\t\tif err = work.Trmm(Right, Upper, ConjTrans, Unit, m, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif n > k {\n\t\t\t\t\t// W := W + C2 * V2**H\n\t\t\t\t\tif err = work.Gemm(NoTrans, ConjTrans, m, k, n-k, one, c.Off(0, k), v.Off(0, k), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T or W * T**H\n\t\t\t\tif err = work.Trmm(Right, Upper, trans, NonUnit, m, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - W * V\n\t\t\t\tif n > k {\n\t\t\t\t\t// C2 := C2 - W * V2\n\t\t\t\t\tif err = c.Off(0, k).Gemm(NoTrans, NoTrans, m, n-k, k, -one, work, v.Off(0, k), one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V1\n\t\t\t\tif err = work.Trmm(Right, Upper, NoTrans, Unit, m, k, one, v); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C1 := C1 - W\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= m; i++ {\n\t\t\t\t\t\tc.Set(i-1, j-1, c.Get(i-1, j-1)-work.Get(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t} else {\n\t\t\t// Let V = ( V1 V2 ) (V2: last K columns)\n\t\t\t// where V2 is unit lower triangular.\n\t\t\tif side == Left {\n\t\t\t\t// Form H * C or H**H * C where C = ( C1 )\n\t\t\t\t// ( C2 )\n\t\t\t\t//\n\t\t\t\t// W := C**H * V**H = (C1**H * V1**H + C2**H * V2**H) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C2**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(n, c.Off(m-k+j-1, 0).CVector(), c.Rows, 1)\n\t\t\t\t\tZlacgv(n, work.Off(0, j-1).CVector(), 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2**H\n\t\t\t\tif err = work.Trmm(Right, Lower, ConjTrans, Unit, n, k, one, v.Off(0, m-k)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif m > k {\n\t\t\t\t\t// W := W + C1**H * V1**H\n\t\t\t\t\tif err = work.Gemm(ConjTrans, ConjTrans, n, k, m-k, one, c, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T**H or W * T\n\t\t\t\tif err = work.Trmm(Right, Lower, transt, NonUnit, n, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - V**H * W**H\n\t\t\t\tif m > k {\n\t\t\t\t\t// C1 := C1 - V1**H * W**H\n\t\t\t\t\tif err = c.Gemm(ConjTrans, ConjTrans, m-k, n, k, -one, v, work, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2\n\t\t\t\tif err = work.Trmm(Right, Lower, NoTrans, Unit, n, k, one, v.Off(0, m-k)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C2 := C2 - W**H\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= n; i++ {\n\t\t\t\t\t\tc.Set(m-k+j-1, i-1, c.Get(m-k+j-1, i-1)-work.GetConj(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t} else if side == Right {\n\t\t\t\t// Form C * H or C * H**H where C = ( C1 C2 )\n\t\t\t\t//\n\t\t\t\t// W := C * V**H = (C1*V1**H + C2*V2**H) (stored in WORK)\n\t\t\t\t//\n\t\t\t\t// W := C2\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\twork.Off(0, j-1).CVector().Copy(m, c.Off(0, n-k+j-1).CVector(), 1, 1)\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2**H\n\t\t\t\tif err = work.Trmm(Right, Lower, ConjTrans, Unit, m, k, one, v.Off(0, n-k)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\t\t\t\tif n > k {\n\t\t\t\t\t// W := W + C1 * V1**H\n\t\t\t\t\tif err = work.Gemm(NoTrans, ConjTrans, m, k, n-k, one, c, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * T or W * T**H\n\t\t\t\tif err = work.Trmm(Right, Lower, trans, NonUnit, m, k, one, t); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C := C - W * V\n\t\t\t\tif n > k {\n\t\t\t\t\t// C1 := C1 - W * V1\n\t\t\t\t\tif err = c.Gemm(NoTrans, NoTrans, m, n-k, k, -one, work, v, one); err != nil {\n\t\t\t\t\t\tpanic(err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// W := W * V2\n\t\t\t\tif err = work.Trmm(Right, Lower, NoTrans, Unit, m, k, one, v.Off(0, n-k)); err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\t// C1 := C1 - W\n\t\t\t\tfor j = 1; j <= k; j++ {\n\t\t\t\t\tfor i = 1; i <= m; i++ {\n\t\t\t\t\t\tc.Set(i-1, n-k+j-1, c.Get(i-1, n-k+j-1)-work.Get(i-1, j-1))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\n\t\t}\n\t}\n}", "func MToF(m Meter) Foot { return Foot(m / 0.3048) }", "func lagrangeInterp(k, n, m int, x []float64) float64 {\n\tretval := 1.0\n\tq := x[k]\n\n\tfor l := 1; l <= m; l++ {\n\t\tfor j := l; j <= n; j += m {\n\t\t\tif j != k {\n\t\t\t\tretval *= 2.0 * (q - x[j])\n\t\t\t}\n\t\t}\n\t}\n\treturn 1.0 / retval\n}", "func rbl(rate decimal.Decimal, per int64, pmt decimal.Decimal, pv decimal.Decimal, when paymentperiod.Type) decimal.Decimal {\n\treturn Fv(rate, per-1, pmt, pv, when)\n}", "func (z *Big) Modf(x *Big) (int *Big, frac *Big) {\n\tint = z\n\tfrac = new(Big)\n\n\tif x.form == zero {\n\t\tz.form = zero\n\t\tfrac.form = zero\n\t\treturn z, frac\n\t}\n\n\tif x.form == inf {\n\t\tz.form = inf\n\t\tfrac.form = inf\n\t\treturn z, frac\n\t}\n\n\tz.ctx = x.ctx\n\tz.form = finite\n\n\t// Needs proper scale.\n\t// Set frac before z in case z aliases x.\n\tfrac.scale = x.scale\n\tfrac.ctx = x.ctx\n\tfrac.form = finite\n\n\tif x.IsInt() {\n\t\tif x.isCompact() {\n\t\t\tz.compact = x.compact\n\t\t} else {\n\t\t\tz.mantissa.Set(&x.mantissa)\n\t\t}\n\t\tz.scale = 0\n\t\treturn z, frac\n\t}\n\n\tif x.isCompact() {\n\t\ti, f, ok := mod(x.compact, x.scale)\n\t\tif ok {\n\t\t\tz.compact, frac.compact = i, f\n\t\t\tz.scale = 0\n\t\t\treturn z, frac\n\t\t}\n\t}\n\n\tm := &x.mantissa\n\t// Possible fallthrough.\n\tif x.isCompact() {\n\t\tm = big.NewInt(x.compact)\n\t}\n\ti, f := modbig(m, x.scale)\n\tz.compact = c.Inflated\n\tfrac.compact = c.Inflated\n\tz.mantissa.Set(i)\n\tfrac.mantissa.Set(f)\n\tz.scale = 0\n\treturn z, frac\n}", "func NewLPSolver(tighten TightenMode) *LPSolver {\n\treturn &LPSolver{SortMatrix: true,\n\t\tSortClauses: true,\n\t\tRegTest: true,\n\t\tTighten: tighten,\n\t}\n}", "func FMod(arg float64, arg2 float64) float64 {\n\tflooRit := Floor(arg / arg2)\n\treturn arg - (flooRit * arg2)\n}", "func MToF(m Meter) Feet { return Feet(m / 0.3048) }", "func ReLUDerivative(y float64) float64 {\n\tif y == 0 {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func (f *Float) RelDiff(x, y *Float) *Float {\n\tx.doinit()\n\ty.doinit()\n\tf.doinit()\n\tC.mpf_reldiff(&f.i[0], &x.i[0], &y.i[0])\n\treturn f\n}", "func Lte(a, b interface{}, opts ...FuncOpt) (retVal Tensor, err error) {\n\tad, adok := a.(*Dense)\n\tbd, bdok := b.(*Dense)\n\tswitch {\n\tcase adok && bdok:\n\t\treturn ad.lteDD(bd, opts...)\n\tcase adok && !bdok:\n\t\treturn ad.lteDS(b, opts...)\n\tcase !adok && bdok:\n\t\treturn bd.gteDS(a, opts...)\n\t}\n\n\tpanic(\"unreachable\")\n}", "func Vflt8(input []int8, inputStride int, output []float32, outputStride int) {\n\tC.vDSP_vflt8((*C.char)(&input[0]), C.vDSP_Stride(inputStride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), minLen(len(input)/inputStride, len(output)/outputStride))\n}", "func (ta *TA) Ln() *TA {\n\treturn ta.Mapf(math.Log, false)\n}", "func (fn *formulaFuncs) FdotINVdotRT(argsList *list.List) formulaArg {\n\targs := fn.prepareFinvArgs(\"F.INV.RT\", argsList)\n\tif args.Type != ArgList {\n\t\treturn args\n\t}\n\tprobability, d1, d2 := args.List[0], args.List[1], args.List[2]\n\treturn newNumberFormulaArg((1/calcBetainv(1-(1-probability.Number), d2.Number/2, d1.Number/2, 0, 1) - 1) * (d2.Number / d1.Number))\n}", "func (f Float) Lead() int {\n\treturn int(f.m >> 63)\n}", "func MakeLowPass(h []float64, wf window.Func, cutoff float64) {\n\tn := len(h)\n\tfor i := range h {\n\t\tx := 2 * math.Pi * cutoff\n\t\tif i == n/2 {\n\t\t\th[i] = x\n\t\t} else {\n\t\t\ty := float64(i) - float64(n)/2\n\t\t\th[i] = (math.Sin(x*y) / y) * wf(float64(i), n)\n\t\t}\n\t}\n\tnormalize(h)\n}", "func LeFn(a interface{}, b interface{}) bool {\n\treturn a.(float64) <= b.(float64)\n}", "func Ldx(c *CPU) {\n\tc.ApplyNZ(c.EffVal)\n\tc.X = c.EffVal\n}", "func (c *Clac) Lg() error {\n\treturn c.applyFloat(1, func(vals []value.Value) (value.Value, error) {\n\t\treturn binary(value.Int(2), \"log\", vals[0])\n\t})\n}", "func lufactor(a [][]float64, ipvt []int) bool {\n\tn := len(a)\n\n\t// check if singular matrix\n\tif isfilled(a, 0) {\n\t\treturn false\n\t}\n\n\t// crout method\n\tfor j := 0; j != n; j++ {\n\t\t// calculate upper triangular for this column\n\t\tfor i := 0; i != j; i++ {\n\t\t\tq := a[i][j]\n\t\t\tfor k := 0; k != i; k++ {\n\t\t\t\tq -= a[i][k] * a[k][j]\n\t\t\t}\n\t\t\ta[i][j] = q\n\t\t}\n\n\t\t// calculate lower triangular for this column\n\t\tL := 0.0\n\t\tR := -1\n\t\tfor i := j; i != n; i++ {\n\t\t\tq := a[i][j]\n\t\t\tfor k := 0; k != j; k++ {\n\t\t\t\tq -= a[i][k] * a[k][j]\n\t\t\t}\n\t\t\ta[i][j] = q\n\t\t\tx := math.Abs(q)\n\t\t\tif x >= L {\n\t\t\t\tL = x\n\t\t\t\tR = i\n\t\t\t}\n\t\t}\n\n\t\t// pivot\n\t\tif j != R {\n\t\t\tfor k := 0; k != n; k++ {\n\t\t\t\ta[R][k], a[j][k] = a[j][k], a[R][k]\n\t\t\t}\n\t\t}\n\n\t\t// keep track of row interchanges and avoid zeroes\n\t\tipvt[j] = R\n\t\tif a[j][j] == 0 {\n\t\t\ta[j][j] = 1e-18\n\t\t}\n\n\t\tif j != n-1 {\n\t\t\tm := 1.0 / a[j][j]\n\t\t\tfor i := j + 1; i != n; i++ {\n\t\t\t\ta[i][j] *= m\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func r_lux(Hstar, fo float64, iSeason, iLandUse int,\n\train, dew, isSO2, isO3 bool) float64 {\n\tvar rlux float64\n\tif dew && iSeason != 3 { // Dew doesn't have any effect in the winter\n\t\tif isSO2 {\n\t\t\tif iLandUse == 0 {\n\t\t\t\trlux = 50. // equation 13 and a half\n\t\t\t} else {\n\t\t\t\trlux = 100. // equation 10.\n\t\t\t}\n\t\t} else if isO3 {\n\t\t\t// equation 11\n\t\t\trlux = 1. / (1./3000. + 1./(3*r_lu[iSeason][iLandUse]))\n\t\t} else {\n\t\t\trluO := 1. / (1./3000. + 1./(3*r_lu[iSeason][iLandUse])) // equation 11\n\t\t\trlux = 1. / (1./(3*r_lu[iSeason][iLandUse]/(1.e-5*Hstar+fo)) + 1.e-7*Hstar +\n\t\t\t\tfo/rluO) // equation 14, modified to match Walmsley eq. 5g\n\t\t}\n\t} else if rain && iSeason != 3 {\n\t\tif isSO2 {\n\t\t\tif iLandUse == 0 {\n\t\t\t\trlux = 50 // equation 13 and a half\n\t\t\t} else {\n\t\t\t\t// equation 12\n\t\t\t\trlux = 1. / (1./5000. + 1./(3*r_lu[iSeason][iLandUse]))\n\t\t\t}\n\t\t} else if isO3 {\n\t\t\t// equation 13\n\t\t\trlux = 1. / (1./1000. + 1./(3*r_lu[iSeason][iLandUse]))\n\t\t} else {\n\t\t\trluO := 1. / (1./1000. + 1./(3*r_lu[iSeason][iLandUse])) // equation 13\n\t\t\trlux = 1. / (1./(3*r_lu[iSeason][iLandUse]/(1.e-5*Hstar+fo)) + 1.e-7*Hstar +\n\t\t\t\tfo/rluO) // equation 14, modified to match Walmsley eq. 5g\n\t\t}\n\t} else {\n\t\trlux = r_lu[iSeason][iLandUse] / (1.e-5*Hstar + fo)\n\t}\n\treturn rlux\n}", "func (f RatingFilter) Lte(value float64) (exp Filter) {\n\treturn Filter{\n\t\texpression: \"rating <= ?\",\n\t\targs: []interface{}{value},\n\t}\n}", "func LogNormalQtl(μ, σ float64) func(p float64) float64 {\n\treturn func(p float64) float64 {\n\t\treturn exp(σ*ZQtlFor(p) + μ)\n\t}\n}", "func (fn *formulaFuncs) LN(argsList *list.List) formulaArg {\n\tif argsList.Len() != 1 {\n\t\treturn newErrorFormulaArg(formulaErrorVALUE, \"LN requires 1 numeric argument\")\n\t}\n\tnumber := argsList.Front().Value.(formulaArg).ToNumber()\n\tif number.Type == ArgError {\n\t\treturn number\n\t}\n\treturn newNumberFormulaArg(math.Log(number.Number))\n}", "func FloatSqrt(z *big.Float, x *big.Float,) *big.Float", "func Mltp(r [3]float64, c float64) (result [3]float64) {\n result[0] = r[0] * c\n result[1] = r[1] * c\n result[2] = r[2] * c\n\n return result\n}", "func (bl *Blend) Lum(rgb Color) float64 {\r\n\treturn 0.3*rgb.R + 0.59*rgb.G + 0.11*rgb.B\r\n}", "func newton(f []int, f_length int, x, xtol, ftol float64, itermax int) float64{\n fx := feval(f, f_length, x)\n var df = deriv(f, f_length);\n var root float64\n var fdx float64;\n var d float64;\n if abs(fx) <= ftol {\n root = x\n } else{\n for i := 1; i < itermax; i++ {\n fdx = feval(df, f_length-1, x)\n d = float64(fx)/fdx;\n x = x - d\n fx = feval(f, f_length, x)\n if (abs(d) <= xtol) || (abs(fx) <= ftol) {\n root = x\n break\n }\n }\n }\n return root\n}", "func powerf3(x float64, n int) float64 {\n\tans := 1.0\n\n\tfor n != 0 {\n\t\t\tans *= x\n\t\t\tn--\n\t}\n\treturn ans\n}", "func fqSqrt(c, u, v *Fq, s int) {\n\tt0, t1, t, r := &Fp{}, &Fp{}, &Fp{}, &Fp{}\n\ta, b, g := &Fp{}, &Fp{}, &Fp{}\n\n\t// a = u0*v0 + u1*v1\n\tfpMul(a, &u[0], &v[0])\n\tfpMul(t0, &u[1], &v[1])\n\tfpAdd(a, a, t0)\n\n\t// b = v0^2 + v1^2\n\tfpSqr(b, &v[0])\n\tfpSqr(t0, &v[1])\n\tfpAdd(b, b, t0)\n\n\t// g = u1*v0 - u0*v1\n\tfpMul(g, &u[1], &v[0])\n\tfpMul(t0, &u[0], &v[1])\n\tfpSub(g, g, t0)\n\n\t// t = 2(a + sqrt(a^2+g^2)) = 2*(a + (a^2+g^2)^(2^125))\n\t// if t=0; then t = 2*(a - (a^2+g^2)^(2^125))\n\tfpSqr(t0, a)\n\tfpSqr(t1, g)\n\tfpAdd(t0, t0, t1)\n\tfor i := 0; i < 125; i++ {\n\t\tfpSqr(t0, t0)\n\t}\n\tfpAdd(t, a, t0)\n\tif t.isZero() {\n\t\tfpSub(t, a, t0)\n\t}\n\tfpAdd(t, t, t)\n\n\t// r = (t*b^3)^(2^125-1)\n\tfpSqr(r, b)\n\tfpMul(r, r, b)\n\tfpMul(r, r, t)\n\tfpTwo1251(r, r)\n\n\t// x0 = (r*b*t)/2\n\t// x1 = (r*b*g)\n\tfpMul(&c[1], r, b)\n\tfpMul(&c[0], &c[1], t)\n\tfpHlf(&c[0], &c[0])\n\tfpMul(&c[1], &c[1], g)\n\n\t// if b*(2*x0)^2 == t then (x0,x1) <- (x1,x0)\n\tfpAdd(t0, &c[0], &c[0])\n\tfpSqr(t0, t0)\n\tfpMul(t0, t0, b)\n\tfpSub(t0, t0, t)\n\tif !t0.isZero() {\n\t\t*t0 = c[0]\n\t\tc[0] = c[1]\n\t\tc[1] = *t0\n\t}\n\n\tif fqSgn(c) != s {\n\t\tfqNeg(c, c)\n\t}\n}", "func Erf(x float64) float64 {\n\t// Constants\n\ta1 := 0.254829592\n\ta2 := -0.284496736\n\ta3 := 1.421413741\n\ta4 := -1.453152027\n\ta5 := 1.061405429\n\tp := 0.3275911\n\n\t// Save the sign of x\n\tvar sign float64\n\tif x < 0.0 {\n\t\tsign = -1.0\n\t} else {\n\t\tsign = 1.0\n\t}\n\tx = math.Abs(x)\n\n\t// Formula 7.1.26 given in Abramowitz and Stegun\n\tt := 1.0 / (1.0 + p*x)\n\ty := 1.0 - ((((a5*t+a4)*t+a3)*t+a2)*t+a1)*t*math.Pow(math.E, -x*x)\n\treturn sign * y\n}", "func lerp(a, b, t float64) float64 {\n\treturn (1.0-t)*a + t*b\n}", "func ExampleAdaptiveZoneFlt() {\n\tvar processed []float64\n\tsignal := []float64{0.1, 0.23, 0.44, 0.25, 0.33, 0.72, 0.48, 0.26, 0.15, 0.3}\n\tfor _, v := range signal {\n\t\tprocessed = append(processed, AdaptiveZoneFlt(v, 1.16724, 80.0, 20.0))\n\t}\n\tfmt.Println(processed)\n}", "func (o Mul) F(t float64, x []float64) float64 {\n\tif o.Fa != nil && o.Fb != nil {\n\t\treturn o.Fa.F(t, x) * o.Fb.F(t, x)\n\t}\n\tchk.Panic(\"mul: fa and fb functions are <nil>\\n\")\n\treturn 0\n}", "func lexFloatStart(lx *lexer) stateFn {\r\n\tr := lx.next()\r\n\tif !unicode.IsDigit(r) {\r\n\t\treturn lx.errorf(\"Floats must have a digit after the '.', but got \"+\r\n\t\t\t\"'%v' instead.\", r)\r\n\t}\r\n\treturn lexFloat\r\n}", "func logrelerr(x float64) float64 {\n\talnrcs := []float64{\n\t\t0.10378693562743769800686267719098e+1, -0.13364301504908918098766041553133,\n\t\t0.19408249135520563357926199374750e-1, -0.30107551127535777690376537776592e-2,\n\t\t0.48694614797154850090456366509137e-3, -0.81054881893175356066809943008622e-4,\n\t\t0.13778847799559524782938251496059e-4, -0.23802210894358970251369992914935e-5,\n\t\t0.41640416213865183476391859901989e-6, -0.73595828378075994984266837031998e-7,\n\t\t0.13117611876241674949152294345011e-7, -0.23546709317742425136696092330175e-8,\n\t\t0.42522773276034997775638052962567e-9, -0.77190894134840796826108107493300e-10,\n\t\t0.14075746481359069909215356472191e-10, -0.25769072058024680627537078627584e-11,\n\t\t0.47342406666294421849154395005938e-12, -0.87249012674742641745301263292675e-13,\n\t\t0.16124614902740551465739833119115e-13, -0.29875652015665773006710792416815e-14,\n\t\t0.55480701209082887983041321697279e-15, -0.10324619158271569595141333961932e-15,\n\t\t0.19250239203049851177878503244868e-16, -0.35955073465265150011189707844266e-17,\n\t\t0.67264542537876857892194574226773e-18, -0.12602624168735219252082425637546e-18,\n\t\t0.23644884408606210044916158955519e-19, -0.44419377050807936898878389179733e-20,\n\t\t0.83546594464034259016241293994666e-21, -0.15731559416479562574899253521066e-21,\n\t\t0.29653128740247422686154369706666e-22, -0.55949583481815947292156013226666e-23,\n\t\t0.10566354268835681048187284138666e-23, -0.19972483680670204548314999466666e-24,\n\t\t0.37782977818839361421049855999999e-25, -0.71531586889081740345038165333333e-26,\n\t\t0.13552488463674213646502024533333e-26, -0.25694673048487567430079829333333e-27,\n\t\t0.48747756066216949076459519999999e-28, -0.92542112530849715321132373333333e-29,\n\t\t0.17578597841760239233269760000000e-29, -0.33410026677731010351377066666666e-30,\n\t\t0.63533936180236187354180266666666e-31,\n\t}\n\tnlnrel := chebyshevInit(43, 0.1*d1mach(3), alnrcs)\n\tif x <= -1 {\n\t\treturn math.NaN()\n\t}\n\tif math.Abs(x) <= 0.375 {\n\t\treturn x * (1.0 - x*chebyshevEval(nlnrel, x/0.375, alnrcs))\n\t}\n\treturn math.Log(x + 1.0)\n}", "func mod(fr int64, scale int32) (dec int64, frac int64, ok bool) {\n\tif fr < 0 {\n\t\tdec, frac, ok = mod(-fr, scale)\n\t\treturn -dec, -frac, ok\n\t}\n\texp, ok := pow.Ten64(int64(scale))\n\tif !ok {\n\t\treturn 0, 0, false\n\t}\n\tif exp == 0 {\n\t\treturn fr, 0, true\n\t}\n\tdec = fr / exp\n\tfrac = fr - (dec * exp)\n\treturn dec, frac, true\n}", "func KToF(k Kelvin) Fahrenheit { return Fahrenheit((k-273.15)*9.0/5.0 + 32.0) }", "func naiveDFTreal(x []float64) (y []complex128) {\n\ty = make([]complex128, len(x))\n\tdt := -2 * math.Pi / float64(len(x))\n\tfor i := range x {\n\t\targ1 := float64(i) * dt\n\t\tfor k, xv := range x {\n\t\t\targ2 := float64(k) * arg1\n\t\t\ty[i] += complex(xv*math.Cos(arg2), xv*math.Sin(arg2))\n\t\t}\n\t}\n\treturn y[:len(x)/2+1]\n}", "func NewLeafListFloatTv(values []float32) *TypedValue {\n\treturn (*TypedValue)(newLeafListFloat(values))\n}", "func (r *ImageRef) Linear(a, b []float64) error {\n\tif len(a) != len(b) {\n\t\treturn errors.New(\"a and b must be of same length\")\n\t}\n\n\tout, err := vipsLinear(r.image, a, b, len(a))\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (b *Builder) Lt(rhs interface{}) *predicate.Predicate {\n\tb.p.RegisterPredicate(impl.Lt(rhs))\n\tif b.t != nil {\n\t\tb.t.Helper()\n\t\tEvaluate(b)\n\t}\n\treturn &b.p\n}", "func (f Fixed) Frac() float64 {\n\tif f.IsNaN() {\n\t\treturn math.NaN()\n\t}\n\treturn float64(f.fp%scale) / float64(scale)\n}", "func (f Fixed) Frac() float64 {\n\tif f.IsNaN() {\n\t\treturn math.NaN()\n\t}\n\treturn float64(f.fp%scale) / float64(scale)\n}", "func _fload(frame *runtime.Frame, index uint) {\n\tval := frame.GetFloat(index)\n\tframe.PushFloat(val)\n}", "func Lerp(a, b Vec, t float64) Vec {\n\treturn a.Scaled(1 - t).Add(b.Scaled(t))\n}", "func ForwardFeeLT(v float32) predicate.Order {\n\treturn predicate.Order(func(s *sql.Selector) {\n\t\ts.Where(sql.LT(s.C(FieldForwardFee), v))\n\t})\n}", "func KToF(k Kelvin) Fahrenheit { return CToF(KToC(k)) }" ]
[ "0.58512765", "0.55804515", "0.55368716", "0.5416149", "0.5291489", "0.52594036", "0.5106329", "0.50993097", "0.50679386", "0.50535303", "0.5043228", "0.50379205", "0.50364494", "0.5034372", "0.5010534", "0.49561793", "0.48973206", "0.48969325", "0.4883939", "0.48805177", "0.4874818", "0.47990984", "0.47963908", "0.4786462", "0.47768208", "0.47741604", "0.47647598", "0.47553778", "0.47515914", "0.4734394", "0.4726972", "0.4714841", "0.47126815", "0.47105432", "0.47014412", "0.46899232", "0.4681546", "0.46783194", "0.46758", "0.46631262", "0.4662778", "0.46600938", "0.46437258", "0.46389434", "0.46355093", "0.46342024", "0.46330574", "0.460759", "0.45879585", "0.458744", "0.4578507", "0.4546445", "0.45414603", "0.45390466", "0.4511195", "0.4502802", "0.45011717", "0.45009208", "0.45005435", "0.44861543", "0.44817", "0.44780505", "0.4473191", "0.44723228", "0.44574594", "0.44570988", "0.44551793", "0.4446606", "0.444138", "0.44365108", "0.44355437", "0.44342995", "0.4422002", "0.44210896", "0.44095102", "0.44089252", "0.4407392", "0.44043583", "0.44027054", "0.4399512", "0.4384036", "0.43765986", "0.43742287", "0.43639803", "0.43618146", "0.43595004", "0.4343318", "0.43423763", "0.43419763", "0.43387288", "0.43384597", "0.4337723", "0.4328932", "0.4327273", "0.43260753", "0.43260753", "0.43248388", "0.43125135", "0.43111193", "0.43072662" ]
0.74752563
0
Norm normalizes a point in the form (z, w) to the form z' or Infinity.
func (p *Point) Norm() { if p.W == 0 { p.Z = 1 } else { p.Z = p.Z / p.W p.W = 1 } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (p *Vect) Normalize() {\n\t// Neat trick I saw somewhere to avoid div/0.\n\tp.Mult(1.0 / (p.Length() + f.FloatMin))\n}", "func (a *Vector3) Normalise() {\n\tl := a.Length()\n\t*a = Vector3{a.X / l, a.Y / l, a.Z / l}\n}", "func (p Point) Normalize() Point {\n\treturn p.Scale(1.0 / math.Sqrt(p.Dot(p)))\n}", "func (v Vec3) Normalized() Vec3 {\n\tf := 1.0 / v.Norm()\n\treturn Vec3{f * v[0], f * v[1], f * v[2]}\n}", "func (v *Vector) Normalize() *Vector {\n\tl := v.Length()\n\treturn &Vector{X: v.X / l, Y: v.Y / l, Z: v.Z / l}\n}", "func Normalize(v Vect) Vect {\n\t// Neat trick I saw somewhere to avoid div/0.\n\treturn Mult(v, 1.0/(Length(v)+f.FloatMin))\n}", "func (etf *Etf) normalize(x, y, z float32) gocv.Vecf {\n\tnv := float32(math.Sqrt(float64(x*x) + float64(y*y) + float64(z*z)))\n\n\tif nv > 0.0 {\n\t\treturn gocv.Vecf{x * 1.0 / nv, y * 1.0 / nv, z * 1.0 / nv}\n\t}\n\treturn gocv.Vecf{0.0, 0.0, 0.0}\n}", "func (t *Tuple) Normalize() *Tuple {\n\tmag := t.Magnitude()\n\tif mag == 0.0 {\n\t\treturn t\n\t}\n\treturn Vector(t.x/mag, t.y/mag, t.z/mag)\n\n}", "func (a Vec4) Normalized() Vec4 {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W)\n\treturn Vec4{a.X / length, a.Y / length, a.Z / length, a.W / length}\n}", "func (t Tuple) Normalize() Tuple {\n\tv := t.Magnitude()\n\tif v == 0 {\n\t\tpanic(\"cannot normalize vector with 0 magnitude\")\n\t}\n\treturn Tuple{t.X / v, t.Y / v, t.Z / v, t.W / v}\n}", "func (v *Vector) Normalize() *Vector {\n\tw := snrm2(len(v.vec), v.vec)\n\tsscal(len(v.vec), 1/w, v.vec)\n\treturn v\n}", "func (v1 *Vec3f) Norm() {\n\tX := v1.X * v1.X\n\tY := v1.Y * v1.Y\n\tZ := v1.Z * v1.Z\n\n\tsum := X + Y + Z\n\troot := math.Sqrt(sum)\n\n\tv1.X /= root\n\tv1.Y /= root\n\tv1.Z /= root\n}", "func (s Sphere) Normal(p vector.Vec4) vector.Vec4 {\n\treturn vector.Subtract(&s.origin, &p)\n}", "func (a Vec2) Normalized() (v Vec2, ok bool) {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y)\n\tif Equal(length, 0) {\n\t\treturn Vec2Zero, false\n\t}\n\treturn Vec2{\n\t\ta.X / length,\n\t\ta.Y / length,\n\t}, true\n}", "func (v Quat) Normalize() Quat {\n\tl := v.Length()\n\tif l != 0 {\n\t\tv.W /= l\n\t\tv.X /= l\n\t\tv.Y /= l\n\t\tv.Z /= l\n\t}\n\treturn v\n}", "func (gdt *Vector3) Normalized() Vector3 {\n\targ0 := gdt.getBase()\n\n\tret := C.go_godot_vector3_normalized(GDNative.api, arg0)\n\n\treturn Vector3{base: &ret}\n\n}", "func (v *Vector) Normalize() *Vector {\n\n\tif v.X == 0 && v.Y == 0 {\n\t\treturn &Vector{\n\t\t\tX: 0, Y: 0,\n\t\t}\n\t}\n\tmag := v.Length()\n\tx := (v.X / mag)\n\ty := (v.Y / mag)\n\treturn &Vector{\n\t\tX: x,\n\t\tY: y,\n\t}\n}", "func Vec3Normalize(a Vec3) (v Vec3)", "func (v Vec) Normalize() Vec {\n\tmag := v.Mag()\n\treturn v.MapBy(func(i int, val float64) float64 { return val / mag })\n}", "func Normalize(t Tuplelike) Tuplelike {\n\treturn Divide(t, Magnitude(t))\n}", "func (vn *VecN) Normalize(dst *VecN) *VecN {\n\tif vn == nil {\n\t\treturn nil\n\t}\n\n\treturn vn.Mul(dst, 1/vn.Len())\n}", "func (t Torus) Norm(a Point) Point {\n\treturn Pt(wrap(a.X, t.W), wrap(a.Y, t.H))\n}", "func (pn Plane) NormalAtPoint(p rays.Point) rays.Ray {\n\treturn pn.normal\n}", "func (v Vec) Normalized() Vec {\n\treturn v.Copy().Normalize()\n}", "func (v Vec3) Normalize() Vec3 {\n\treturn v.Scale(1.0 / v.Magnitude())\n}", "func Normalize(v *Vec) *Vec {\n\treturn Divide(v, v.Magnitude())\n}", "func (s *Sphere) NormalAt(p Vector) Vector {\n\treturn p.Minus(s.Center).Normalize()\n}", "func norm(t, a, b float64) float64 {\n\treturn (t - a) * (1 / (b - a))\n}", "func (q Quat) Normalize() Quat {\n\tlength := q.Length()\n\tif length == 1 { // shortcut\n\t\treturn q\n\t}\n\treturn Quat{q.W / length, q.X / length, q.Y / length, q.Z / length}\n}", "func (p *Posting) Norm() float64 {\n\treturn float64(float32(1.0 / math.Sqrt(float64(math.Float32bits(p.norm)))))\n}", "func normalize(f *dump.Frame) {\n\ta := f.Vectors()\n\tfor i := range a[0] {\n\n\t\tfor j := range a[0][i] {\n\n\t\t\tfor k := range a[0][i][j] {\n\t\t\t\tx, y, z := a[0][i][j][k], a[1][i][j][k], a[2][i][j][k]\n\t\t\t\tnorm := math.Sqrt(float64(x*x + y*y + z*z))\n\t\t\t\tinvnorm := float32(1)\n\t\t\t\tif norm != 0 {\n\t\t\t\t\tinvnorm = float32(1 / norm)\n\t\t\t\t}\n\t\t\t\ta[0][i][j][k] *= invnorm\n\t\t\t\ta[1][i][j][k] *= invnorm\n\t\t\t\ta[2][i][j][k] *= invnorm\n\n\t\t\t}\n\t\t}\n\t}\n}", "func (u Vec) Normal() Vec {\n\treturn Vec{-u.Y, u.X}\n}", "func (sx ScaleX) Normalize(min, max, x float64) float64 {\n\ttXMin := sx(min)\n\treturn (sx(x) - tXMin) / (sx(max) - tXMin)\n}", "func mpnorm(a *Mpflt) {\n\tos := sigfig(a)\n\tif os == 0 {\n\t\t// zero\n\t\ta.Exp = 0\n\n\t\ta.Val.Neg = 0\n\t\treturn\n\t}\n\n\t// this will normalize to the nearest word\n\tx := a.Val.A[os-1]\n\n\ts := (Mpnorm - os) * Mpscale\n\n\t// further normalize to the nearest bit\n\tfor {\n\t\tx <<= 1\n\t\tif x&Mpbase != 0 {\n\t\t\tbreak\n\t\t}\n\t\ts++\n\t\tif x == 0 {\n\t\t\t// this error comes from trying to\n\t\t\t// convert an Inf or something\n\t\t\t// where the initial x=0x80000000\n\t\t\ts = (Mpnorm - os) * Mpscale\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t_Mpshiftfix(&a.Val, s)\n\tmpsetexp(a, int(a.Exp)-s)\n}", "func (v Vector) Normalize() (Vector, bool) {\n\tmag := v.Magnitude()\n\t// Zero-length vector has no direction and therefore can not be normalized\n\tif mag <= 0.0 {\n\t\treturn v, false\n\t}\n\treturn v.Scale(1.0 / mag), true\n}", "func (a *Vec4) Normalize() {\n\tlength := math.Sqrt(a.X*a.X + a.Y*a.Y + a.Z*a.Z + a.W*a.W)\n\ta.X /= length\n\ta.Y /= length\n\ta.Z /= length\n\ta.W /= length\n}", "func (v Vector2D) Normalize() Vector {\n\tlength := v.Length()\n\tv.X /= length\n\tv.Y /= length\n\treturn v\n}", "func (v Vec3) Norm() float32 {\n\treturn float32(math.Sqrt(float64(v.SquareNorm())))\n}", "func l2norm(w map[int]float64) float64 {\n sum := float64(0)\n for _, v := range w {\n sum += v * v\n }\n return math.Sqrt(sum)\n}", "func (v V) Norm() float32 {\n\tvar x2 float64\n\tfor _, x := range v {\n\t\tx2 += math.Pow(float64(x), 2)\n\t}\n\treturn Float32(math.Sqrt(x2))\n}", "func (v Vec3) SquareNorm() float32 {\n\treturn v[0]*v[0] + v[1]*v[1] + v[2]*v[2]\n}", "func NewStdNorm() (x *Norm){\n x = NewNorm(0.,1.)\n return\n}", "func Norm(a float64) float64 {\n\tif a > math.Pi {\n\t\ta -= math.Floor(a*IPi2)*Pi2 + Pi2\n\t} else if a < -math.Pi {\n\t\ta -= math.Ceil(a*IPi2)*Pi2 - Pi2\n\t}\n\treturn a\n}", "func Norm(v []float64) float64 {\n\treturn math.Sqrt(ScalarProduct(v, v))\n}", "func (v Vector2) Normalize() Vector2 {\n\treturn v.ScalarMultiply(1.0 / v.Length())\n}", "func (v *Vec4) Normalize() *Vec4{\n\tlenv := (gl.Float)(math.Sqrt((float64)(v.X*v.X + v.Y*v.Y + v.Z*v.Z)))\n\treturn &Vec4{ v.X / lenv, v.Y / lenv, v.Z / lenv, v.W }\n}", "func normalize(input []float64) []float64 {\n\t// gracefully handle empty inputs.\n\tif len(input) == 0 {\n\t\treturn input\n\t}\n\tmin, max := input[0], input[0]\n\tfor _, v := range input {\n\t\tif v > max {\n\t\t\tmax = v\n\t\t}\n\t\tif v < min {\n\t\t\tmin = v\n\t\t}\n\t}\n\tfor i, v := range input {\n\t\tinput[i] = (v - min) / (max - min)\n\t}\n\treturn input\n}", "func (v Vector) Normalize() Vector {\n\tnorm := v.Norm()\n\tif norm == 0 {\n\t\t// A 0 norm occurs iff a vector v is the 0 vector\n\t\treturn v\n\t}\n\treturn NewVector(v.X/norm, v.Y/norm, v.Z/norm)\n}", "func (self *Sax) normalize(measureList []float64) []float64 {\n var err error\n if len(measureList) < 1 {\n return measureList\n }\n\n s2 := float64(1)\n m2 := float64(0)\n m1 := mean(measureList)\n if err != nil {\n panic(err)\n }\n s1 := stdDev(measureList, m1)\n if err != nil {\n panic(err)\n }\n\n stdMultiplier := (s2 / s1)\n\n for i, m := range measureList {\n measureList[i] = float64(m2 + (m - m1)) * stdMultiplier\n }\n return measureList\n}", "func (pl *Plane) NormalAt(point *Tuple) Tuple {\n\tobNormal := Vector(0, 1, 0)\n\twNormal := pl.NormalToWorld(obNormal)\n\treturn *wNormal\n}", "func NormalExtrude(p V3) V2 {\n\treturn V2{p.X, p.Y}\n}", "func LPNorm(vector []float64, p float64) (float64, error) {\n\tdistance := 0.\n\tfor _, jj := range vector {\n\t\tdistance += math.Pow(math.Abs(jj), p)\n\t}\n\treturn math.Pow(distance, 1/p), nil\n}", "func NormalPDF(z float64) float64 {\n\treturn math.Exp(-math.Pow(z, 2)/2) / math.Sqrt(2*math.Pi)\n}", "func normalize(vals []float64) {\n\tvar mean float64\n\tallEqual := true\n\tfor _, x := range vals {\n\t\tif x != vals[0] {\n\t\t\tallEqual = false\n\t\t}\n\t\tmean += x\n\t}\n\n\tif allEqual {\n\t\tfor i := range vals {\n\t\t\tvals[i] = 0\n\t\t}\n\t\treturn\n\t}\n\n\tmean /= float64(len(vals))\n\n\tvar variance float64\n\tfor _, x := range vals {\n\t\tdiff := x - mean\n\t\tvariance += diff * diff\n\t}\n\tvariance /= float64(len(vals))\n\n\tscale := 1 / math.Sqrt(variance)\n\tfor i, x := range vals {\n\t\tvals[i] = (x - mean) * scale\n\t}\n}", "func NormalizedDistance(a, b []float32) (float32, error) {\n\tsim, err := cosineSim(a, b)\n\tif err != nil {\n\t\treturn 1, fmt.Errorf(\"normalized distance: %v\", err)\n\t}\n\n\treturn (1 - sim) / 2, nil\n}", "func Vnormalize(v Vect) Vect {\n\treturn goVect(C.cpvnormalize(v.c()))\n}", "func NormFloat64() float64 { return globalRand.NormFloat64() }", "func NormFloat64() float64 { return globalRand.NormFloat64() }", "func Vector3Normalize(v Vector3) Vector3 {\n\tresult := v\n\n\tvar length, ilength float32\n\n\tlength = Vector3Length(v)\n\n\tif length == 0 {\n\t\tlength = 1.0\n\t}\n\n\tilength = 1.0 / length\n\n\tresult.X *= ilength\n\tresult.Y *= ilength\n\tresult.Z *= ilength\n\n\treturn result\n}", "func (v Vector) Norm() float64 {\n\treturn math.Sqrt(v.Dot(v))\n}", "func (mu *MuHash) normalize() {\n\tmu.numerator.Divide(&mu.denominator)\n\tmu.denominator.SetToOne()\n}", "func randNorm(x float32) float32 {\n\tr := rand.Float32()*.2 + .9\n\tx *= r\n\tif x > 1 {\n\t\treturn 1\n\t}\n\treturn x\n}", "func (s *Solution) Normalize() *Solution {\n\tclone := s.Clone()\n\n\tfor i, _ := range clone.Weighings {\n\t\tclone.Weighings[i] = NewWeighing(clone.Weighings[i].Pan(0).Sort(), clone.Weighings[i].Pan(1).Sort())\n\t}\n\tclone.flags |= NORMALISED &^ (CANONICALISED)\n\treturn clone\n}", "func (o Orbit) VNorm() float64 {\n\treturn Norm(o.vVec)\n}", "func (v Vector2) Normalize() Vector {\r\n\tif v.Length() == 0 {\r\n\t\treturn Vector2d(rand.Float64(), rand.Float64())\r\n\t}\r\n\r\n\treturn v.MulScalar(1 / v.Length())\r\n}", "func (v Vec) Norm(degree float64) float64 {\n\tif degree <= 0.0 {\n\t\tpanic(fmt.Sprintf(\"Invalid non-positive norm degree: %v\", degree))\n\t}\n\ts := 0.0\n\t// Special case for plain sum\n\tif degree == 1.0 {\n\t\tfor _, val := range v {\n\t\t\ts += math.Abs(val)\n\t\t}\n\t\treturn s\n\t}\n\n\tfor _, val := range v {\n\t\ts += math.Pow(math.Abs(val), degree)\n\t}\n\treturn math.Pow(s, 1.0/degree)\n}", "func (sy ScaleY) Normalize(min, max, x float64) float64 {\n\ttYMin := sy(min)\n\treturn (sy(x) - tYMin) / (sy(max) - tYMin)\n}", "func (m mathUtil) Normalize(values ...float64) []float64 {\n\tvar total float64\n\tfor _, v := range values {\n\t\ttotal += v\n\t}\n\toutput := make([]float64, len(values))\n\tfor x, v := range values {\n\t\toutput[x] = m.RoundDown(v/total, 0.0001)\n\t}\n\treturn output\n}", "func (n *NoOpVectorizer) NormalizedDistance(a, b []float32) (float32, error) {\n\treturn 0, nil\n}", "func (b box) findNormal(point vector) vector {\n\tnormal := makeVector(0, 0, 0) //point.sub(b.center).direction()\n\tif math.Abs(point.x-b.min.x) < errorDelta {\n\t\tnormal = makeVector(-1, 0, 0)\n\t} else if math.Abs(point.x-b.max.x) < errorDelta {\n\t\tnormal = makeVector(1, 0, 0)\n\t} else if math.Abs(point.y-b.min.y) < errorDelta {\n\t\tnormal = makeVector(0, -1, 0)\n\t} else if math.Abs(point.y-b.max.y) < errorDelta {\n\t\tnormal = makeVector(0, 1, 0)\n\t} else if math.Abs(point.z-b.min.z) < errorDelta {\n\t\tnormal = makeVector(0, 0, -1)\n\t} else if math.Abs(point.z-b.max.z) < errorDelta {\n\t\tnormal = makeVector(0, 0, 1)\n\t} else {\n\t\tfmt.Println(\"Point not placed:\", math.Abs(point.x-b.min.x) < errorDelta)\n\t}\n\treturn normal\n}", "func QuaternionNormalize(q Quaternion) Quaternion {\n\tresult := q\n\n\tlength := QuaternionLength(q)\n\n\tif length != 0.0 {\n\t\tresult.X /= length\n\t\tresult.Y /= length\n\t\tresult.Z /= length\n\t\tresult.W /= length\n\t}\n\n\treturn result\n}", "func NewNorm(mu float64, sigma float64) (x *Norm){\n x = &Norm{Continuous{},mu,sigma}\n // Discrete.discreter self reference X\n // It allows to implement more general variables\n x.Continuous = Continuous{x}\n return\n}", "func Normal(a [100][100]float64, b [100]float64, m int32) {\n\tvar i, j int32\n\tvar big float64\n\n\tfor i = 0; i < m; i++ {\n\t\tbig = 0.0\n\n\t\tfor j = 0; j < m; j++ {\n\t\t\tif big < math.Abs(a[i][j]) {\n\t\t\t\tbig = math.Abs(a[i][j])\n\t\t\t}\n\t\t}\n\n\t\tfor j = 0; j < m; j++ {\n\t\t\ta[i][j] = a[i][j] / big\n\t\t}\n\n\t\tb[i] = b[i] / big\n\t}\n}", "func (b *BasicShape) NormalAt(geometry.Vector) geometry.Vector {\n\tpanic(\"NormalAt is not implemented for basic shape\")\n}", "func (q1 Quat) Normalize() Quat {\n\tlength := q1.Len()\n\n\tif FloatEqual(1, length) {\n\t\treturn q1\n\t}\n\tif length == 0 {\n\t\treturn QuatIdent()\n\t}\n\tif length == InfPos {\n\t\tlength = MaxValue\n\t}\n\n\treturn Quat{q1.W * 1 / length, q1.V.Mul(1 / length)}\n}", "func (tri *Triangle) Normalize() *Triangle {\n\tv1 := tri.Qe.Orig()\n\tv2 := tri.Qe.Dest()\n\tv3 := tri.Qe.RPrev().Dest()\n\n\tc21 := cmp.PointLess(v2, v1)\n\tc31 := cmp.PointLess(v3, v1)\n\tc32 := cmp.PointLess(v3, v2)\n\n\tif c21 == false && c31 == false {\n\t\t// the original is correct\n\t\treturn tri\n\t}\n\tif c31 && c32 {\n\t\treturn &Triangle{tri.Qe.RNext()}\n\t}\n\treturn &Triangle{tri.Qe.RPrev()}\n}", "func (z *Zone) Normalize() {\n\tz.Domain = Normalize(z.Domain)\n\tz.InfoURL = NormalizeURL(z.InfoURL)\n\tvar tags []string\n\ttags = append(tags, z.Tags...)\n\tz.Tags = NewSet(tags...).Values()\n\tz.NameServers = NormalizeDomains(z.NameServers)\n\tz.Wildcards = NormalizeDomains(z.Wildcards)\n\tz.subdomains = NormalizeDomains(z.subdomains)\n\tz.WhoisServer = Normalize(z.WhoisServer)\n\tz.WhoisURL = NormalizeURL(z.WhoisURL)\n\tz.normalizePolicies()\n\tz.normalizeLanguages()\n}", "func (k *Kernel) Normalized() ConvolutionMatrix {\n\tsum := absum(k)\n\tw := k.Width\n\th := k.Height\n\tnk := NewKernel(w, h)\n\n\t// avoid division by 0\n\tif sum == 0 {\n\t\tsum = 1\n\t}\n\n\tfor i := 0; i < w*h; i++ {\n\t\tnk.Matrix[i] = k.Matrix[i] / sum\n\t}\n\n\treturn nk\n}", "func (g *Group) LocalNormalAt(p *algebra.Vector, hit *Intersection) (*algebra.Vector, error) {\n\treturn nil, GroupNormalError(*g)\n}", "func NormalCDF(z float64) float64 {\n\treturn (1 + math.Erf(z/(math.Sqrt2))) / 2\n}", "func normalize(brightness uint) float64 {\n\treturn float64(brightness) / 100.0\n}", "func (x Norm) D(v float64) (f float64){\n // TODO : calculate me once forall and multiply me with 1/x.sigma...\n norm := 1./(x.sigma*math.Sqrt2*math.SqrtPi)\n exponentiate := -0.5*math.Pow((v-x.mu)/x.sigma,2)\n f = norm*math.Exp(exponentiate)\n return\n}", "func NewNormalizer() *Normalizer { return &Normalizer{Norm: \"l2\", Axis: 1} }", "func (z nat) divW(x nat, y Word) (q nat, r Word) {\n\tm := len(x)\n\tswitch {\n\tcase y == 0:\n\t\tpanic(\"division by zero\")\n\tcase y == 1:\n\t\tq = z.set(x) // result is x\n\t\treturn\n\tcase m == 0:\n\t\tq = z.make(0) // result is 0\n\t\treturn\n\t}\n\t// m > 0\n\tz = z.make(m)\n\tr = divWVW(z, 0, x, y)\n\tq = z.norm()\n\treturn\n}", "func (c *Capsule) NormalSDF(coord Coord) (Coord, float64) {\n\tvar n Coord\n\tres := c.genericSDF(coord, &n, nil)\n\treturn n, res\n}", "func Abs1(v Vertex) float64 {\n\treturn math.Sqrt(v.X*v.X + v.Y*v.Y)\n}", "func normalize(v byte) float64 {\n\n\treturn float64(v) / 255\n}", "func (q1 Quat) Norm() float32 {\n\treturn q1.Len()\n}", "func TruncatedNormal(scope *Scope, shape tf.Output, dtype tf.DataType, optional ...TruncatedNormalAttr) (output tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\tattrs := map[string]interface{}{\"dtype\": dtype}\n\tfor _, a := range optional {\n\t\ta(attrs)\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"TruncatedNormal\",\n\t\tInput: []tf.Input{\n\t\t\tshape,\n\t\t},\n\t\tAttrs: attrs,\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (t Torus) normPair(a, b Point) (Point, Point) {\n\ta = t.Norm(a)\n\tb.X = nearWrap(a.X, b.X, t.W)\n\tb.Y = nearWrap(a.Y, b.Y, t.H)\n\treturn a, b\n}", "func (m *LikelihoodStudentsT) Normalize() {\n\tmeanX, stdX := MeanStdMat(m.X)\n\tm.MeanX = meanX\n\tm.StdX = stdX\n\tmeanY, stdY := stat.MeanStdDev(m.Y, nil)\n\tm.MeanY = meanY\n\tm.StdY = stdY\n}", "func norminv(p float64) (float64, error) {\n\ta := map[int]float64{\n\t\t1: -3.969683028665376e+01, 2: 2.209460984245205e+02, 3: -2.759285104469687e+02,\n\t\t4: 1.383577518672690e+02, 5: -3.066479806614716e+01, 6: 2.506628277459239e+00,\n\t}\n\tb := map[int]float64{\n\t\t1: -5.447609879822406e+01, 2: 1.615858368580409e+02, 3: -1.556989798598866e+02,\n\t\t4: 6.680131188771972e+01, 5: -1.328068155288572e+01,\n\t}\n\tc := map[int]float64{\n\t\t1: -7.784894002430293e-03, 2: -3.223964580411365e-01, 3: -2.400758277161838e+00,\n\t\t4: -2.549732539343734e+00, 5: 4.374664141464968e+00, 6: 2.938163982698783e+00,\n\t}\n\td := map[int]float64{\n\t\t1: 7.784695709041462e-03, 2: 3.224671290700398e-01, 3: 2.445134137142996e+00,\n\t\t4: 3.754408661907416e+00,\n\t}\n\tpLow := 0.02425 // Use lower region approx. below this\n\tpHigh := 1 - pLow // Use upper region approx. above this\n\tif 0 < p && p < pLow {\n\t\t// Rational approximation for lower region.\n\t\tq := math.Sqrt(-2 * math.Log(p))\n\t\treturn (((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /\n\t\t\t((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil\n\t} else if pLow <= p && p <= pHigh {\n\t\t// Rational approximation for central region.\n\t\tq := p - 0.5\n\t\tr := q * q\n\t\tf1 := ((((a[1]*r+a[2])*r+a[3])*r+a[4])*r + a[5]) * r\n\t\tf2 := (b[1]*r + b[2]) * r\n\t\tf3 := ((math.Nextafter(f2, f2)+b[3])*r + b[4]) * r\n\t\tf4 := (math.Nextafter(f3, f3) + b[5]) * r\n\t\treturn (math.Nextafter(f1, f1) + a[6]) * q /\n\t\t\t(math.Nextafter(f4, f4) + 1), nil\n\t} else if pHigh < p && p < 1 {\n\t\t// Rational approximation for upper region.\n\t\tq := math.Sqrt(-2 * math.Log(1-p))\n\t\treturn -(((((c[1]*q+c[2])*q+c[3])*q+c[4])*q+c[5])*q + c[6]) /\n\t\t\t((((d[1]*q+d[2])*q+d[3])*q+d[4])*q + 1), nil\n\t}\n\treturn 0, errors.New(formulaErrorNUM)\n}", "func (a *AxisPosition) normalize(gtx layout.Context, axis layout.Axis, elements int, dimensioner Dimensioner) {\n\tif a.First < 0 {\n\t\ta.First = 0\n\t}\n\tif a.First > elements {\n\t\ta.First = elements - 1\n\t}\n\n\tconstraint := axis.Convert(gtx.Constraints.Max).X\n\tfor a.Offset < 0 && a.First > 0 {\n\t\ta.First--\n\t\tdim := dimensioner(axis, a.First, constraint)\n\t\ta.Offset += dim\n\t\ta.OffsetAbs += dim\n\t}\n\tif a.Offset < 0 {\n\t\ta.Offset = 0\n\t}\n\tfor a.Offset > dimensioner(axis, a.First, constraint) && a.First < elements-1 {\n\t\tdim := dimensioner(axis, a.First, constraint)\n\t\ta.First++\n\t\ta.Offset -= dim\n\t\ta.OffsetAbs += dim\n\t}\n}", "func normalize(val, oldMax, newMax int) int {\n\treturn int(float64(newMax) / float64(oldMax) * float64(val))\n}", "func NewNormal(lb int64, ub int64) *Normal {\n\treturn &Normal{\n\t\tImpl: distuv.Normal{\n\t\t\tMu: float64(lb + ub/2), // Mean of the normal distribution\n\t\t\tSigma: NormalSigma, // Standard deviation of the normal distribution\n\t\t},\n\t}\n}", "func TestNormalize(t *testing.T) {\n\tvar i uint\n\t// It makes no sense to normalize a zero vector, therefore we start at 1.\n\tfor i = 1; i < 100; i++ {\n\t\ta := makeRandomVector(i)\n\t\tb := Normalize(a)\n\n\t\tif b.Len() != float64(1) {\n\t\t\tt.Error(\"Normalization failed, vector doesn't have length 1.\")\n\t\t\tt.Logf(\"%f != 1\", b.Len())\n\t\t}\n\t}\n}", "func (k *ConvKernel) Normalize() {\n\tdiameter := k.Radius*2 + 1\n\tarea := diameter * diameter\n\tsum := float32(0)\n\tfor i := 0; i < area; i++ {\n\t\tsum += k.Kernel[i]\n\t}\n\n\t// only attempt to normalize if the sum is significantly\n\t// different from both zero and one.\n\tfSum := float64(sum)\n\tif (math.Abs(fSum) >= TOLERANCE) && (math.Abs(fSum-1.0) >= TOLERANCE) {\n\t\tfor i := 0; i < area; i++ {\n\t\t\tk.Kernel[i] /= sum // normalize by dividing each entry\n\t\t}\n\t}\n}", "func (p Pitch) Normalize() Pitch {\n\tif v, found := normalizedPitches[p]; found {\n\t\treturn v\n\t}\n\n\treturn p\n}", "func (a *Archive) tsNorm(timestamp int64) int64 {\n\tts := timestamp - (timestamp % a.Interval)\n\tif ts < timestamp {\n\t\tts += a.Interval\n\t}\n\treturn ts\n}", "func normalizeLat(latDeg float64) float64 {\n\tif latDeg >= -90 && latDeg <= 90 {\n\t\treturn latDeg\n\t}\n\toff := math.Abs(math.Mod(latDeg+90, 360))\n\tif off <= 180 {\n\t\treturn off - 90\n\t}\n\treturn (360 - off) - 90\n}" ]
[ "0.66640604", "0.6445196", "0.64385116", "0.6264954", "0.61577773", "0.6157405", "0.61462456", "0.6131998", "0.60935086", "0.6074688", "0.6061909", "0.60590535", "0.60422295", "0.60111094", "0.6008327", "0.59955215", "0.59912163", "0.5913502", "0.59132713", "0.58844364", "0.5863331", "0.5859794", "0.58077973", "0.5726639", "0.57188", "0.5675096", "0.5660285", "0.5648752", "0.5639733", "0.56351143", "0.5613925", "0.56076455", "0.5595849", "0.558803", "0.55856407", "0.5557063", "0.55110824", "0.55050576", "0.55032283", "0.54946274", "0.5484112", "0.5422652", "0.5417356", "0.5402917", "0.5402436", "0.5397096", "0.53956795", "0.53813297", "0.53642875", "0.5334575", "0.53133994", "0.529814", "0.52886146", "0.5236814", "0.51962227", "0.51918906", "0.51886654", "0.51886654", "0.5184895", "0.51806885", "0.5179765", "0.5171432", "0.5154185", "0.51319695", "0.5123163", "0.5071903", "0.50575244", "0.504358", "0.5040178", "0.5022585", "0.5014015", "0.49779367", "0.4956959", "0.49547756", "0.49508592", "0.49217772", "0.49165067", "0.48805952", "0.4865115", "0.48612344", "0.48474273", "0.48345256", "0.4812351", "0.47564125", "0.47535753", "0.47455925", "0.47262052", "0.4718501", "0.4717632", "0.47174016", "0.4717051", "0.47067702", "0.4702858", "0.46854037", "0.46734038", "0.4661876", "0.46461296", "0.46390787", "0.46386382", "0.46305752" ]
0.7175584
0
NewVoxel returns a new initialized voxel
func NewVoxel() *Voxel { return &Voxel{allCanIntersect: true} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func New(x, y, z float64) *Vector {\n\treturn &Vector{Scalar(x), Scalar(y), Scalar(z)}\n}", "func NewV(d int) *V {\n\tif d <= 0 {\n\t\tpanic(ErrDim)\n\t}\n\treturn &V{Data: make([]float64, d)}\n}", "func NewUniverse() Universe {\n\tu := make(Universe, height) //15\n\tfor i := range u {\n\t\tu[i] = make([]bool, width) //80\n\n\t}\n\treturn u\n}", "func newCube(part *vu.Ent, x, y, z, cubeSize float64) *cube {\n\tc := &cube{}\n\tc.part = part.AddPart()\n\tc.cells = []*vu.Ent{}\n\tc.cx, c.cy, c.cz, c.csize = x, y, z, cubeSize\n\tc.ccnt, c.cmax = 0, 8\n\tc.mergec = func() { c.merge() }\n\tc.trashc = func() { c.trash() }\n\tc.addc = func() { c.addCell() }\n\tc.remc = func() { c.removeCell() }\n\n\t// calculate the cell center locations (unsorted)\n\tqs := c.csize * 0.25\n\tc.centers = csort{\n\t\t&lin.V3{X: x - qs, Y: y - qs, Z: z - qs},\n\t\t&lin.V3{X: x - qs, Y: y - qs, Z: z + qs},\n\t\t&lin.V3{X: x - qs, Y: y + qs, Z: z - qs},\n\t\t&lin.V3{X: x - qs, Y: y + qs, Z: z + qs},\n\t\t&lin.V3{X: x + qs, Y: y - qs, Z: z - qs},\n\t\t&lin.V3{X: x + qs, Y: y - qs, Z: z + qs},\n\t\t&lin.V3{X: x + qs, Y: y + qs, Z: z - qs},\n\t\t&lin.V3{X: x + qs, Y: y + qs, Z: z + qs},\n\t}\n\treturn c\n}", "func New(opts ...Option) *Vox {\n\tv := &Vox{\n\t\tcb: nil,\n\t\tholdTime: time.Millisecond * 500,\n\t\tthreshold: 0.1,\n\t\tlastActivation: time.Time{},\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(v)\n\t}\n\n\treturn v\n}", "func Identity(v magica.VoxelObject) (r magica.VoxelObject) {\n\tr = v.Copy()\n\treturn r\n}", "func NewWhite() Vector3 {\n\treturn New(1, 1, 1)\n}", "func NewUniverse() Universe {\n\tu := (make(Universe, height))\n\tfor row := range u {\n\t\tu[row] = make([]bool, width)\n\t}\n\treturn u\n}", "func NewUniverse() Universe {\n\tu := make(Universe, height)\n\tfor i := range u {\n\t\tu[i] = make([]bool, width)\n\t}\n\treturn u\n}", "func RotateAndTile(v magica.VoxelObject, angle float64, xOffset, yOffset int, scale geometry.PointF, boundingVolume BoundingVolume) (r magica.VoxelObject) {\n\tradians := (angle * math.Pi) / 180\n\n\t// If no bounding volume was supplied default to (0,0,0)-(max, max, max)\n\tif (boundingVolume.Max == geometry.Point{}) {\n\t\tboundingVolume.Max = geometry.Point{X: v.Size.X, Y: v.Size.Y, Z: v.Size.Z}\n\t}\n\n\t// If no scale is supplied default to (1,1,1)\n\tif (scale == geometry.PointF{}) {\n\t\tscale = geometry.PointF{X: 1, Y: 1, Z: 1}\n\t}\n\n\tr = v.Copy()\n\n\tbvx := boundingVolume.Max.X - boundingVolume.Min.X\n\tbvy := boundingVolume.Max.Y - boundingVolume.Min.Y\n\tbvz := boundingVolume.Max.Z - boundingVolume.Min.Z\n\n\t// Clear the object\n\titerator := func(x, y, z int) {\n\t\tr.Voxels[x][y][z] = 0\n\t}\n\n\tr.Iterate(iterator)\n\n\t// RotateAndTile the output\n\titerator = func(x, y, z int) {\n\t\tsx := ((bvx + xOffset + int((float64(x)*math.Cos(radians)-float64(y)*math.Sin(radians))*scale.X)) % bvx) + boundingVolume.Min.X\n\t\tsy := ((bvy + yOffset + int((float64(x)*math.Sin(radians)+float64(y)*math.Cos(radians))*scale.Y)) % bvy) + boundingVolume.Min.Y\n\t\tsz := ((z + bvz) % bvz) + boundingVolume.Min.Z\n\n\t\tif r.Voxels[x][y][z] == 0 && sx >= 0 && sy >= 0 && sx < v.Size.X && sy < v.Size.Y {\n\t\t\tr.Voxels[x][y][z] = v.Voxels[sx][sy][sz]\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func V(x, y f.Float) Vect { return Vect{x, y} }", "func New(size int) Vec {\n\treturn Vec(make([]float64, size))\n}", "func newEutranVector(rand, xres, autn, kasme []byte) *EutranVector {\n\tvar eutran = &EutranVector{}\n\tcopy(eutran.Rand[:], rand)\n\tcopy(eutran.Xres[:], xres)\n\tcopy(eutran.Autn[:], autn)\n\tcopy(eutran.Kasme[:], kasme)\n\treturn eutran\n}", "func InitNew() {\n\tPos = image.Point{}\n}", "func NewVoxelBlockIndexByCoord(blockCoord string) []byte {\n\tsz := len(blockCoord)\n\tindex := make([]byte, 1+sz)\n\tindex[0] = byte(KeyVoxelBlock)\n\tcopy(index[1:], blockCoord)\n\treturn dvid.IndexBytes(index)\n}", "func NewGridUniverse(width, height int) Universe {\n\tgrid := createGrid(width, height)\n\tfor i := 0; i < (width * height / 4); i++ {\n\t\tgrid[rand.Intn(height)][rand.Intn(width)] = true\n\t}\n\treturn gridUniverse{\n\t\twidth: width,\n\t\theight: height,\n\t\tgrid: grid,\n\t}\n}", "func voxelize(bvi *bvInfo, zi int, ch chan<- voxelInfo) {\n\tbv := bvi.bv\n\tif err := bv.VoxelizeZ(bvi.mesh, zi); err != nil {\n\t\tlog.Printf(\"voxelize(%v): %v\", zi, err)\n\t\treturn\n\t}\n\n\tvType := \"cut\"\n\tif bvi.base {\n\t\tvType = \"base\"\n\t}\n\tlog.Printf(\"voxelize(%v): sending %v %v voxels to imager(%v)...\", zi, len(bv.WhiteVoxels), vType, zi)\n\n\tkeyFunc := func(k binvox.Key) {\n\t\tk.X += bvi.dx\n\t\tk.Y += bvi.dy\n\t\tk.Z += bvi.dz\n\t\tif zi != k.Z {\n\t\t\tlog.Fatalf(\"voxelize(%v): k{%v,%v,%v} does not match zi=%v\", zi, k.X, k.Y, k.Z, zi)\n\t\t}\n\t\tif k.X < 0 || k.Y < 0 || k.Z < 0 {\n\t\t\treturn // common for a cut to extend beyond the bounds of the base.\n\t\t}\n\t\tch <- voxelInfo{X: k.X, Y: k.Y, Base: bvi.base}\n\t}\n\tfor k := range bv.WhiteVoxels {\n\t\tkeyFunc(k)\n\t}\n\tfor k := range bv.ColorVoxels {\n\t\tkeyFunc(k)\n\t}\n}", "func NewVector(x, y, z float64) Vector {\n\treturn Vector{x, y, z, vectorW}\n}", "func NewVector(dim int) Vector {\n\treturn Vector{\n\t\tdim: dim,\n\t\tdata: map[int]float64{},\n\t}\n}", "func NewVector(newX uint, newY uint) *Vector {\n\treturn &Vector{X: newX, Y: newY}\n}", "func RotateY(v magica.VoxelObject, angle float64) (r magica.VoxelObject) {\n\tsin, cos := math.Sin(degToRad(angle)), math.Cos(degToRad(angle))\n\n\torgMidpointX := float64(v.Size.X) / 2\n\torgMidpointZ := float64(v.Size.Z) / 2\n\n\txVector := (orgMidpointX * math.Abs(cos)) + (orgMidpointZ * math.Abs(sin))\n\tzVector := (orgMidpointX * math.Abs(sin)) + (orgMidpointZ * math.Abs(cos))\n\n\tsizeX, sizeZ := int(math.Ceil(xVector*2)), int(math.Ceil(zVector*2))\n\n\tr = magica.VoxelObject{\n\t\tVoxels: nil,\n\t\tPaletteData: v.PaletteData,\n\t\tSize: geometry.Point{X: sizeX, Y: v.Size.Y, Z: sizeZ},\n\t}\n\n\t// Create the voxel array\n\tr.Voxels = make([][][]byte, r.Size.X)\n\tfor x := 0; x < r.Size.X; x++ {\n\t\tr.Voxels[x] = make([][]byte, r.Size.Y)\n\t\tfor y := 0; y < r.Size.Y; y++ {\n\t\t\tr.Voxels[x][y] = make([]byte, r.Size.Z)\n\t\t}\n\t}\n\n\tvMidpointX := float64(v.Size.X) / 2\n\tvMidpointZ := float64(v.Size.Z) / 2\n\n\titerator := func(x, y, z int) {\n\n\t\tfdx := float64(x) - (float64(r.Size.X) / 2)\n\t\tfdz := float64(z) - (float64(r.Size.Z) / 2)\n\n\t\tfdx, fdz = (fdx*cos)+(fdz*sin), (fdx*-sin)+(fdz*cos)\n\n\t\tdx := int(math.Ceil(fdx + vMidpointX))\n\t\tdz := int(math.Ceil(fdz + vMidpointZ))\n\n\t\tif dx >= 0 && dz >= 0 && dx < v.Size.X && dz < v.Size.Z {\n\t\t\tr.Voxels[x][y][z] = v.Voxels[dx][y][dz]\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func NewInvVect(typ InvType, hash *daghash.Hash) *InvVect {\n\treturn &InvVect{\n\t\tType: typ,\n\t\tHash: hash,\n\t}\n}", "func V(x, y float64) Vect {\n\treturn Vect{x, y}\n}", "func NewView(world *eve.Group, sc *gi3d.Scene, root *gi3d.Group) *View {\n\tvw := &View{World: world, Scene: sc, Root: root}\n\treturn vw\n}", "func TestNewUniverse(t *testing.T) {\n\tt.Parallel()\n\tx, y := 80, 15\n\n\tu := NewUniverse(x, y)\n\tif len(u) != y {\n\t\tt.Errorf(\"Newly initialized universe is %v rows high. Want %v rows.\", len(u), y)\n\t}\n\n\tfor row := range u {\n\t\tif len(u[row]) != x {\n\t\t\tt.Errorf(\"Newly initialized universe is %v columns wide. Want %v columns.\", len(u[0]), x)\n\t\t}\n\t}\n}", "func RotateZ(v magica.VoxelObject, angle float64) (r magica.VoxelObject) {\n\tsin, cos := math.Sin(degToRad(angle)), math.Cos(degToRad(angle))\n\n\torgMidpointY := float64(v.Size.Y) / 2\n\torgMidpointZ := float64(v.Size.Z) / 2\n\n\tzVector := (orgMidpointY * math.Abs(sin)) + (orgMidpointZ * math.Abs(cos))\n\tyVector := (orgMidpointY * math.Abs(cos)) + (orgMidpointZ * math.Abs(sin))\n\n\tsizeZ, sizeY := int(math.Ceil(zVector*2)), int(math.Ceil(yVector*2))\n\n\tr = magica.VoxelObject{\n\t\tVoxels: nil,\n\t\tPaletteData: v.PaletteData,\n\t\tSize: geometry.Point{X: v.Size.X, Y: sizeY, Z: sizeZ},\n\t}\n\n\t// Create the voxel array\n\tr.Voxels = make([][][]byte, r.Size.X)\n\tfor x := 0; x < r.Size.X; x++ {\n\t\tr.Voxels[x] = make([][]byte, r.Size.Y)\n\t\tfor y := 0; y < r.Size.Y; y++ {\n\t\t\tr.Voxels[x][y] = make([]byte, r.Size.Z)\n\t\t}\n\t}\n\n\tvMidpointY := float64(v.Size.Y) / 2\n\n\titerator := func(x, y, z int) {\n\n\t\tfdy := float64(y) - (float64(r.Size.Y) / 2)\n\t\tfdz := float64(z)\n\n\t\tfdy, fdz = (fdy*cos)+(fdz*sin), (fdy*-sin)+(fdz*cos)\n\n\t\tdy := int(math.Ceil(fdy + vMidpointY))\n\t\tdz := int(math.Ceil(fdz))\n\n\t\tif dy >= 0 && dz >= 0 && dy < v.Size.Y && dz < v.Size.Z {\n\t\t\tr.Voxels[x][y][z] = v.Voxels[x][dy][dz]\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func NewVarbinary(name string, m map[string]interface{}) (Vindex, error) {\n\treturn &Varbinary{name: name}, nil\n}", "func (v *Voxel) Add(p primitive.Primitive) {\n\tif p.CanIntersect() {\n\t\tv.primitives = append(v.primitives, p)\n\t} else {\n\t\tgridAccel := NewGrid(p.Refine())\n\t\tv.primitives = append(v.primitives, gridAccel)\n\t}\n}", "func NewBox(name string, width, height float32, offset mgl.Vec2) (*Mesh, error) {\n\tvar (\n\t\thw = width * 0.5\n\t\thh = height * 0.5\n\t)\n\n\treturn MakeMesh(\n\t\tname, 2, gl.TRIANGLES,\n\t\t[]float32{\n\t\t\t-hw + offset[0], -hh + offset[1],\n\t\t\t-hw + offset[0], hh + offset[1],\n\t\t\thw + offset[0], hh + offset[1],\n\t\t\thw + offset[0], -hh + offset[1],\n\t\t},\n\t\tnil, nil, nil,\n\t\t[]uint8{0, 1, 2, 0, 2, 3},\n\t)\n}", "func HotSpot(value Vec2) *SimpleElement { return newSEVec2(\"hotSpot\", value) }", "func NewWorld(width int, height int) *World {\n\tworld := World{}\n\n\t// When the worldLocation is 0,0 then the grid IS the world.\n\tworld.GenerateGrid(image.Point{0, 0}, width, height)\n\n\treturn &world\n}", "func New() *Venom {\n\treturn NewWithStore(NewDefaultConfigStore())\n}", "func NewWorld(x, y int) *World {\n\tcells := make([]bool, x*y)\n\treturn &World{generation: 0, xSize: x, ySize: y, cells: cells}\n}", "func NewGrid(width int, height int) (grid Grid) {\n grid = make(Grid, width)\n for x := 0; x < width; x++ {\n grid[x] = make([][]uint8, height)\n }\n\n return grid\n}", "func NewUniverse(grpcClient pb.GovoxClient, player *common.Player) *Universe {\n\tu := Universe{}\n\tu.Player = player\n\tu.PlanetMap = make(map[int64]*Planet)\n\tu.GRPCClient = grpcClient\n\treturn &u\n}", "func (r *ReconcileZdyfapi) NameNewPv(m *zdyfv1alpha1.Zdyfapi) *corev1.PersistentVolume {\n\n\tnpv := &corev1.PersistentVolume{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"PersistentVolume\",\n\t\t\tAPIVersion: \"apps/v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: m.Spec.NamePVName,\n\t\t\tNamespace: m.Namespace,\n\t\t\tLabels: map[string]string{\"app\": \"nn-pv-1\"},\n\t\t\t//Annotations: map[string]string{\"type\": \"namenode\"},\n\t\t\tOwnerReferences: []metav1.OwnerReference{\n\t\t\t\t*metav1.NewControllerRef(m, schema.GroupVersionKind{\n\t\t\t\t\tGroup: zdyfv1alpha1.SchemeGroupVersion.Group,\n\t\t\t\t\tVersion: zdyfv1alpha1.SchemeGroupVersion.Version,\n\t\t\t\t\tKind: \"Zdyfapi\",\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\tSpec: corev1.PersistentVolumeSpec{\n\t\t\tCapacity: corev1.ResourceList{\n\t\t\t\t\"storage\": resource.MustParse(m.Spec.NamePvStorage),\n\t\t\t},\n\t\t\t//VolumeMode: &corev1.PersistentVolumeFilesystem,\n\t\t\tAccessModes: []corev1.PersistentVolumeAccessMode{\n\t\t\t\tcorev1.ReadWriteOnce,\n\t\t\t},\n\t\t\tStorageClassName: m.Spec.NameSCName, //local volume 只提供了卷的延迟绑定\n\t\t\tPersistentVolumeReclaimPolicy: corev1.PersistentVolumeReclaimDelete,\n\t\t\tPersistentVolumeSource: corev1.PersistentVolumeSource{\n\t\t\t\tLocal: &corev1.LocalVolumeSource{\n\t\t\t\t\tPath: \"/var/lib/docker/volumes/namenode/_data\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tNodeAffinity: &corev1.VolumeNodeAffinity{\n\t\t\t\tRequired: &corev1.NodeSelector{\n\t\t\t\t\tNodeSelectorTerms: []corev1.NodeSelectorTerm{{ //pv node 关联没设置好\n\t\t\t\t\t\tMatchExpressions: []corev1.NodeSelectorRequirement{{\n\t\t\t\t\t\t\tKey: \"kubernetes.io/hostname\",\n\t\t\t\t\t\t\tOperator: corev1.NodeSelectorOpIn,\n\t\t\t\t\t\t\tValues: []string{\"docker-desktop\"}, //设置节点\n\t\t\t\t\t\t}},\n\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn npv\n}", "func makeRandomVector(dim uint) *Vector {\n\treturn NewFrom(makeRandSlice(dim))\n}", "func newVisual(name string) *Visual {\n\tvisual := Visual{ID: uuid.New(), Name: name} // FIXME: uuid is randomly generated, so there could be a collission\n\n\treturn &visual\n}", "func newVariable(name, paramType string) *Param {\n\treturn &Param{\n\t\tParameterKind: variable,\n\t\tName: name,\n\t\tParameterType: paramType,\n\t}\n}", "func (s *Struct_RainForcastRegion) New(date string) *Struct_RainForcastRegion {\n\tst := new(Struct_RainForcastRegion)\n\n\tst_r := make([]*Struct_RainForcastRegion_Region, 0)\n\n\tst.Date = date\n\tst.Region = st_r\n\n\treturn st\n}", "func newTile(topo Topo, zoom, x, y int) *tile {\n\treturn &tile{topo, zoom, x, y, tileKey(uint(zoom), uint(x), uint(y))}\n}", "func (d *Data) PutVoxels(v dvid.VersionID, mutID uint64, vox *Voxels, roiname dvid.InstanceName, mutate bool) error {\n\tr, err := GetROI(v, roiname, vox)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// extract buffer interface if it exists\n\tstore, err := datastore.GetOrderedKeyValueDB(d)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Data type imageblk had error initializing store: %v\\n\", err)\n\t}\n\n\t// extract buffer interface\n\t_, hasbuffer := store.(storage.KeyValueRequester)\n\n\t// Make sure vox is block-aligned\n\tif !dvid.BlockAligned(vox, d.BlockSize()) {\n\t\treturn fmt.Errorf(\"cannot store voxels in non-block aligned geometry %s -> %s\", vox.StartPoint(), vox.EndPoint())\n\t}\n\n\t// Only do one request at a time, although each request can start many goroutines.\n\tif !hasbuffer {\n\t\tif vox.NumVoxels() > 256*256*256 {\n\t\t\tserver.LargeMutationMutex.Lock()\n\t\t\tdefer server.LargeMutationMutex.Unlock()\n\t\t}\n\t}\n\n\t// create some buffer for handling requests\n\tfinishedRequests := make(chan error, 1000)\n\tputrequests := 0\n\n\t// Post new extents if there was a change (will always require 1 GET which should\n\t// not be a big deal for large posts or for distributed back-ends)\n\t// (assumes rest of the command will finish correctly which seems reasonable)\n\tctx := datastore.NewVersionedCtx(d, v)\n\tputrequests++\n\tgo func() {\n\t\terr := d.PostExtents(ctx, vox.StartPoint(), vox.EndPoint())\n\t\tfinishedRequests <- err\n\t}()\n\n\t// Iterate through index space for this data.\n\tfor it, err := vox.NewIndexIterator(d.BlockSize()); err == nil && it.Valid(); it.NextSpan() {\n\t\ti0, i1, err := it.IndexSpan()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tptBeg := i0.Duplicate().(dvid.ChunkIndexer)\n\t\tptEnd := i1.Duplicate().(dvid.ChunkIndexer)\n\n\t\tbegX := ptBeg.Value(0)\n\t\tendX := ptEnd.Value(0)\n\n\t\tc := dvid.ChunkPoint3d{begX, ptBeg.Value(1), ptBeg.Value(2)}\n\t\tfor x := begX; x <= endX; x++ {\n\t\t\tc[0] = x\n\t\t\tcurIndex := dvid.IndexZYX(c)\n\n\t\t\t// Don't PUT if this index is outside a specified ROI\n\t\t\tif r != nil && r.Iter != nil && !r.Iter.InsideFast(curIndex) {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tkv := &storage.TKeyValue{K: NewTKey(&curIndex)}\n\t\t\tputOp := &putOperation{vox, curIndex, v, mutate, mutID}\n\t\t\top := &storage.ChunkOp{putOp, nil}\n\t\t\tputrequests++\n\t\t\td.PutChunk(&storage.Chunk{op, kv}, hasbuffer, finishedRequests)\n\t\t}\n\t}\n\t// wait for everything to finish\n\tfor i := 0; i < putrequests; i++ {\n\t\terrjob := <-finishedRequests\n\t\tif errjob != nil {\n\t\t\terr = errjob\n\t\t}\n\t}\n\treturn err\n}", "func NewRed() Vector3 {\n\treturn New(1, 0, 0)\n}", "func New(img Image, dump string, shrink bool, term *Term) *VM {\n\tvm := VM{\n\t\timg,\n\t\tdump,\n\t\tshrink,\n\t\tmake(map[int32]chan int32),\n\t\tmake(map[int32]*os.File),\n\t\tterm,\n\t}\n\treturn &vm\n}", "func V(x, y float64) Vec {\n\treturn Vec{x, y}\n}", "func NEW_VECTOR(indices []int, values []float64, n int) VECTOR_TYPE {\n if len(indices) != len(values) {\n panic(\"number of indices does not match number of values\")\n }\n r := NIL_VECTOR(n)\n for i, k := range indices {\n if k >= n {\n panic(\"index larger than vector dimension\")\n }\n if _, ok := r.values[k]; ok {\n panic(\"index appeared multiple times\")\n } else {\n if values[i] != 0.0 {\n r.values[k] = NEW_SCALAR(values[i])\n r.indexInsert(k)\n }\n }\n }\n return r\n}", "func New(cam ray.Ray, sample, maxDepth, core, thread int, na, ng, ratio float64) *World {\n\tif core > runtime.NumCPU() {\n\t\tcore = runtime.NumCPU()\n\t}\n\treturn &World{\n\t\tCam: cam,\n\t\tSample: sample,\n\t\tMaxDepth: maxDepth,\n\t\tCore: core,\n\t\tThread: thread,\n\t\tRatio: ratio, Na: na, Ng: ng,\n\t\tn1: na / ng, n2: ng / na}\n}", "func (w *RandomWorld) New() error {\n\t// Check if the world was initialized with valid terrain sizes\n\tif w.Height <= 0 || w.Width <= 0 {\n\t\treturn fmt.Errorf(\"the terrain size can't be less than or equal to zero (given WxH: %dx%d)\", w.Width,\n\t\t\tw.Height)\n\t}\n\t// Initialize the food and being map\n\tw.BeingList = make(map[string]*GoWorld.Being)\n\tw.FoodList = make(map[string]*GoWorld.Food)\n\n\t// Set the pathfinder\n\tw.pathFinder = pathing.NewPathfinder(w)\n\n\t// Initialize the empty images of the terrain\n\trect := image.Rect(0, 0, w.Width, w.Height)\n\tw.TerrainImage = image.NewGray(rect)\n\tw.TerrainZones = image.NewRGBA(rect)\n\tw.TerrainSpots = make([][]*Spot, w.Width)\n\tfor i := range w.TerrainSpots {\n\t\tw.TerrainSpots[i] = make([]*Spot, w.Height)\n\t\tfor j := range w.TerrainSpots[i] {\n\t\t\tw.TerrainSpots[i][j] = &Spot{}\n\t\t}\n\t}\n\n\t// Get an instance of a Perlin noise generator\n\tperl := noise.NewPerlin(6, 0.4, 0)\n\tvar g color.Gray\n\tvar grayNoise uint8\n\t// Histogram to calculate how many pixels belong to each value (grayscale, so 256 bins with size 1)\n\thist := make([]int, 256)\n\t// Fill the grayscale image with Perlin noise\n\tfor x := 0; x < w.Width; x++ {\n\t\tfor y := 0; y < w.Height; y++ {\n\t\t\tfloatNoise := perl.OctaveNoise2D(float64(x)/255, float64(y)/255)\n\n\t\t\t// Paint the grayscale (pseudo DEM) terrain\n\t\t\tgrayNoise = uint8(floatNoise * 255)\n\t\t\tg = color.Gray{\n\t\t\t\tY: grayNoise,\n\t\t\t}\n\t\t\tw.TerrainImage.Set(x, y, g)\n\t\t\t// Increment the bin that counts the grayscale value\n\t\t\thist[grayNoise]++\n\t\t}\n\t}\n\t// Calculate at which height (0-255 grayscale) a zone begins and ends with custom ratios for each zone\n\tzoneLimits := w.CalculateZoneLimits(hist, 0.20, 0.50, 0.10, 0.15, 0.025, 0.025)\n\n\tvar c color.RGBA\n\tfor x := 0; x < w.Width; x++ {\n\t\tfor y := 0; y < w.Height; y++ {\n\t\t\tgrayNoise = w.TerrainImage.GrayAt(x, y).Y\n\t\t\t// Paint the zones using colors\n\t\t\tfor i, l := range zoneLimits {\n\t\t\t\tif grayNoise <= l {\n\t\t\t\t\t// Found the appropriate zone, paint it with the i-th color\n\t\t\t\t\tc = Surfaces[i].Color\n\t\t\t\t\tw.TerrainSpots[x][y].Surface = &Surfaces[i]\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tw.TerrainZones.Set(x, y, c)\n\t\t}\n\t}\n\t// Store the terrain image\n\tf, _ := os.Create(\"terrain.png\")\n\tdefer f.Close()\n\t_ = png.Encode(f, w.TerrainZones)\n\treturn nil\n}", "func Remove(v magica.VoxelObject, src magica.VoxelObject, index uint8) (r magica.VoxelObject) {\n\tr = v.Copy()\n\n\titerator := func(x, y, z int) {\n\t\tif x < src.Size.X && y < src.Size.Y && z < src.Size.Z && src.Voxels[x][y][z] != index {\n\t\t\tr.Voxels[x][y][z] = 0\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func NewVCopy(data []float64) *V {\n\td := len(data)\n\tif d == 0 {\n\t\tpanic(ErrDim)\n\t}\n\tnewData := make([]float64, d)\n\tcopy(newData, data)\n\treturn &V{Data: newData}\n}", "func ProduceEmpty(v magica.VoxelObject) (r magica.VoxelObject) {\n\tr = v.Copy()\n\n\titerator := func(x, y, z int) {\n\t\tif r.Voxels[x][y][z] == 255 {\n\t\t\tr.Voxels[x][y][z] = 0\n\t\t}\n\t}\n\n\tr.Iterate(iterator)\n\n\treturn r\n}", "func CreateNewBox(boxType string, boxVersion string) error {\n\tif mebroutines.ExistsFile(mebroutines.GetVDIImagePath()) {\n\t\terr := os.Remove(mebroutines.GetVDIImagePath())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not remove old vdi file %s: %w\", mebroutines.GetVDIImagePath(), err)\n\t\t}\n\t\tlog.Debug(\"Removed existing VDI file %s\", mebroutines.GetVDIImagePath())\n\t}\n\n\tcalculatedBoxCPUs, err := calculateBoxCPUs()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcalculatedBoxMemory, errMemory := calculateBoxMemory()\n\tif errMemory != nil {\n\t\treturn errMemory\n\t}\n\n\tlog.Debug(\"Calculated new VM specs - CPUs: %d, Memory: %d\", calculatedBoxCPUs, calculatedBoxMemory)\n\n\tcreateCommands := getCreateNewBoxBasicCommands(boxName, boxType, boxVersion, calculatedBoxCPUs, calculatedBoxMemory)\n\n\tvBoxVersion, err := vboxmanage.GetVBoxManageVersion()\n\tif err != nil {\n\t\tlog.Error(\"Could not get VBoxManage version: %v\", err)\n\n\t\treturn err\n\t}\n\n\tclipboardCommand, err := getCreateNewBoxClipboadCommand(vBoxVersion)\n\tif err != nil {\n\t\tlog.Error(\"Could not get new box clipboard creation command: %v\", err)\n\n\t\treturn err\n\t}\n\tcreateCommands = append(createCommands, clipboardCommand)\n\n\tcreateCommands = append(createCommands, vboxmanage.VBoxCommand{\"snapshot\", boxName, \"take\", boxSnapshotName})\n\n\terr = vboxmanage.RunCommands(createCommands)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvboxmanage.ResetVBoxResponseCache()\n\n\treturn nil\n}", "func NewRectangle(x int, y int, width int, height int) *Rectangle {\n return &Rectangle{js.Global.Get(\"Phaser\").Get(\"Rectangle\").New(x, y, width, height)}\n}", "func New(width uint16, height uint16) *Texture {\n\tt := &Texture{\n\t\twidth: width,\n\t\theight: height,\n\t\tpixels: make([]rgb565.Rgb565Color, width*height),\n\t}\n\n\tfor i := range t.pixels {\n\t\tt.pixels[i] = rgb565.New(0x00, 0x00, 0x00)\n\t}\n\n\treturn t\n}", "func init_vertex(x, y int) Vertex {\n return Vertex{x, y}\n}", "func NewCube() *Mesh {\n\n\tmesh := NewMesh(\"Cube\",\n\n\t\t// Top\n\n\t\tNewVertex(1, 1, -1, 1, 0),\n\t\tNewVertex(1, 1, 1, 1, 1),\n\t\tNewVertex(-1, 1, -1, 0, 0),\n\n\t\tNewVertex(-1, 1, -1, 0, 0),\n\t\tNewVertex(1, 1, 1, 1, 1),\n\t\tNewVertex(-1, 1, 1, 0, 1),\n\n\t\t// Bottom\n\n\t\tNewVertex(-1, -1, -1, 0, 0),\n\t\tNewVertex(1, -1, 1, 1, 1),\n\t\tNewVertex(1, -1, -1, 1, 0),\n\n\t\tNewVertex(-1, -1, 1, 0, 1),\n\t\tNewVertex(1, -1, 1, 1, 1),\n\t\tNewVertex(-1, -1, -1, 0, 0),\n\n\t\t// Front\n\n\t\tNewVertex(-1, 1, 1, 0, 0),\n\t\tNewVertex(1, -1, 1, 1, 1),\n\t\tNewVertex(1, 1, 1, 1, 0),\n\n\t\tNewVertex(-1, -1, 1, 0, 1),\n\t\tNewVertex(1, -1, 1, 1, 1),\n\t\tNewVertex(-1, 1, 1, 0, 0),\n\n\t\t// Back\n\n\t\tNewVertex(1, 1, -1, 1, 0),\n\t\tNewVertex(1, -1, -1, 1, 1),\n\t\tNewVertex(-1, 1, -1, 0, 0),\n\n\t\tNewVertex(-1, 1, -1, 0, 0),\n\t\tNewVertex(1, -1, -1, 1, 1),\n\t\tNewVertex(-1, -1, -1, 0, 1),\n\n\t\t// Right\n\n\t\tNewVertex(1, 1, -1, 1, 0),\n\t\tNewVertex(1, 1, 1, 1, 1),\n\t\tNewVertex(1, -1, -1, 0, 0),\n\n\t\tNewVertex(1, -1, -1, 0, 0),\n\t\tNewVertex(1, 1, 1, 1, 1),\n\t\tNewVertex(1, -1, 1, 0, 1),\n\n\t\t// Left\n\n\t\tNewVertex(-1, -1, -1, 0, 0),\n\t\tNewVertex(-1, 1, 1, 1, 1),\n\t\tNewVertex(-1, 1, -1, 1, 0),\n\n\t\tNewVertex(-1, -1, 1, 0, 1),\n\t\tNewVertex(-1, 1, 1, 1, 1),\n\t\tNewVertex(-1, -1, -1, 0, 0),\n\t)\n\n\treturn mesh\n\n}", "func New() *Novis {\n\treturn &Novis{\n\t\tRoot: &Branch{\n\t\t\tbranches: make(map[string]*Branch),\n\t\t},\n\t}\n}", "func NewV(capHint int) *Gini {\n\tg := &Gini{\n\t\txo: xo.NewSV(capHint)}\n\treturn g\n}", "func New() VerkleNode {\n\treturn newInternalNode(0)\n}", "func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, class string, annotations ...string) *v1.PersistentVolume {\n\tvolume := v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tResourceVersion: \"1\",\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity),\n\t\t\t},\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tGCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany},\n\t\t\tPersistentVolumeReclaimPolicy: reclaimPolicy,\n\t\t\tStorageClassName: class,\n\t\t},\n\t\tStatus: v1.PersistentVolumeStatus{\n\t\t\tPhase: phase,\n\t\t},\n\t}\n\n\tif boundToClaimName != \"\" {\n\t\tvolume.Spec.ClaimRef = &v1.ObjectReference{\n\t\t\tKind: \"PersistentVolumeClaim\",\n\t\t\tAPIVersion: \"v1\",\n\t\t\tUID: types.UID(boundToClaimUID),\n\t\t\tNamespace: testNamespace,\n\t\t\tName: boundToClaimName,\n\t\t}\n\t}\n\n\tif len(annotations) > 0 {\n\t\tvolume.Annotations = make(map[string]string)\n\t\tfor _, a := range annotations {\n\t\t\tswitch a {\n\t\t\tcase annDynamicallyProvisioned:\n\t\t\t\tvolume.Annotations[a] = mockPluginName\n\t\t\tdefault:\n\t\t\t\tvolume.Annotations[a] = \"yes\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &volume\n}", "func newBlockInventory(instance *BlockInstance, inv IInventory, ejectOnUnsubscribe bool, invTypeId InvTypeId) *blockInventory {\n blkInv := &blockInventory{\n inv: inv,\n subscribers: make(map[EntityId]IPlayerClient),\n ejectOnUnsubscribe: ejectOnUnsubscribe,\n invTypeId: invTypeId,\n }\n\n if instance != nil {\n blkInv.chunk = instance.Chunk\n blkInv.blockLoc = instance.BlockLoc\n }\n\n blkInv.inv.SetSubscriber(blkInv)\n\n return blkInv\n}", "func NewVector(x, y, z float64) *Tuple {\n\treturn &Tuple{x, y, z, 0.0}\n}", "func New(data []byte) *Index {}", "func NewMvexBox() *MvexBox {\n\treturn &MvexBox{}\n}", "func NewScene(width, height uint8) (*Scene, error) {\n\tarea, err := NewUsefulArea(width, height)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot create scene: %s\", err)\n\t}\n\n\treturn &Scene{\n\t\tarea: area,\n\t\tlocations: make([]Location, 0),\n\t\tlocationsMutex: &sync.RWMutex{},\n\t}, nil\n}", "func New(device int) *MiniOpenCV {\n\treturn &MiniOpenCV{device: device}\n}", "func (*vspR) NewStruct() *vspR {\n\treturn &vspR{}\n}", "func newVar(v interface{}) (*interface{}, error) {\n\tx := interface{}(v)\n\treturn &x, nil\n}", "func newScene(win wde.Window, e *Engine) *scene {\n\ts := &scene{\n\t\twin: win,\n\t\te: e,\n\t}\n\n\treturn s\n}", "func NewWorld(width, height, regionCount int) *World {\n\tvar w World\n\tw.width = width\n\tw.height = height\n\n\tw.initializeTiles()\n\tw.initializeRegions(regionCount, makeDefaultBiomes())\n\tw.expandRegions(-1, -1)\n\n\treturn &w\n}", "func newPanel(part *vu.Ent, x, y, z float64, level int) *panel {\n\tp := &panel{}\n\tp.part = part.AddPart()\n\tp.lvl = level\n\tp.cubes = []*cube{}\n\tp.cx, p.cy, p.cz = x, y, z\n\tp.ccnt, p.cmax = 0, (level-1)*(level-1)*8\n\tp.mergec = func() { p.merge() }\n\tp.trashc = func() { p.trash() }\n\tp.addc = func() { p.addCell() }\n\tp.remc = func() { p.removeCell() }\n\treturn p\n}", "func New(x, y int, v []float32) Matrix {\n\n\tif x*y != len(v) {\n\t\tpanic(\"number of elements doesn't match size\")\n\t}\n\treturn &myMatrix{x, y, v}\n}", "func (b *BinVOX) ToMesh() *gl.Mesh {\n\tlog.Printf(\"Generating mesh for %v voxels...\", len(b.WhiteVoxels)+len(b.ColorVoxels))\n\tvoxels := []gl.Voxel{}\n\tkeyFunc := func(v Key) {\n\t\tvoxels = append(voxels, gl.Voxel{X: v.X, Y: v.Y, Z: v.Z})\n\t}\n\tfor v := range b.WhiteVoxels {\n\t\tkeyFunc(v)\n\t}\n\tfor v := range b.ColorVoxels {\n\t\tkeyFunc(v)\n\t}\n\n\tmesh := gl.NewVoxelMesh(voxels)\n\tlog.Printf(\"Done generating mesh with %v triangles and %v lines.\", len(mesh.Triangles), len(mesh.Lines))\n\tmbb := mesh.BoundingBox()\n\tlog.Printf(\"Mesh MBB in voxel units = %v\", mbb)\n\n\tlog.Println(\"Moving the mesh back into its original position...\")\n\tt1 := gl.V(0.5, 0.5, 0.5)\n\tlog.Printf(\"Translating by %v\", t1)\n\tmbb.Min = mbb.Min.Add(t1)\n\tmbb.Max = mbb.Max.Add(t1)\n\tlog.Printf(\"Translated mesh MBB in voxel units = %v\", mbb)\n\n\tvpmm := b.VoxelsPerMM()\n\tmmpv := 1.0 / vpmm\n\ts := gl.V(mmpv, mmpv, mmpv) // uniform scaling\n\tlog.Printf(\"Scaling by %v millimeters per voxel\", mmpv)\n\n\tt2 := gl.V(b.TX, b.TY, b.TZ)\n\tlog.Printf(\"Translating by %v\", t2)\n\n\tm := gl.Identity().Translate(t1).Scale(s).Translate(t2)\n\tmesh.Transform(m)\n\tmbb = mesh.BoundingBox()\n\tlog.Printf(\"Done moving mesh to MBB=%v\", mbb)\n\n\treturn mesh\n}", "func newGrid(x, y int) Grid {\n\tg := make([][]Square, x)\n\tfor i := 0; i < x; i++ {\n\t\tg[i] = make([]Square, y)\n\t}\n\treturn g\n}", "func newVolume(name, capacity, boundToClaimUID, boundToClaimName string, phase v1.PersistentVolumePhase, reclaimPolicy v1.PersistentVolumeReclaimPolicy, class string, annotations ...string) *v1.PersistentVolume {\n\tfs := v1.PersistentVolumeFilesystem\n\tvolume := v1.PersistentVolume{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tResourceVersion: \"1\",\n\t\t},\n\t\tSpec: v1.PersistentVolumeSpec{\n\t\t\tCapacity: v1.ResourceList{\n\t\t\t\tv1.ResourceName(v1.ResourceStorage): resource.MustParse(capacity),\n\t\t\t},\n\t\t\tPersistentVolumeSource: v1.PersistentVolumeSource{\n\t\t\t\tGCEPersistentDisk: &v1.GCEPersistentDiskVolumeSource{},\n\t\t\t},\n\t\t\tAccessModes: []v1.PersistentVolumeAccessMode{v1.ReadWriteOnce, v1.ReadOnlyMany},\n\t\t\tPersistentVolumeReclaimPolicy: reclaimPolicy,\n\t\t\tStorageClassName: class,\n\t\t\tVolumeMode: &fs,\n\t\t},\n\t\tStatus: v1.PersistentVolumeStatus{\n\t\t\tPhase: phase,\n\t\t},\n\t}\n\n\tif boundToClaimName != \"\" {\n\t\tvolume.Spec.ClaimRef = &v1.ObjectReference{\n\t\t\tKind: \"PersistentVolumeClaim\",\n\t\t\tAPIVersion: \"v1\",\n\t\t\tUID: types.UID(boundToClaimUID),\n\t\t\tNamespace: testNamespace,\n\t\t\tName: boundToClaimName,\n\t\t}\n\t}\n\n\tif len(annotations) > 0 {\n\t\tvolume.Annotations = make(map[string]string)\n\t\tfor _, a := range annotations {\n\t\t\tswitch a {\n\t\t\tcase storagehelpers.AnnDynamicallyProvisioned:\n\t\t\t\tvolume.Annotations[a] = mockPluginName\n\t\t\tdefault:\n\t\t\t\tvolume.Annotations[a] = \"yes\"\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &volume\n}", "func NewUDiv(x, y value.Value) *InstUDiv {\n\tinst := &InstUDiv{X: x, Y: y}\n\t// Compute type.\n\tinst.Type()\n\treturn inst\n}", "func New(options ...Option) *PersistentVolume {\n\tpv := &PersistentVolume{}\n\n\tfor _, op := range options {\n\t\top(pv)\n\t}\n\n\treturn pv\n}", "func New(data []byte) *Index", "func NewTile(v TileValue, x, y int) *Tile {\n\topts := &ebiten.DrawImageOptions{}\n\topts.GeoM.Translate(float64(TileSize*x), float64(TileSize*y))\n\treturn &Tile{\n\t\tValue: v,\n\t\tX: x, Y: y,\n\t\tDrawX: float64(TileSize * x), DrawY: float64(TileSize * y),\n\t\tDrawImg: emptyTileImage(),\n\t\tDrawOpts: opts,\n\t}\n}", "func NewVc(vCapHint, cCapHint int) *Gini {\n\tg := &Gini{\n\t\txo: xo.NewSVc(vCapHint, cCapHint)}\n\n\treturn g\n}", "func (*Viewport) New() akara.Component {\n\treturn &Viewport{\n\t\tBackground: color.Transparent,\n\t}\n}", "func New(size int, dmin, dmax []float64) Cube {\n\td := make(map[int]map[int]map[int][]float64, size)\n\n\tfor x := 0; x < size; x++ {\n\t\tyy := make(map[int]map[int][]float64, size)\n\n\t\tfor y := 0; y < size; y++ {\n\t\t\tz := make(map[int][]float64, size)\n\t\t\tyy[y] = z\n\t\t}\n\n\t\td[x] = yy\n\t}\n\n\treturn Cube{\n\t\tSize: size,\n\t\tData: d,\n\t\tDomainMin: dmin,\n\t\tDomainMax: dmax,\n\t}\n}", "func NewGreen() Vector3 {\n\treturn New(1, 0, 0)\n}", "func New(tagName ...string) *VM {\n\tif len(tagName) == 0 {\n\t\ttagName = append(tagName, \"\")\n\t}\n\treturn &VM{\n\t\ttagName: tagName[0],\n\t\tstructJar: make(map[int32]*structVM, 256),\n\t}\n}", "func NewVolume(volumeRequest provider.Volume) Volume {\n\t// Build the template to send to backend\n\n\tvolume := Volume{\n\t\tID: volumeRequest.VolumeID,\n\t\tCRN: volumeRequest.CRN,\n\t\tTags: volumeRequest.VPCVolume.Tags,\n\t\tZone: &Zone{\n\t\t\tName: volumeRequest.Az,\n\t\t},\n\t\tProvider: string(volumeRequest.Provider),\n\t\tVolumeType: string(volumeRequest.VolumeType),\n\t}\n\tif volumeRequest.Name != nil {\n\t\tvolume.Name = *volumeRequest.Name\n\t}\n\tif volumeRequest.Capacity != nil {\n\t\tvolume.Capacity = int64(*volumeRequest.Capacity)\n\t}\n\tif volumeRequest.VPCVolume.Profile != nil {\n\t\tvolume.Profile = &Profile{\n\t\t\tName: volumeRequest.VPCVolume.Profile.Name,\n\t\t}\n\t}\n\tif volumeRequest.VPCVolume.ResourceGroup != nil {\n\t\tvolume.ResourceGroup = &ResourceGroup{\n\t\t\tID: volumeRequest.VPCVolume.ResourceGroup.ID,\n\t\t\tName: volumeRequest.VPCVolume.ResourceGroup.Name,\n\t\t}\n\t}\n\n\tif volumeRequest.Iops != nil {\n\t\tvalue, err := strconv.ParseInt(*volumeRequest.Iops, 10, 64)\n\t\tif err != nil {\n\t\t\tvolume.Iops = 0\n\t\t}\n\t\tvolume.Iops = value\n\t}\n\tif volumeRequest.VPCVolume.VolumeEncryptionKey != nil && len(volumeRequest.VPCVolume.VolumeEncryptionKey.CRN) > 0 {\n\t\tencryptionKeyCRN := volumeRequest.VPCVolume.VolumeEncryptionKey.CRN\n\t\tvolume.VolumeEncryptionKey = &VolumeEncryptionKey{CRN: encryptionKeyCRN}\n\t}\n\n\tvolume.Cluster = volumeRequest.Attributes[ClusterIDTagName]\n\tvolume.Status = StatusType(volumeRequest.Attributes[VolumeStatus])\n\treturn volume\n}", "func NewVessel(id uuid.UUID, name, beam, loa, draft, status string) *Vessel {\n\treturn &Vessel{\n\t\tID: id,\n\t\tName: name,\n\t\tBeam: beam,\n\t\tLOA: loa,\n\t\tDraft: draft,\n\t\tStatus: status,\n\t}\n}", "func NewBox(width float32, depth float32, height float32) Box {\n\tvar box Box\n\n\t// No negative stuff\n\tif width <= 0.0 || depth <= 0.0 || height <= 0.0 {\n\t\tlog.Fatalf(\"Model.NewBox: must have positive sizes, got (w:%f, d:%f, h:%f)\", width, depth, height)\n\t}\n\n\t// Corner points\n\tfbl := vector.NewVector([]float32{-width / 2.0, 0.0, -depth / 2.0})\n\tbbl := vector.NewVector([]float32{-width / 2.0, 0.0, depth / 2.0})\n\tbbr := vector.NewVector([]float32{width / 2.0, 0.0, depth / 2.0})\n\tfbr := vector.NewVector([]float32{width / 2.0, 0.0, -depth / 2.0})\n\tftl := vector.NewVector([]float32{-width / 2.0, height, -depth / 2.0})\n\tbtl := vector.NewVector([]float32{-width / 2.0, height, depth / 2.0})\n\tbtr := vector.NewVector([]float32{width / 2.0, height, depth / 2.0})\n\tftr := vector.NewVector([]float32{width / 2.0, height, -depth / 2.0})\n\n\t// Meshes from the points\n\tbox.meshes = []Mesh{\n\t\t// Bottom\n\t\tNewMesh([]vector.Vector{fbl, bbl, fbr}),\n\t\tNewMesh([]vector.Vector{bbl, bbr, fbr}),\n\t\t// Top\n\t\tNewMesh([]vector.Vector{ftl, btl, ftr}),\n\t\tNewMesh([]vector.Vector{btl, btr, ftr}),\n\t\t// Left\n\t\tNewMesh([]vector.Vector{fbl, bbl, btl}),\n\t\tNewMesh([]vector.Vector{fbl, ftl, btl}),\n\t\t// Right\n\t\tNewMesh([]vector.Vector{fbr, bbr, btr}),\n\t\tNewMesh([]vector.Vector{fbr, ftr, btr}),\n\t\t// Front\n\t\tNewMesh([]vector.Vector{fbl, ftl, ftr}),\n\t\tNewMesh([]vector.Vector{fbl, fbr, ftr}),\n\t\t// Back\n\t\tNewMesh([]vector.Vector{bbl, btl, btr}),\n\t\tNewMesh([]vector.Vector{bbl, bbr, btr}),\n\t}\n\n\tbox.width = width\n\tbox.depth = depth\n\tbox.height = height\n\n\treturn box\n}", "func CreateNewFv(nodeID int, timeAfter string, remarks string, timeStart string, version string, verState int) (Fverinfo, error) {\n\tif nodeID == 0 || timeAfter == \"\" || remarks == \"\" || timeStart == \"\" || version == \"\" || verState == 0 {\n\t\treturn Fverinfo{}, errors.New(\"Not enough argument supplied\")\n\t}\n\treturn Fverinfo{\n\t\tNodeID: nodeID,\n\t\tEndDate: timeAfter,\n\t\tRemarks: remarks,\n\t\tStartDate: timeStart,\n\t\tVersion: version,\n\t\tVerState: verState,\n\t}, nil\n}", "func NewV0(bloxid string) (*V0, error) {\n\tif len(bloxid) == 0 {\n\t\treturn nil, ErrIDEmpty\n\t}\n\n\treturn parseV0(bloxid)\n}", "func NewVFile(pwd, modded, real string, size int64, compressed, decompress bool, fx DataPack) *VFile {\n\tmdir := filepath.Dir(modded)\n\trdir := filepath.Dir(real)\n\tvf := VFile{\n\t\tCompressed: compressed,\n\t\tDecompress: decompress,\n\t\tBaseDir: pwd,\n\t\tDir: mdir,\n\t\tShadowDir: rdir,\n\t\tFileName: filepath.Base(modded),\n\t\tMod: time.Now(),\n\t\tDatasize: size,\n\t\tDataPack: fx,\n\t}\n\n\treturn &vf\n}", "func NewVShare(data []float64) *V {\n\tif len(data) == 0 {\n\t\tpanic(ErrDim)\n\t}\n\treturn &V{Data: data}\n}", "func NewBox(x1, y1, x2, y2 int) *Box {\n\treturn &Box{Rect: image.Rect(x1, y1, x2, y2)}\n}", "func NewVariety(\n\tid uuid.UUID,\n\tcommodityID uuid.UUID,\n\tname string,\n\torigin string,\n\tspecs string) *Variety {\n\treturn &Variety{\n\t\tID: id,\n\t\tCommodityID: commodityID,\n\t\tName: name,\n\t\tOrigin: origin,\n\t\tSpecs: specs,\n\t}\n}", "func NewUniverse(ss ...string) *Universe {\n\tm := make(map[string]float64)\n\tfor _, s := range ss {\n\t\tm[s] = 0\n\t}\n\n\treturn &Universe{\n\t\tm: m,\n\t}\n}", "func NewVector(slice interface{}) *Tensor {\n\tv := reflect.ValueOf(slice)\n\tlength := v.Len()\n\tdtype := SliceTypeToDtype[reflect.TypeOf(slice)]\n\tbytelen := length * int(DtypeSize[dtype])\n\tif v.Len() != length {\n\t\treturn nil\n\t}\n\tsliceHeader := reflect.SliceHeader{\n\t\tData: uintptr(unsafe.Pointer(v.Pointer())),\n\t\tCap: int(bytelen),\n\t\tLen: int(bytelen),\n\t}\n\treturn &Tensor{\n\t\tBuffer: *(*[]byte)(unsafe.Pointer(&sliceHeader)),\n\t\tDims: []int64{int64(length)},\n\t\tDtype: dtype,\n\t}\n}", "func New(x, y, z, size float64, totalLevels, preGenLevels uint8) (*Octree, error) {\n\tif preGenLevels > totalLevels {\n\t\treturn nil, errors.New(\"preGenLevels may not be bigger than totalLevels\")\n\t}\n\n\tif size <= 0 {\n\t\treturn nil, errors.New(\"Size must be a positive number greater than zero\")\n\t}\n\n\tt := &Octree{\n\t\tleafMap: make(map[interface{}]*leaf),\n\t\tleafMapLock: &sync.Mutex{},\n\t\tlevels: totalLevels,\n\t\troot: &octant{\n\t\t\tx: x,\n\t\t\ty: y,\n\t\t\tz: z,\n\t\t\tsize: size,\n\t\t}}\n\n\tvar preGen func(oct *octant, currLevel uint8)\n\tpreGen = func(oct *octant, currLevel uint8) {\n\t\tfor i := 0; i < 8; i++ {\n\t\t\tif currLevel != totalLevels {\n\t\t\t\toct.children[i] = oct.newOctant(i, currLevel == preGenLevels)\n\t\t\t\tif currLevel < preGenLevels {\n\t\t\t\t\tpreGen(oct.children[i].(*octant), currLevel+1)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toct.children[i] = oct.newLeaf(i)\n\t\t\t}\n\t\t}\n\t}\n\n\tpreGen(t.root, 0)\n\n\treturn t, nil\n}", "func NewNode(port int) dhtNode {\n\t// Todo: create a node and then return it.\n\treturn dht.NewSurface(port)\n}", "func NewPrimitives() Primitives {\n\treturn Primitives{\n\t\t\"vtxs\": NewAttributes(Int, 0),\n\t}\n}", "func NewHealth() *Health {\n\tconst vertexShader = `\n\t\t#version 410\n\n\t\tin vec4 coord;\n\t\tout vec2 tcoord;\n\n\t\tvoid main(void) {\n\t\t\tgl_Position = vec4(coord.xy, 0, 1);\n\t\t\ttcoord = coord.zw;\n\t\t}\n\t`\n\n\tconst fragmentShader = `\n\t\t#version 410\n\n\t\tin vec2 tcoord;\n\t\tuniform sampler2D tex;\n\t\tout vec4 frag_color;\n\n\t\tvoid main(void) {\n\t\t\tvec4 texel = texture(tex, tcoord);\n\t\t\tfrag_color = texel;\n\t\t}\n\t`\n\n\th := Health{}\n\n\th.program = createProgram(vertexShader, fragmentShader)\n\tbindAttribute(h.program, 0, \"coord\")\n\n\th.textureUniform = uniformLocation(h.program, \"tex\")\n\th.pointsVBO = newVBO()\n\th.drawableVAO = newPointsVAO(h.pointsVBO, 4)\n\n\trgba, _ := LoadImages([]string{\"textures/health.png\", \"textures/health-empty.png\"}, 16)\n\th.textureUnit = 4\n\tgl.ActiveTexture(uint32(gl.TEXTURE0 + h.textureUnit))\n\tgl.GenTextures(1, &h.texture)\n\tgl.BindTexture(gl.TEXTURE_2D, h.texture)\n\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)\n\tgl.TexParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST)\n\n\tgl.TexImage2D(\n\t\tgl.TEXTURE_2D,\n\t\t0,\n\t\tgl.RGBA,\n\t\tint32(rgba.Rect.Size().X),\n\t\tint32(rgba.Rect.Size().Y),\n\t\t0,\n\t\tgl.RGBA,\n\t\tgl.UNSIGNED_BYTE,\n\t\tgl.Ptr(rgba.Pix),\n\t)\n\n\tgl.GenerateMipmap(gl.TEXTURE_2D)\n\treturn &h\n}", "func ExampleNewSurface() {\n\tlength := 10\n\tnewSurface := NewSurface(length)\n\tnode := NewNode(4,5, true)\n\tnewSurface.Print(node)\n\n\t// Output:\n\t// -------------------- Y\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 9\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 8\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 7\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 6\n\t// [ 0 0 0 0 1 0 0 0 0 0 ] 5\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 4\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 3\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 2\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 1\n\t// [ 0 0 0 0 0 0 0 0 0 0 ] 0\n\t// --------------------\n\t// X 0 1 2 3 4 5 6 7 8 9 X\n}" ]
[ "0.54246366", "0.53961533", "0.5368537", "0.5325154", "0.52639985", "0.52551687", "0.5206027", "0.5179891", "0.5164758", "0.5157647", "0.50985044", "0.507762", "0.5011818", "0.49793324", "0.49436477", "0.49371257", "0.49264735", "0.49020922", "0.48898882", "0.48364195", "0.48292488", "0.4796018", "0.47656876", "0.47560158", "0.47426707", "0.47411022", "0.47131798", "0.47124103", "0.46949074", "0.46910962", "0.46768045", "0.46679825", "0.4666275", "0.46532133", "0.46451446", "0.46430025", "0.46378133", "0.46213576", "0.46102524", "0.46061707", "0.4601472", "0.46001023", "0.4593963", "0.4591841", "0.45784083", "0.4575972", "0.45713812", "0.45683467", "0.45620167", "0.45600918", "0.4547929", "0.45462012", "0.4538269", "0.45371577", "0.45348498", "0.4533475", "0.45286906", "0.45255247", "0.45247087", "0.45022145", "0.4501954", "0.44831818", "0.44779864", "0.4473789", "0.447218", "0.44644406", "0.4463462", "0.44584337", "0.4455428", "0.4455315", "0.44449604", "0.44306007", "0.44283992", "0.4423936", "0.44238004", "0.44187257", "0.4417141", "0.44110367", "0.440982", "0.4406116", "0.440037", "0.43977016", "0.4396377", "0.43953875", "0.43911794", "0.43885154", "0.4387745", "0.43759286", "0.43702212", "0.43628538", "0.43588534", "0.43571925", "0.43533292", "0.43434405", "0.43375206", "0.43354684", "0.4331139", "0.43228117", "0.43045235", "0.42997786" ]
0.83172894
0
Intersect checks whether a ray itnersects any of the voxel's primitives
func (v *Voxel) Intersect(ray geometry.Ray, in *primitive.Intersection) bool { return primitive.IntersectMultiple(v.primitives, ray, in) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r Ray) Intersect(s Ray) (v Vec, ok bool) {\n\tif r.Colinear(s) {\n\t\treturn\n\t}\n\n\tv = r.LineIntersect(s)\n\n\treturn v, r.InAABB(v) && s.InAABB(v)\n}", "func (rx *RotationX) Intersection(ray geometry.Ray, tMin, tMax float64, rng *rand.Rand) (*material.RayHit, bool) {\r\n\r\n\trotatedRay := ray\r\n\r\n\trotatedRay.Origin.Y = rx.cosTheta*ray.Origin.Y + rx.sinTheta*ray.Origin.Z\r\n\trotatedRay.Origin.Z = -rx.sinTheta*ray.Origin.Y + rx.cosTheta*ray.Origin.Z\r\n\r\n\trotatedRay.Direction.Y = rx.cosTheta*ray.Direction.Y + rx.sinTheta*ray.Direction.Z\r\n\trotatedRay.Direction.Z = -rx.sinTheta*ray.Direction.Y + rx.cosTheta*ray.Direction.Z\r\n\r\n\trayHit, wasHit := rx.Primitive.Intersection(rotatedRay, tMin, tMax, rng)\r\n\tif wasHit {\r\n\t\tunrotatedNormal := rayHit.NormalAtHit\r\n\t\tunrotatedNormal.Y = rx.cosTheta*rayHit.NormalAtHit.Y - rx.sinTheta*rayHit.NormalAtHit.Z\r\n\t\tunrotatedNormal.Z = rx.sinTheta*rayHit.NormalAtHit.Y + rx.cosTheta*rayHit.NormalAtHit.Z\r\n\t\treturn &material.RayHit{\r\n\t\t\tRay: ray,\r\n\t\t\tNormalAtHit: unrotatedNormal,\r\n\t\t\tTime: rayHit.Time,\r\n\t\t\tU: rayHit.U,\r\n\t\t\tV: rayHit.V,\r\n\t\t\tMaterial: rayHit.Material,\r\n\t\t}, true\r\n\t}\r\n\treturn nil, false\r\n}", "func (s Sphere) rayIntersect(orig, dir vec3) (hit bool, hitpos, normal vec3) {\n\tdir = dir.Norm()\n\toc := s.Center.Sub(orig)\n\tOQ := orig.Add(dir.ScalarProduct(dir.DotProduct(oc)))\n\tCQ := oc.Sub(OQ)\n\tif CQ.Magnitude() > s.Radius {\n\t\treturn false, vec3{}, vec3{}\n\t}\n\tlenPQ := math.Sqrt(s.Radius*s.Radius - CQ.Magnitude()*CQ.Magnitude())\n\tlenOP := OQ.Magnitude() - lenPQ\n\thitpos = orig.Add(dir.ScalarProduct(lenOP))\n\tnorm := hitpos.Sub(oc)\n\n\treturn true, hitpos, norm.Norm()\n}", "func (v *Voxel) IntersectP(ray geometry.Ray) bool {\n\treturn primitive.IntersectPMultiple(v.primitives, ray)\n}", "func (p *RPrism) Intersect(r Ray) (float64, *Material, Vec3, Vec3, bool) {\n\tqueries := []*rprismIntersectQ{\n\t\t{\n\t\t\t[3]float64{r.V.X, r.V.Y, r.V.Z},\n\t\t\t[3]float64{r.D.X, r.D.Y, r.D.Z},\n\t\t\tp.Pos.X, p.Pos.Y, p.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2],\n\t\t\tVec3{-1, 0, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.X, r.V.Y, r.V.Z},\n\t\t\t[3]float64{r.D.X, r.D.Y, r.D.Z},\n\t\t\tp.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2],\n\t\t\tVec3{1, 0, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Y, r.V.Z, r.V.X},\n\t\t\t[3]float64{r.D.Y, r.D.Z, r.D.X},\n\t\t\tp.Pos.Y, p.Pos.Z, p.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0],\n\t\t\tVec3{0, -1, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Y, r.V.Z, r.V.X},\n\t\t\t[3]float64{r.D.Y, r.D.Z, r.D.X},\n\t\t\tp.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0],\n\t\t\tVec3{0, 1, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Z, r.V.X, r.V.Y},\n\t\t\t[3]float64{r.D.Z, r.D.X, r.D.Y},\n\t\t\tp.Pos.Z, p.Pos.X, p.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1],\n\t\t\tVec3{0, 0, -1},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Z, r.V.X, r.V.Y},\n\t\t\t[3]float64{r.D.Z, r.D.X, r.D.Y},\n\t\t\tp.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1],\n\t\t\tVec3{0, 0, 1},\n\t\t},\n\t}\n\tnearest := math.MaxFloat64\n\tfound := false\n\tvar normal Vec3\n\tfor _, q := range queries {\n\t\td, ok := rprismIntersects(q)\n\t\tif ok {\n\t\t\tif d > minDistance && d < nearest {\n\t\t\t\tfound = true\n\t\t\t\tnearest = d\n\t\t\t\tnormal = q.normal\n\t\t\t}\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn 0, nil, Vec3{}, Vec3{}, false\n\t}\n\tpt := r.At(nearest)\n\treturn nearest, p.Mat, pt, normal, found\n}", "func (s *Sphere) Intersect(r *Ray, isect *Intersection) (hit bool) {\n\t// -(d . o) +- sqrt((d . o)^2 - (d . d)((o . o) - 1)) / (d . d)\n\tdo := r.Dir.Dot(r.Origin)\n\tdd := r.Dir.Dot(r.Dir)\n\too := r.Origin.Dot(r.Origin)\n\n\tdiscriminant := do*do - dd*(oo-1)\n\tif discriminant < 0 {\n\t\treturn false\n\t}\n\n\tdiscriminant = math.Sqrt(discriminant)\n\n\tt2 := (-do + discriminant) / dd\n\tif t2 <= Rayε {\n\t\treturn false\n\t}\n\n\tt1 := (-do - discriminant) / dd\n\tif t1 > Rayε {\n\t\tisect.T = t1\n\t\t// No need to normalize because it's a unit sphere at the origin\n\t\tisect.Normal = r.At(t1)\n\t\tisect.Material = s.Object.Material\n\t\t// TODO: possible optimization would be to check if we even need uv coordinates\n\t\tu := 0.5 + (math.Atan2(isect.Normal.Y(), isect.Normal.X()) / (2 * math.Pi))\n\t\tv := 0.5 - (math.Asin(isect.Normal.Z()) / math.Pi)\n\t\tisect.UVCoords = mgl64.Vec2{u, v}\n\t\treturn true\n\t}\n\n\tif t2 > Rayε {\n\t\tisect.T = t2\n\t\tisect.Normal = r.At(t2)\n\t\tisect.Material = s.Object.Material\n\t\tu := 0.5 + (math.Atan2(isect.Normal.Y(), isect.Normal.X()) / (2 * math.Pi))\n\t\tv := 0.5 - (math.Asin(isect.Normal.Z()) / math.Pi)\n\t\tisect.UVCoords = mgl64.Vec2{u, v}\n\t\treturn true\n\t}\n\n\treturn false\n}", "func intersects(\n\tm_minx, m_miny, m_maxx, m_maxy float64,\n\to_minx, o_miny, o_maxx, o_maxy float64,\n) bool {\n\t//not disjoint\n\treturn !(o_minx > m_maxx || o_maxx < m_minx || o_miny > m_maxy || o_maxy < m_miny)\n}", "func (b *BasicShape) Intersect(geometry.Ray, *DifferentialGeometry) bool {\n\tpanic(\"Intersect is not implemented for basic shape\")\n}", "func (cone Cone) Intersect(r ray.Ray) *space.Hit {\n\tif vec3.DotProduct(cone.disc.Normal, r.Direction) < 0 {\n\t\tdiscHit := cone.disc.Intersect(r)\n\n\t\tif discHit != nil {\n\t\t\treturn discHit\n\t\t}\n\t}\n\n\tconeHit := cone.walls.Intersect(r)\n\n\treturn coneHit\n}", "func (r Ray) LineIntersect(s Ray) (point Vec) {\n\t/*\n\t\tequation is derived from system of equations with\n\t\ttwo unknowns where equations are r.Formula and s.Formula\n\t\tfrom which we can derive x of intersection point\n\n\t\tstarting with:\n\t\t\tr.V.Y*X - r.V.X*Y - r.V.Y*r.O.X + r.V.X*r.O.Y = 0\n\t\tand:\n\t\t\ts.V.Y*X - s.V.X*Y - s.V.Y*s.O.X + s.V.X*s.O.Y = 0\n\n\t\tget y from first one:\n\t\t\tr.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y = r.V.X*Y\n\t\t\t(r.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y)/r.V.X = Y\n\n\t\tthen we substitute and get x:\n\t\t\ts.V.Y*X - s.V.X * (r.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y) / r.V.X - s.V.Y*s.O.X + s.V.X*s.O.Y = 0 // * r.V.X\n\t\t\ts.V.Y*X*r.V.X - s.V.X*r.V.Y*X + s.V.X*r.V.Y*r.O.X - s.V.X*r.V.X*r.O.Y - s.V.Y*s.O.X*r.V.X + s.V.X*s.O.Y*r.V.X = 0 // - s.V.Y*X*r.V.X + s.V.X*r.V.Y*X\n\t\t\ts.V.X*r.V.Y*r.O.X - s.V.X*r.V.X*r.O.Y - s.V.Y*s.O.X*r.V.X + s.V.X*s.O.Y*r.V.X = s.V.X*r.V.Y*X - s.V.Y*X*r.V.X // simplify\n\t\t\ts.V.X * (r.V.Y*r.O.X + r.V.X * (s.O.Y - r.O.Y)) - s.V.Y*s.O.X*r.V.X = X * (s.V.X*r.V.Y - s.V.Y*r.V.X) // / (s.V.X*r.V.Y - s.V.Y*r.V.X)\n\t\t\t(s.V.X * (r.V.Y*r.O.X + r.V.X * (s.O.Y - r.O.Y)) - s.V.Y*s.O.X*r.V.X) / (s.V.X*r.V.Y - s.V.Y*r.V.X) = X\n\t*/\n\n\tpoint.X = (s.V.X*(r.V.Y*r.O.X+r.V.X*(s.O.Y-r.O.Y)) - s.V.Y*s.O.X*r.V.X) / (s.V.X*r.V.Y - s.V.Y*r.V.X)\n\n\tif r.V.X == 0 {\n\t\tpoint.Y = s.ProjectX(point.X)\n\t} else {\n\t\tpoint.Y = r.ProjectX(point.X)\n\t}\n\n\treturn\n}", "func (pl *Plane) IntersectWithRay(ray *Ray) (count int, ans []Intersection, intersect bool) {\n\tdeter, _ := pl.Transform.Determinant()\n\tinv := pl.Transform.GetInverse(deter)\n\tray = ray.Transform(inv)\n\tif math.Abs(ray.Direction.Y) < 0.00001 {\n\t\treturn 0, ans, false\n\t}\n\tans = append(ans, *NewIntersection(-ray.Origin.Y/ray.Direction.Y, *ray, pl))\n\treturn 1, ans, true\n}", "func IntersectMultiple(primitives []Primitive, ray geometry.Ray, in *Intersection) bool {\n\tvar hasHit bool\n\tfor _, pr := range primitives {\n\n\t\tif ok := pr.Intersect(ray, in); !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\thasHit = true\n\t\tray.Maxt = in.DfGeometry.Distance\n\t}\n\n\treturn hasHit\n}", "func (s Sphere) Intersect(r *Ray) (*Intersection, bool) {\n\n\tl := vector.Subtract(&r.origin, &s.origin)\n\ta := vector.Dot(&r.direction, &r.direction)\n\tb := 2 * vector.Dot(&r.direction, &l)\n\tc := vector.Dot(&l, &l) - s.radius*s.radius\n\n\tr0, r1, err := solveQuadratic(a, b, c)\n\n\tif err {\n\t\treturn nil, false\n\t}\n\n\tt0 := math.Min(r0, r1)\n\tt1 := math.Max(r0, r1)\n\n\tif t0 < 0 && t1 < 0 {\n\t\treturn nil, false\n\t}\n\n\ti := Intersection{thing: s, r: *r, dist: t0}\n\n\treturn &i, true\n}", "func (stri *SmoothTriangle) IntersectWithRay(ray *Ray) (count int, ans []Intersection, intersect bool) {\n\tdeter, _ := stri.Transform.Determinant()\n\tiT := stri.Transform.GetInverse(deter)\n\tnewR := ray.Transform(iT)\n\tdirCrossE2, _ := newR.Direction.CrossProduct(&stri.Edge2)\n\tdet, _ := stri.Edge1.DotProduct(&dirCrossE2)\n\tif math.Abs(det) < 0.00001 {\n\t\treturn 0, ans, intersect\n\t}\n\tf := float64(1) / det\n\tp1ToOrigin, _ := ray.Origin.Subtract(&stri.Point1)\n\tdot, _ := p1ToOrigin.DotProduct(&dirCrossE2)\n\tu := f * dot\n\tif u < 0 || u > 1 {\n\t\treturn 0, ans, intersect\n\t}\n\toriCrossE1, _ := p1ToOrigin.CrossProduct(&stri.Edge1)\n\tdot2, _ := ray.Direction.DotProduct(&oriCrossE1)\n\tv := f * dot2\n\tif v < 0 || (u+v) > 1 {\n\t\treturn 0, ans, intersect\n\t}\n\tdot3, _ := stri.Edge2.DotProduct(&oriCrossE1)\n\tt := f * dot3\n\tinter := stri.IntersectionWithUandV(*newR, t, u, v)\n\tans = append(ans, *inter)\n\treturn 1, ans, true\n}", "func (b Bounds3) IntersectP(ray Ray) (bool, float64, float64) {\n\tt0 := float64(0)\n\tt1 := ray.tMax\n\tfor i := 0; i < 3; i++ {\n\t\t// cheaper to multiply than divide so compute reciprocal first\n\t\tinvRayDir := 1 / ray.Dir.Get(i)\n\t\ttNear := (b.pMin.Get(i) - ray.Orig.Get(i)) * invRayDir\n\t\ttFar := (b.pMax.Get(i) - ray.Orig.Get(i)) * invRayDir\n\t\tif tNear > tFar {\n\t\t\ttNear, tFar = tFar, tNear\n\t\t}\n\t\t//TODO: update tFar to be more robust\n\t\tif tNear > 0 {\n\t\t\tt0 = tNear\n\t\t}\n\t\tif tFar < t1 {\n\t\t\tt1 = tFar\n\t\t}\n\t\tif t0 > t1 {\n\t\t\treturn false, 0, 0\n\t\t}\n\t}\n\treturn true, t0, t1\n}", "func (self *Rectangle) IntersectsI(args ...interface{}) bool{\n return self.Object.Call(\"intersects\", args).Bool()\n}", "func (r *Ray) Intersect(o Ray) (Vector, bool) {\n\tconst width = 0.03\n\n\tclampInRange := func(p Vector) (Vector, bool) {\n\t\tdist := r.Origin.Distance(p)\n\t\tif dist < r.Mint || dist > r.Maxt {\n\t\t\treturn r.Origin, false\n\t\t}\n\n\t\treturn p, true\n\t}\n\n\tif r.Origin == o.Origin {\n\t\treturn r.Origin, true\n\t}\n\n\td3 := r.Direction.Cross(o.Direction)\n\n\tif !d3.Equals(NewVector(0, 0, 0)) {\n\t\tmatrix := [12]float64{\n\t\t\tr.Direction.X,\n\t\t\t-o.Direction.X,\n\t\t\td3.X,\n\t\t\to.Origin.X - r.Origin.X,\n\n\t\t\tr.Direction.Y,\n\t\t\t-o.Direction.Y,\n\t\t\td3.Y,\n\t\t\to.Origin.Y - r.Origin.Y,\n\n\t\t\tr.Direction.Z,\n\t\t\t-o.Direction.Z,\n\t\t\td3.Z,\n\t\t\to.Origin.Z - r.Origin.Z,\n\t\t}\n\n\t\tresult := solve(matrix, 3, 4)\n\n\t\ta := result[3]\n\t\tb := result[7]\n\t\tc := result[11]\n\n\t\tif a >= 0 && b >= 0 {\n\t\t\tdist := d3.MultiplyScalar(c)\n\t\t\tif dist.Length() <= width {\n\t\t\t\treturn clampInRange(r.At(a))\n\t\t\t}\n\t\t\treturn r.Origin, false\n\t\t}\n\t}\n\n\tdP := o.Origin.Multiply(r.Origin)\n\n\ta2 := r.Direction.Dot(dP)\n\tb2 := o.Direction.Dot(dP.Neg())\n\n\tif a2 < 0 && b2 < 0 {\n\t\tdist := r.Origin.Distance(dP)\n\t\tif dP.Length() <= width {\n\t\t\treturn clampInRange(r.At(dist))\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tp3a := r.Origin.Plus(r.Direction.MultiplyScalar(a2))\n\td3a := o.Origin.Minus(p3a)\n\n\tp3b := r.Origin\n\td3b := o.Origin.Plus(o.Direction.MultiplyScalar(b2)).Minus(p3b)\n\n\tif b2 < 0 {\n\t\tif d3a.Length() <= width {\n\t\t\treturn clampInRange(p3a)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif a2 < 0 {\n\t\tif d3b.Length() <= width {\n\t\t\treturn clampInRange(p3b)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif d3a.Length() <= d3b.Length() {\n\t\tif d3a.Length() <= width {\n\t\t\treturn clampInRange(p3a)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif d3b.Length() <= width {\n\t\treturn clampInRange(p3b)\n\t}\n\n\treturn r.Origin, false\n}", "func (g *Group) LocalIntersect(r *algebra.Ray) ([]*Intersection, bool) {\n\txs := make([]*Intersection, 0, 0)\n\tvar hit bool = false\n\n\t// Get the AABB of the group\n\tmin, max := g.GetBounds()\n\n\tif min == nil {\n\t\treturn xs, false\n\t}\n\tif GetBoundsTransform(min, max, g.GetTransform()).Intersect(r.Transform(g.GetTransform())) == false {\n\t\treturn xs, false\n\t}\n\n\tfor _, s := range g.shapes {\n\t\tm := s.GetTransform()\n\t\tri := r.Transform(m.Inverse())\n\t\tshapeXs, shapeHit := s.LocalIntersect(ri)\n\t\thit = hit || shapeHit\n\t\tfor _, t := range shapeXs {\n\t\t\txs = append(xs, t)\n\t\t}\n\t}\n\treturn xs, hit\n}", "func (s Sphere) RayIntersects(origin vector.Vector3, direction vector.Vector3, t0 float64) (float64, bool) {\n\t// solve for tc\n\t// find vector from ray origin to sphere center\n\tL := s.Center.Subtract(origin)\n\ttc := L.DotProduct(direction)\n\n\tif tc < 0.0 {\n\t\treturn t0, false\n\t}\n\td2 := L.DotProduct(L) - (tc * tc)\n\tr2 := s.Radius * s.Radius\n\tif d2 > r2 {\n\t\treturn t0, false\n\t}\n\n\t// solve t1c\n\tt1c := math.Sqrt(r2 - d2)\n\n\t// solve intersection points\n\tt0 = tc - t1c\n\tt1 := tc + t1c\n\tif t0 < 0.0 {\n\t\tt0 = t1\n\t}\n\tif t0 < 0.0 {\n\t\treturn t0, false\n\t}\n\treturn t0, true\n}", "func (self *Rectangle) Intersects(b *Rectangle) bool{\n return self.Object.Call(\"intersects\", b).Bool()\n}", "func (s *Scene) FindIntersection(r raytracing.Ray) (bool, float64, int) {\n\tcurrentObject := -1\n\tt := 20000.0\n\n\tvar intersected bool\n\tfor i, object := range s.Objects {\n\t\tif intersected, t = object.Intersect(r, t); intersected {\n\t\t\tcurrentObject = i\n\t\t}\n\t}\n\n\tintersected = (currentObject != -1)\n\treturn intersected, t, currentObject\n}", "func (e Entities) Intersect(rect pixel.Rect) bool {\n\t// check if any entities returned intersect the given point\n\tfor i := range e {\n\t\t// check for intersect\n\t\tif e[i].Intersects(rect) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (e *Entity) Intersects(o *Entity) bool {\n\tif e.Body.Position.X > o.Body.Position.X+o.Body.Width || e.Body.Position.X+e.Body.Width < o.Body.Position.X || e.Body.Position.Y > o.Body.Position.Y+o.Body.Height || e.Body.Position.Y+e.Body.Height < o.Body.Position.Y {\n\t\treturn false\n\t}\n\treturn true\n}", "func (self *Rectangle) IntersectsRawI(args ...interface{}) bool{\n return self.Object.Call(\"intersectsRaw\", args).Bool()\n}", "func TestIntersect(t *testing.T) {\n\ttype args struct {\n\t\ta interface{}\n\t\tb interface{}\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant interface{}\n\t}{\n\t\t{\n\t\t\tname: \"int64-slice-交集\",\n\t\t\targs: args{\n\t\t\t\ta: []int64{1, 2, 3, 4, 4, 5, 6},\n\t\t\t\tb: []int64{1, 3, 5, 7, 9, 11},\n\t\t\t},\n\t\t\twant: []int64{1, 3, 5},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar ret []int64\n\t\t\tif got := Intersect(tt.args.a, tt.args.b, &ret); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"Intersection() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (s *Sphere) Intersect(pt, ur Vector3) float64 {\n\t// if the vector is normalized, a is always 1\n\tb := ur.Scale(2).Dot(pt.Sub(s.point))\n\tc := pt.Sub(s.point).Dot(pt.Sub(s.point)) - s.radius*s.radius\n\tdisc := b*b - 4*c\n\tif disc < 0 {\n\t\treturn math.Inf(0)\n\t}\n\tt0 := (-b - math.Sqrt(disc)) / 2\n\tif t0 > 0 {\n\t\treturn t0 - EPSILON\n\t}\n\tt1 := (-b + math.Sqrt(disc)) / 2\n\treturn t1 - EPSILON\n}", "func (self *Rectangle) IntersectsRaw(left int, right int, top int, bottom int, tolerance int) bool{\n return self.Object.Call(\"intersectsRaw\", left, right, top, bottom, tolerance).Bool()\n}", "func (s1 Segment) Intersect(e2 Edge) (Vector, bool) {\n\treturn Intersect(s1, e2)\n}", "func (s *Sphere) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(s.position)\n\tdefer eye.Add(s.position)\n\n\tvar (\n\t\ta = v.X*v.X + v.Y*v.Y + v.Z*v.Z\n\t\tb = 2*float64(eye.X)*v.X + float64(eye.Y)*v.Y + float64(eye.Z)*v.Z\n\t\tc = float64(eye.X*eye.X + eye.Y*eye.Y + eye.Z*eye.Z - s.R*s.R)\n\t)\n\treturn utils.SecondDegree(a, b, c)\n}", "func (oCone OpenCone) Intersect(r ray.Ray) *space.Hit {\n\td := r.Direction\n\t// x0 := vec3.Subtract(vec3.Subtract(r.Origin, this.Position), vec3.Vec3{0,this.Height,0})\n\tx0 := vec3.Subtract(vec3.Subtract(r.Origin, oCone.Position), vec3.Multiply(oCone.Height, oCone.Normal))\n\n\ta := d.X*d.X + d.Z*d.Z - (d.Y*d.Y)*(oCone.Radius*oCone.Radius)\n\tb := 2*x0.X*d.X + 2*x0.Z*d.Z - (2*x0.Y*d.Y)*(oCone.Radius*oCone.Radius)\n\tc := x0.X*x0.X + x0.Z*x0.Z - (x0.Y*x0.Y)*(oCone.Radius*oCone.Radius)\n\n\tsqrtOf := b*b - 4*a*c\n\n\tif sqrtOf < 0 {\n\t\treturn nil\n\t}\n\tvar t float64\n\tif sqrtOf == 0 {\n\t\tt = -b / (2 * a)\n\t\tif !r.InRange(t) {\n\t\t\treturn nil\n\t\t}\n\t} else if sqrtOf > 0 {\n\t\tt = (-b - math.Sqrt(sqrtOf)) / (2 * a)\n\t\tif !r.InRange(t) {\n\t\t\tt = (-b + math.Sqrt(sqrtOf)) / (2 * a)\n\t\t\tif !r.InRange(t) {\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tpoint := r.PointAt(t)\n\n\tif point.Y < oCone.Position.Y || point.Y > oCone.Position.Y+oCone.Height {\n\t\treturn nil\n\t}\n\n\ttipToPoint := vec3.Subtract(point, vec3.Add(oCone.Position, vec3.Multiply(oCone.Height, oCone.Normal)))\n\tnormal := vec3.Normalize(vec3.CrossProduct(vec3.CrossProduct(tipToPoint, oCone.Normal), tipToPoint))\n\n\t// it is correct. Don't change it again!\n\tif vec3.DotProduct(r.Direction, normal) > 0 {\n\t\tnormal = vec3.Multiply(-1, normal)\n\t}\n\n\treturn &space.Hit{\n\t\tT: t,\n\t\tPosition: point,\n\t\tNormal: normal,\n\t\tMaterial: oCone.Material,\n\t\t// Material: Material_Normal{},\n\t}\n}", "func _v2dIntersect(p0 *Vec2d, p1 *Vec2d, p2 *Vec2d, p3 *Vec2d, inter *Vec2d) {\n\tvar s1, s2 Vec2d\n\n\ts1.x = p1.x - p0.x\n\ts1.y = p1.y - p0.y\n\ts2.x = p3.x - p2.x\n\ts2.y = p3.y - p2.y\n\n\tt := (s2.x*(p0.y-p2.y) - s2.y*(p0.x-p2.x)) / (-s2.x*s1.y + s1.x*s2.y)\n\n\tinter.x = p0.x + (t * s1.x)\n\tinter.y = p0.y + (t * s1.y)\n}", "func (g Object) Intersects(o Object) bool {\n\treturn g.bridge().Intersects(o.bridge())\n}", "func (pn Plane) DoesRayIntersect(r rays.Ray) (doesIntersect bool, intersectPoint0 rays.Point, intersectPoint1 rays.Point) {\n\tvar p0 rays.Point\n\tsurfaceNormal := pn.NormalAtPoint(intersectPoint0)\n\tdenom := rays.DotProduct(surfaceNormal.Direction, r.Direction)\n\n\tif denom < 1e-6 {\n\t\treturn false, p0, p0\n\t}\n\n\ttop := rays.DotProduct(rays.Subtract(surfaceNormal.Origin, r.Origin), surfaceNormal.Direction)\n\tt := top / denom\n\n\tif t < 0 {\n\t\treturn false, p0, p0\n\t}\n\tp0 = rays.Add(r.Origin, rays.Multiply(r.Direction, t))\n\treturn true, p0, p0\n}", "func (p *PGeometry) Intersects(other *Geometry) (bool, error) {\n\treturn p.predicate(\"intersects\", cGEOSPreparedIntersects, other)\n}", "func rprismIntersects(q *rprismIntersectQ) (float64, bool) {\n\tt := (q.bcPlane - q.v[0]) / q.d[0]\n\tif t < 0 {\n\t\treturn 0, false\n\t}\n\tb := q.v[1] + t*q.d[1]\n\tc := q.v[2] + t*q.d[2]\n\tif b >= q.minB && b <= q.maxB && c >= q.minC && c <= q.maxC {\n\t\treturn t, true\n\t}\n\treturn 0, false\n}", "func (r *Ray) IntersectSphere(s Sphere) (float64, float64) {\n\toc := r.Origin.Minus(s.Center)\n\tk1 := r.Direction.Dot(r.Direction)\n\tk2 := 2 * oc.Dot(r.Direction)\n\tk3 := oc.Dot(oc) - s.Radius*s.Radius\n\n\tdiscriminant := k2*k2 - 4*k1*k3\n\tif discriminant < 0 {\n\t\treturn math.Inf(1), math.Inf(1)\n\t}\n\n\tt1 := (-k2 + math.Sqrt(discriminant)) / (2 * k1)\n\tt2 := (-k2 - math.Sqrt(discriminant)) / (2 * k1)\n\treturn t1, t2\n}", "func (rc *Raycaster) IntersectObjects(inodes []INode, recursive bool) []Intersect {\n\n\tintersects := []Intersect{}\n\tfor _, inode := range inodes {\n\t\trc.intersectObject(inode, &intersects, recursive)\n\t}\n\tsort.Slice(intersects, func(i, j int) bool {\n\t\treturn intersects[i].Distance < intersects[j].Distance\n\t})\n\treturn intersects\n}", "func (self *Rectangle) IntersectionI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"intersection\", args)}\n}", "func (b *BasicShape) IntersectP(geometry.Ray) bool {\n\tpanic(\"IntersectP is not implemented for basic shape\")\n}", "func (p *Plan) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(p.position)\n\tdefer eye.Add(p.position)\n\n\tif v.Z == 0 {\n\t\treturn 0\n\t}\n\treturn -float64(eye.Z) / v.Z\n}", "func (intGroup intersectionGroup) Intersect(r ray.Ray) *space.Hit {\n\tvar furthestHit *space.Hit\n\tvar h *space.Hit\n\n\tfor _, shape := range intGroup.shapes {\n\t\th = shape.Intersect(r)\n\t\tif h == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif furthestHit == nil || h.T > furthestHit.T {\n\t\t\tfurthestHit = h\n\t\t}\n\t}\n\n\treturn furthestHit\n}", "func Test_314(t *testing.T) {\n\ttestName := \"Test_314\"\n\trunStart := time.Now()\n\tfmt.Printf(\"%s BBox Intersections\\n\", testName)\n\tdefer func() {\n\t\tVerbose.Printf(\"%s took %v\\n\", testName, time.Since(runStart))\n\t}()\n\tvar (\n\t\tmybox BBox = BBox{MinX: -76.932480, MinY: 36.549660, MaxX: -76.407532, MaxY: 36.921856}\n\t\trailbox BBox = BBox{MinX: -76.917970, MinY: 36.682432, MaxX: -76.916911, MaxY: 36.684338}\n\t)\n\n\tif !mybox.Sane() || !railbox.Sane() {\n\t\tt.Fatalf(\"Intersects() failed\")\n\t}\n\texpected := true\n\tvalue1 := mybox.Intersects(railbox)\n\tif value1 != expected {\n\t\tt.Errorf(\"Intersects() failed\")\n\t}\n\tvalue2 := railbox.Intersects(mybox)\n\tif value2 != expected {\n\t\tt.Errorf(\"Intersects() failed\")\n\t}\n}", "func (mr *MockVirtualMeshSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockVirtualMeshSet)(nil).Intersection), set)\n}", "func (p *Ball) Intersection(line *objects.Ray) (position, color,\n\tnormal *objects.Vector, diffuse,\n\tspecularIntensity, specularPower, reflectivity float64) {\n\n\tposition = p.sphere.Intersection(line)\n\tif position == nil {\n\t\treturn\n\t}\n\tcolor = p.Color()\n\tnormal = position.SubtractVector(p.Sphere().Position())\n\tdiffuse = p.Diffuse()\n\tspecularIntensity = p.SpecularIntensity()\n\tspecularPower = p.SpecularPower()\n\treflectivity = p.Reflectivity()\n\treturn\n}", "func Intersect(r1, r2 *Rect) bool {\n\t// There are four cases of overlap:\n\t//\n\t// 1. a1------------b1\n\t// a2------------b2\n\t// p--------q\n\t//\n\t// 2. a1------------b1\n\t// a2------------b2\n\t// p--------q\n\t//\n\t// 3. a1-----------------b1\n\t// a2-------b2\n\t// p--------q\n\t//\n\t// 4. a1-------b1\n\t// a2-----------------b2\n\t// p--------q\n\t//\n\t// Thus there are only two cases of non-overlap:\n\t//\n\t// 1. a1------b1\n\t// a2------b2\n\t//\n\t// 2. a1------b1\n\t// a2------b2\n\t//\n\t// Enforced by constructor: a1 <= b1 and a2 <= b2. So we can just\n\t// check the endpoints.\n\n\tfor i := range r1.p {\n\t\ta1, b1, a2, b2 := r1.p[i], r1.q[i], r2.p[i], r2.q[i]\n\t\tif b2 <= a1 || b1 <= a2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (self *Rectangle) Intersection(b *Rectangle, out *Rectangle) *Rectangle{\n return &Rectangle{self.Object.Call(\"intersection\", b, out)}\n}", "func (g *Circle) Intersects(obj Object) bool {\n\tswitch other := obj.(type) {\n\tcase *Point:\n\t\treturn g.containsPoint(other.Center())\n\tcase *Circle:\n\t\treturn other.Distance(g) <= (other.meters + g.meters)\n\tcase Collection:\n\t\tfor _, p := range other.Children() {\n\t\t\tif g.Intersects(p) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t\treturn false\n\tcase *Feature:\n\t\treturn g.Intersects(other.base)\n\tdefault:\n\t\t// No simple cases, so using polygon approximation.\n\t\treturn g.getObject().Intersects(obj)\n\t}\n}", "func (mr *MockEnvoyFilterSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockEnvoyFilterSet)(nil).Intersection), set)\n}", "func RectIntersects(aMinX, aMinY, aMaxX, aMaxY, bMinX, bMinY, bMaxX, bMaxY float64) bool {\n\treturn !(aMaxX < bMinX || aMinX > bMaxX || aMaxY < bMinY || aMinY > bMaxY)\n}", "func (tri *Triangle) IntersectsPoint(v quadedge.Vertex) bool {\n\te := tri.Qe\n\n\tfor i := 0; i < 3; i++ {\n\t\tlc := v.Classify(e.Orig(), e.Dest())\n\t\tswitch lc {\n\t\t// return true if v is on the edge\n\t\tcase quadedge.ORIGIN:\n\t\t\treturn true\n\t\tcase quadedge.DESTINATION:\n\t\t\treturn true\n\t\tcase quadedge.BETWEEN:\n\t\t\treturn true\n\t\t// return false if v is well outside the triangle\n\t\tcase quadedge.LEFT:\n\t\t\treturn false\n\t\tcase quadedge.BEHIND:\n\t\t\treturn false\n\t\tcase quadedge.BEYOND:\n\t\t\treturn false\n\t\t}\n\t\t// go to the next edge of the triangle.\n\t\te = e.RNext()\n\t}\n\n\t// if v is to the right of all edges, it is inside the triangle.\n\treturn true\n}", "func IntersectPMultiple(primitives []Primitive, ray geometry.Ray) bool {\n\tfor _, pr := range primitives {\n\t\tif intersected := pr.IntersectP(ray); intersected {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (r Rect) Intersect(s Rect) Rect {\n\tt := R(\n\t\tmath.Max(r.Min.X, s.Min.X),\n\t\tmath.Max(r.Min.Y, s.Min.Y),\n\t\tmath.Min(r.Max.X, s.Max.X),\n\t\tmath.Min(r.Max.Y, s.Max.Y),\n\t)\n\tif t.Min.X >= t.Max.X || t.Min.Y >= t.Max.Y {\n\t\treturn Rect{}\n\t}\n\treturn t\n}", "func (geom Geometry) Intersects(other Geometry) bool {\n\tval := C.OGR_G_Intersects(geom.cval, other.cval)\n\treturn val != 0\n}", "func (b BoundingBox) Intersects(o BoundingBox) bool {\n\tif b.MaxX < o.MinX {\n\t\treturn false // a is left of b\n\t}\n\n\tif b.MinX > o.MaxX {\n\t\treturn false // a is right of b\n\t}\n\tif b.MaxY < o.MinY {\n\t\treturn false // a is above b\n\t}\n\n\tif b.MinY > o.MaxY {\n\t\treturn false // a is below b\n\t}\n\n\treturn true // boxes overlap\n}", "func (diffGroup differenceGroup) Intersect(r ray.Ray) *space.Hit {\n\thit := diffGroup.minuend.Intersect(r)\n\tif hit == nil {\n\t\treturn nil\n\t}\n\tif diffGroup.subtrahend.Includes(hit.Position) {\n\t\torignalT := hit.T\n\t\tr.Origin = hit.Position\n\t\t// r.T0 = 0.1\n\t\thit = diffGroup.subtrahend.Intersect(r)\n\t\tif hit == nil { // Should not happen. But it can when t.T0 is not 0\n\t\t\treturn nil\n\t\t}\n\t\tif !diffGroup.minuend.Includes(hit.Position) {\n\t\t\treturn nil\n\t\t}\n\t\thit.Normal = vec3.Multiply(-1, hit.Normal)\n\t\thit.T += orignalT\n\t}\n\treturn hit\n}", "func (mr *MockMutableListMockRecorder) Intersect(other interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersect\", reflect.TypeOf((*MockMutableList)(nil).Intersect), other)\n}", "func (mr *MockVirtualServiceSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockVirtualServiceSet)(nil).Intersection), set)\n}", "func IntersectPlane( plane_p, plane_n Vec3D, lineStart , lineEnd Vec3D ) Vec3D {\n plane_n = plane_n.Normalize()\n plane_d := -plane_n.Dot( plane_p)\n ad := lineStart.Dot(plane_n)\n bd := lineEnd.Dot(plane_n)\n t := (-plane_d - ad) / (bd - ad)\n lineStartToEnd := lineEnd.Sub(lineStart)\n lineToIntersect := lineStartToEnd.Mul(t)\n return lineStart.Add(lineToIntersect)\n}", "func (mr *MockListMockRecorder) Intersect(other interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersect\", reflect.TypeOf((*MockList)(nil).Intersect), other)\n}", "func (poly Polygon) Intersect(poly2 Polygon) bool {\r\n\tvertices := poly.GetWorldVertices()\r\n\tvertices2 := poly2.GetWorldVertices()\r\n\tfor i := 1; i < len(vertices); i++ {\r\n\t\tedgeVec := linalg.Vector2f64{X: vertices[i].X - vertices[i-1].X, Y: vertices[i].Y - vertices[i-1].Y}\r\n\t\taxis := edgeVec.NormalVec()\r\n\t\tseg0 := poly2.ProjectOn(axis)\r\n\t\tseg1 := poly.ProjectOn(axis)\r\n\t\tif !overlap(seg0, seg1) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\tfor i := 1; i < len(vertices2); i++ {\r\n\t\tedgeVec := linalg.Vector2f64{X: vertices2[i].X - vertices2[i-1].X, Y: vertices2[i].Y - vertices2[i-1].Y}\r\n\t\taxis := edgeVec.NormalVec()\r\n\t\tseg0 := poly2.ProjectOn(axis)\r\n\t\tseg1 := poly.ProjectOn(axis)\r\n\t\tif !overlap(seg0, seg1) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func HasIntersection(op shared.Operation, shapes map[string]shared.Operation) (bool, string) {\n\treturn collision.CollideWithOtherShapes(op, shapes)\n}", "func (orth *Orthotope) Intersects(o *Orthotope) int32 {\n\tinT := int32(0)\n\toutT := int32(math.MaxInt32)\n\tfor index, p0 := range o.Point {\n\t\tp1 := o.Delta[index] + p0\n\n\t\tif orth.Delta[index] == 0 {\n\t\t\tif orth.Point[index] < p0 || p1 < orth.Point[index] {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t} else {\n\t\t\tif orth.Delta[index] < 0 {\n\t\t\t\t// Swap p0 and p1 for negative directions.\n\t\t\t\tp0, p1 = p1, p0\n\t\t\t}\n\t\t\tp0T := ((p0 - orth.Point[index]) << ACCURACY) / orth.Delta[index]\n\t\t\tinT = disc.Max(inT, p0T)\n\n\t\t\tp1T := ((p1 - orth.Point[index]) << ACCURACY) / orth.Delta[index]\n\t\t\toutT = disc.Min(outT, p1T)\n\t\t}\n\t}\n\n\tif inT < outT && inT >= 0 {\n\t\treturn inT\n\t}\n\treturn -1\n}", "func (rc *Raycaster) IntersectObject(inode INode, recursive bool) []Intersect {\n\n\tintersects := []Intersect{}\n\trc.intersectObject(inode, &intersects, recursive)\n\tsort.Slice(intersects, func(i, j int) bool {\n\t\treturn intersects[i].Distance < intersects[j].Distance\n\t})\n\treturn intersects\n}", "func (b *Bound) Intersects(bound *Bound) bool {\n\n\tif (b.ne[0] < bound.sw[0]) ||\n\t\t(b.sw[0] > bound.ne[0]) ||\n\t\t(b.ne[1] < bound.sw[1]) ||\n\t\t(b.sw[1] > bound.ne[1]) {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (self IntRect) Intersects(rect IntRect) (*IntRect, bool) {\n\tintersect := new(C.sfIntRect)\n\tb := C.sfIntRect_intersects(self.Cref, rect.Cref, intersect) == 1\n\treturn &IntRect{intersect}, b\n}", "func (t Torus) Intersect(a, b Rectangle) Rectangle {\n\ta, b = t.AlignRects(a, b)\n\treturn a.Intersect(b)\n}", "func (g SimplePoint) Intersects(o Object) bool {\n\treturn intersectsObjectShared(g, o,\n\t\tfunc(v Polygon) bool {\n\t\t\treturn poly.Point(Position{X: g.X, Y: g.Y, Z: 0}).Intersects(polyExteriorHoles(v.Coordinates))\n\t\t},\n\t\tfunc(v MultiPolygon) bool {\n\t\t\tfor _, c := range v.Coordinates {\n\t\t\t\tif poly.Point(Position{X: g.X, Y: g.Y, Z: 0}).Intersects(polyExteriorHoles(c)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t)\n}", "func Intersection() {\n\n}", "func (c MethodsCollection) Intersect() pIntersect {\n\treturn pIntersect{\n\t\tMethod: c.MustGet(\"Intersect\"),\n\t}\n}", "func intersect(b, c *Block, postnum []int, idom []*Block) *Block {\n\t// TODO: This loop is O(n^2). It used to be used in nilcheck,\n\t// see BenchmarkNilCheckDeep*.\n\tfor b != c {\n\t\tif postnum[b.ID] < postnum[c.ID] {\n\t\t\tb = idom[b.ID]\n\t\t} else {\n\t\t\tc = idom[c.ID]\n\t\t}\n\t}\n\treturn b\n}", "func intersects(p1, q1, p2, q2 *node) bool {\n\tif (equals(p1, q1) && equals(p2, q2)) ||\n\t\t(equals(p1, q2) && equals(p2, q1)) {\n\t\treturn true\n\t}\n\treturn (area(p1, q1, p2) > 0.0) != (area(p1, q1, q2) > 0.0) &&\n\t\t(area(p2, q2, p1) > 0.0) != (area(p2, q2, q1) > 0.0)\n}", "func TestIntersectionHorizontal(t *testing.T) {\n\tsegment1, err := newLineSegment(point{x: 0, y: 0}, point{x: 10, y: 0})\n\tif err != nil {\n\t\tt.Error(\"error\")\n\t}\n\n\tsegment2, err := newLineSegment(point{x: 5, y: -10}, point{x: 5, y: 10})\n\tif err != nil {\n\t\tt.Error(\"error\")\n\t}\n\n\tintersection, points := doesIntersect(segment1, segment2)\n\n\tif !intersection {\n\t\tt.Error(\"segments should intersect\")\n\t}\n\n\tpoint := points[0]\n\n\tif point.x != 5 && point.y != 0 {\n\t\tt.Error(\"intersection point should be {5, 0}\")\n\t}\n}", "func (a *AABB) Intersect(b *AABB) bool {\n\tif b.center.x+b.half.x < a.center.x-a.half.x {\n\t\treturn false\n\t}\n\tif b.center.y+b.half.y < a.center.y-a.half.y {\n\t\treturn false\n\t}\n\tif b.center.x-b.half.x > a.center.x+a.half.x {\n\t\treturn false\n\t}\n\tif b.center.y-b.half.y > a.center.y+a.half.y {\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (e Entities) Intersects(rect pixel.Rect) (entities Entities) {\n\t// check if any entities returned intersect the given point and if they do add them to the return list\n\tfor i := range e {\n\t\t// add to list if they intersect\n\t\tif e[i].Intersects(rect) {\n\t\t\tentities = append(entities, e[i])\n\t\t}\n\t}\n\treturn\n}", "func (r Ray) Contains(pos Vec) bool {\n\treturn r.Formula(pos) == 0 && r.InAABB(pos)\n}", "func (i *Result) Intersection() []geom.Coord {\n\treturn i.intersection\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Intersection), set)\n}", "func intersectsWithRaycast(point *geo.Point, start geo.Point, end geo.Point) bool {\n\t// Always ensure that the the first point\n\t// has a y coordinate that is less than the second point\n\tif start.Lng() > end.Lng() {\n\n\t\t// Switch the points if otherwise.\n\t\tstart, end = end, start\n\n\t}\n\n\t// Move the point's y coordinate\n\t// outside of the bounds of the testing region\n\t// so we can start drawing a ray\n\tfor point.Lng() == start.Lng() || point.Lng() == end.Lng() {\n\t\tnewLng := math.Nextafter(point.Lng(), math.Inf(1))\n\t\tpoint = geo.NewPoint(point.Lat(), newLng)\n\t}\n\n\t// If we are outside of the polygon, indicate so.\n\tif point.Lng() < start.Lng() || point.Lng() > end.Lng() {\n\t\treturn false\n\t}\n\n\tif start.Lat() > end.Lat() {\n\t\tif point.Lat() > start.Lat() {\n\t\t\treturn false\n\t\t}\n\t\tif point.Lat() < end.Lat() {\n\t\t\treturn true\n\t\t}\n\n\t} else {\n\t\tif point.Lat() > end.Lat() {\n\t\t\treturn false\n\t\t}\n\t\tif point.Lat() < start.Lat() {\n\t\t\treturn true\n\t\t}\n\t}\n\n\traySlope := (point.Lng() - start.Lng()) / (point.Lat() - start.Lat())\n\tdiagSlope := (end.Lng() - start.Lng()) / (end.Lat() - start.Lat())\n\n\treturn raySlope >= diagSlope\n}", "func (intGroup intersectionGroup) Includes(point vec3.Vec3) bool {\n\tfor _, shape := range intGroup.shapes {\n\t\tif !shape.Includes(point) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func TestIntersection(t *testing.T) {\n\ttests := []struct {\n\t\tnote string\n\t\trules []string\n\t\texpected interface{}\n\t}{\n\t\t{\"intersection_0_sets\", []string{`p = x { intersection(set(), x) }`}, \"[]\"},\n\t\t{\"intersection_2_sets\", []string{`p = x { intersection({set(), {1, 2}}, x) }`}, \"[]\"},\n\t\t{\"intersection_2_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2}; intersection({s1, s2}, x) }`}, \"[2]\"},\n\t\t{\"intersection_3_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2, 3, 4}; s3 = {4, 5, 6}; intersection({s1, s2, s3}, x) }`}, \"[]\"},\n\t\t{\"intersection_4_sets\", []string{`p = x { s1 = {\"a\", \"b\", \"c\", \"d\"}; s2 = {\"b\", \"c\", \"d\"}; s3 = {\"c\", \"d\"}; s4 = {\"d\"}; intersection({s1, s2, s3, s4}, x) }`}, \"[\\\"d\\\"]\"},\n\t}\n\n\tdata := loadSmallTestData()\n\n\tfor _, tc := range tests {\n\t\trunTopDownTestCase(t, data, tc.note, tc.rules, tc.expected)\n\t}\n}", "func (mr *MockServiceEntrySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockServiceEntrySet)(nil).Intersection), set)\n}", "func (g Object) IntersectsBBox(bbox BBox) bool {\n\treturn g.bridge().IntersectsBBox(geojson.BBox{\n\t\tMin: geojson.Position{bbox.Min.X, bbox.Min.Y, bbox.Min.Z},\n\t\tMax: geojson.Position{bbox.Max.X, bbox.Max.Y, bbox.Max.Z},\n\t})\n}", "func (r Ray) LineIntersectCircle(c Circ) (g, h Vec) {\n\t/*\n\t\t(X - c.C.X)^2 + (Y - c.C.Y)^2 = c.R*c.R\n\t\tr.V.Y*X - r.V.X*Y - r.V.Y*r.O.X + r.V.X*r.O.Y = 0\n\n\t\tX*X - 2*c.C.X*X + c.C.X*c.C.X + Y*Y - 2*c.C.Y*Y + c.C.Y*c.C.Y = c.R*c.R\n\t\t(r.V.X*Y + r.V.Y*r.O.X - r.V.X*r.O.Y) / r.V.Y = X\n\n\t\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\t\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\n\t\tX*X - 2*c.C.X*X + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t(r.V.X*Y + b) / r.V.Y = X\n\n\t\t(r.V.X*Y + b)^2 / r.V.Y*r.V.Y - 2*c.C.X * (r.V.X*Y + b) / r.V.Y + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t// * r.V.Y*r.V.Y\n\t\t(r.V.X*Y + b)^2 - 2*c.C.X*r.V.Y * (r.V.X*Y + b) + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// brackets\n\t\tr.V.X*r.V.X*Y*Y + 2*b*r.V.X*Y + b*b - 2*c.C.X*r.V.Y*r.V.X*Y - 2*c.C.X*r.V.Y*b + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// simplify\n\t\tY*Y * (r.V.X*r.V.X + r.V.Y*r.V.Y) + Y * (2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y) + b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y = 0\n\n\t\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\t\te := 2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y\n\t\tf := b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y\n\n\t\te := 2 * (b*r.V.X - r.V.Y * (c.C.X*r.V.X + c.C.Y*r.V.Y))\n\t*/\n\n\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\te := 2 * (b*r.V.X - r.V.Y*(c.C.X*r.V.X+c.C.Y*r.V.Y))\n\tf := b*b - r.V.Y*(2*c.C.X*b-a*r.V.Y)\n\n\tg.Y, h.Y = Polynomial(d, e, f)\n\tif r.V.Y == 0 {\n\t\tg.X, h.X = c.ProjectY(g.Y)\n\t} else {\n\t\tg.X = r.ProjectY(g.Y)\n\t\th.X = r.ProjectY(h.Y)\n\t}\n\n\treturn\n}", "func (mr *MockVirtualDestinationSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockVirtualDestinationSet)(nil).Intersection), set)\n}", "func (mr *MockFailoverServiceSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockFailoverServiceSet)(nil).Intersection), set)\n}", "func (mr *MockWasmDeploymentSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockWasmDeploymentSet)(nil).Intersection), set)\n}", "func (g *Gene) Intersect(region Coor) bool {\n\treturn region.Intersect(g.Coordinate)\n}", "func (r Ray) InAABB(pos Vec) bool {\n\tp := r.O.To(pos)\n\tif r.V.Y == 0 {\n\t\tp.Y = 0\n\t} else {\n\t\tp.Y /= r.V.Y\n\t}\n\tif r.V.X == 0 {\n\t\tp.X = 0\n\t} else {\n\t\tp.X /= r.V.X\n\t}\n\treturn p.X <= 1 && p.Y <= 1 && p.X >= 0 && p.Y >= 0\n}", "func (mr *MockAuthorizationPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockAuthorizationPolicySet)(nil).Intersection), set)\n}", "func Intersect(queries ...Query) VariadicQuery {\n\treturn VariadicQuery{\n\t\tOperator: QueryIntersect,\n\t\tQueries: queries,\n\t}\n}", "func boundsIntersects(sa, sb, oa, ob *Point) bool {\n\tvar s_minx, s_miny, s_maxx, s_maxy = bounds(sa, sb)\n\tvar o_minx, o_miny, o_maxx, o_maxy = bounds(oa, ob)\n\t//not disjoint\n\treturn !(o_minx > s_maxx || o_maxx < s_minx || o_miny > s_maxy || o_maxy < s_miny)\n}", "func (i Intersections) Hit() (Intersection, bool) {\n\ti.Sort()\n\n\tfor _, intersection := range i {\n\t\tif intersection.T >= 0 {\n\t\t\treturn intersection, true\n\t\t}\n\t}\n\n\treturn Intersection{}, false\n}", "func (n *numbers) Intersect() []int {\n\tm := map[int]int{}\n\tfor _, el := range n.nums1 {\n\t\tm[el]++\n\t}\n\tout := make([]int, 0)\n\tfor _, el := range n.nums2 {\n\t\tif m[el] > 0 {\n\t\t\tm[el]--\n\t\t\tout = append(out, el)\n\t\t}\n\t}\n\treturn out\n}", "func (s Sphere) Hit(ray geo.Ray) (bool, geo.Point3D) {\n\tp := ray.Endpoint\n\tv := ray.Direction\n\tradius := s.radius\n\tcenter := s.center\n\tb := 2 * ((p.X-center.X)*v.X + (p.Y-center.Y)*v.Y + (p.Z-center.Z)*v.Z)\n\tc := (p.X-center.X)*(p.X-center.X) + (p.Y-center.Y)*(p.Y-center.Y) + (p.Z-center.Z)*(p.Z-center.Z) - radius*radius\n\tdelta := b*b - 4*c\n\tvar isHit bool\n\tvar hitPoint geo.Point3D\n\tif delta >= 0.0 {\n\t\tisHit = true\n\t\tresultA := -(b + math.Sqrt(delta)) / 2.0\n\t\tresultB := -(b - math.Sqrt(delta)) / 2.0\n\t\tvar result float64\n\t\tif resultA*resultA < resultB*resultB {\n\t\t\tresult = resultA\n\t\t} else {\n\t\t\tresult = resultB\n\t\t}\n\n\t\tif result < 0.00001 {\n\t\t\tisHit = false\n\t\t}\n\n\t\thitPoint = geo.Point3D{\n\t\t\tX: result*v.X + p.X,\n\t\t\tY: result*v.Y + p.Y,\n\t\t\tZ: result*v.Z + p.Z,\n\t\t}\n\t} else {\n\t\tisHit = false\n\t\thitPoint = geo.Point3D{}\n\t}\n\n\treturn isHit, hitPoint\n}", "func (r Ray) IntersectsCircle(c Circ) bool {\n\treturn r.LineIntersectsCircle(c) && r.InAABB(c.C)\n}", "func (mr *MockServiceDependencySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockServiceDependencySet)(nil).Intersection), set)\n}", "func (b *BasicShape) CanIntersect() bool {\n\treturn true\n}", "func (mr *MockTrafficPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockTrafficPolicySet)(nil).Intersection), set)\n}", "func CheckIntersect(original, extras []string) bool {\n\tfor _, i := range original {\n\t\tfor _, x := range extras {\n\t\t\tif i == x {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn false\n}", "func (m *MockVirtualMeshSet) Intersection(set v1alpha1sets.VirtualMeshSet) v1alpha1sets.VirtualMeshSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Intersection\", set)\n\tret0, _ := ret[0].(v1alpha1sets.VirtualMeshSet)\n\treturn ret0\n}" ]
[ "0.74060893", "0.732763", "0.6979644", "0.68721515", "0.6831556", "0.68281", "0.66193557", "0.6575707", "0.65466934", "0.65392756", "0.6522488", "0.6492574", "0.64610386", "0.64063007", "0.6380784", "0.6371579", "0.6317271", "0.6311212", "0.62917763", "0.62733907", "0.618304", "0.6164722", "0.6155212", "0.61426026", "0.61190903", "0.60978025", "0.6081524", "0.60369265", "0.59694654", "0.5966465", "0.59305984", "0.59158707", "0.59079254", "0.58777213", "0.5869876", "0.5850232", "0.58387554", "0.58381987", "0.58251846", "0.58191586", "0.57693124", "0.57687676", "0.57624155", "0.5754912", "0.5754518", "0.57524073", "0.57289195", "0.5722027", "0.5716264", "0.57136315", "0.5703296", "0.5695688", "0.56846243", "0.5680373", "0.5675584", "0.5652464", "0.56506056", "0.56492096", "0.56270736", "0.562088", "0.56142575", "0.5595112", "0.5573553", "0.55650234", "0.556341", "0.55616266", "0.55587655", "0.55557305", "0.5544605", "0.55393153", "0.5534762", "0.5524946", "0.5514382", "0.54926944", "0.5490034", "0.5485922", "0.54839045", "0.544464", "0.5430597", "0.54221344", "0.5419586", "0.5396342", "0.5393859", "0.53928167", "0.5391072", "0.53910345", "0.53721035", "0.5368299", "0.53648764", "0.53594977", "0.53467464", "0.5338839", "0.5334335", "0.5323646", "0.53157645", "0.53106225", "0.5306779", "0.5295613", "0.52823144", "0.5274513" ]
0.8042535
0
IntersectP checks whether a ray itnersects any of the voxel's primitives. It does not return intersection data so it is faster than the Intersect method.
func (v *Voxel) IntersectP(ray geometry.Ray) bool { return primitive.IntersectPMultiple(v.primitives, ray) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (b Bounds3) IntersectP(ray Ray) (bool, float64, float64) {\n\tt0 := float64(0)\n\tt1 := ray.tMax\n\tfor i := 0; i < 3; i++ {\n\t\t// cheaper to multiply than divide so compute reciprocal first\n\t\tinvRayDir := 1 / ray.Dir.Get(i)\n\t\ttNear := (b.pMin.Get(i) - ray.Orig.Get(i)) * invRayDir\n\t\ttFar := (b.pMax.Get(i) - ray.Orig.Get(i)) * invRayDir\n\t\tif tNear > tFar {\n\t\t\ttNear, tFar = tFar, tNear\n\t\t}\n\t\t//TODO: update tFar to be more robust\n\t\tif tNear > 0 {\n\t\t\tt0 = tNear\n\t\t}\n\t\tif tFar < t1 {\n\t\t\tt1 = tFar\n\t\t}\n\t\tif t0 > t1 {\n\t\t\treturn false, 0, 0\n\t\t}\n\t}\n\treturn true, t0, t1\n}", "func (b *BasicShape) IntersectP(geometry.Ray) bool {\n\tpanic(\"IntersectP is not implemented for basic shape\")\n}", "func (v *Voxel) Intersect(ray geometry.Ray, in *primitive.Intersection) bool {\n\treturn primitive.IntersectMultiple(v.primitives, ray, in)\n}", "func (p *RPrism) Intersect(r Ray) (float64, *Material, Vec3, Vec3, bool) {\n\tqueries := []*rprismIntersectQ{\n\t\t{\n\t\t\t[3]float64{r.V.X, r.V.Y, r.V.Z},\n\t\t\t[3]float64{r.D.X, r.D.Y, r.D.Z},\n\t\t\tp.Pos.X, p.Pos.Y, p.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2],\n\t\t\tVec3{-1, 0, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.X, r.V.Y, r.V.Z},\n\t\t\t[3]float64{r.D.X, r.D.Y, r.D.Z},\n\t\t\tp.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2],\n\t\t\tVec3{1, 0, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Y, r.V.Z, r.V.X},\n\t\t\t[3]float64{r.D.Y, r.D.Z, r.D.X},\n\t\t\tp.Pos.Y, p.Pos.Z, p.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0],\n\t\t\tVec3{0, -1, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Y, r.V.Z, r.V.X},\n\t\t\t[3]float64{r.D.Y, r.D.Z, r.D.X},\n\t\t\tp.Pos.Y + p.Dim[1], p.Pos.Z, p.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0],\n\t\t\tVec3{0, 1, 0},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Z, r.V.X, r.V.Y},\n\t\t\t[3]float64{r.D.Z, r.D.X, r.D.Y},\n\t\t\tp.Pos.Z, p.Pos.X, p.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1],\n\t\t\tVec3{0, 0, -1},\n\t\t},\n\t\t{\n\t\t\t[3]float64{r.V.Z, r.V.X, r.V.Y},\n\t\t\t[3]float64{r.D.Z, r.D.X, r.D.Y},\n\t\t\tp.Pos.Z + p.Dim[2], p.Pos.X, p.Pos.X + p.Dim[0], p.Pos.Y, p.Pos.Y + p.Dim[1],\n\t\t\tVec3{0, 0, 1},\n\t\t},\n\t}\n\tnearest := math.MaxFloat64\n\tfound := false\n\tvar normal Vec3\n\tfor _, q := range queries {\n\t\td, ok := rprismIntersects(q)\n\t\tif ok {\n\t\t\tif d > minDistance && d < nearest {\n\t\t\t\tfound = true\n\t\t\t\tnearest = d\n\t\t\t\tnormal = q.normal\n\t\t\t}\n\t\t}\n\t}\n\n\tif !found {\n\t\treturn 0, nil, Vec3{}, Vec3{}, false\n\t}\n\tpt := r.At(nearest)\n\treturn nearest, p.Mat, pt, normal, found\n}", "func (r Ray) Intersect(s Ray) (v Vec, ok bool) {\n\tif r.Colinear(s) {\n\t\treturn\n\t}\n\n\tv = r.LineIntersect(s)\n\n\treturn v, r.InAABB(v) && s.InAABB(v)\n}", "func (rx *RotationX) Intersection(ray geometry.Ray, tMin, tMax float64, rng *rand.Rand) (*material.RayHit, bool) {\r\n\r\n\trotatedRay := ray\r\n\r\n\trotatedRay.Origin.Y = rx.cosTheta*ray.Origin.Y + rx.sinTheta*ray.Origin.Z\r\n\trotatedRay.Origin.Z = -rx.sinTheta*ray.Origin.Y + rx.cosTheta*ray.Origin.Z\r\n\r\n\trotatedRay.Direction.Y = rx.cosTheta*ray.Direction.Y + rx.sinTheta*ray.Direction.Z\r\n\trotatedRay.Direction.Z = -rx.sinTheta*ray.Direction.Y + rx.cosTheta*ray.Direction.Z\r\n\r\n\trayHit, wasHit := rx.Primitive.Intersection(rotatedRay, tMin, tMax, rng)\r\n\tif wasHit {\r\n\t\tunrotatedNormal := rayHit.NormalAtHit\r\n\t\tunrotatedNormal.Y = rx.cosTheta*rayHit.NormalAtHit.Y - rx.sinTheta*rayHit.NormalAtHit.Z\r\n\t\tunrotatedNormal.Z = rx.sinTheta*rayHit.NormalAtHit.Y + rx.cosTheta*rayHit.NormalAtHit.Z\r\n\t\treturn &material.RayHit{\r\n\t\t\tRay: ray,\r\n\t\t\tNormalAtHit: unrotatedNormal,\r\n\t\t\tTime: rayHit.Time,\r\n\t\t\tU: rayHit.U,\r\n\t\t\tV: rayHit.V,\r\n\t\t\tMaterial: rayHit.Material,\r\n\t\t}, true\r\n\t}\r\n\treturn nil, false\r\n}", "func (c MethodsCollection) Intersect() pIntersect {\n\treturn pIntersect{\n\t\tMethod: c.MustGet(\"Intersect\"),\n\t}\n}", "func (pl *Plane) IntersectWithRay(ray *Ray) (count int, ans []Intersection, intersect bool) {\n\tdeter, _ := pl.Transform.Determinant()\n\tinv := pl.Transform.GetInverse(deter)\n\tray = ray.Transform(inv)\n\tif math.Abs(ray.Direction.Y) < 0.00001 {\n\t\treturn 0, ans, false\n\t}\n\tans = append(ans, *NewIntersection(-ray.Origin.Y/ray.Direction.Y, *ray, pl))\n\treturn 1, ans, true\n}", "func (r Ray) LineIntersect(s Ray) (point Vec) {\n\t/*\n\t\tequation is derived from system of equations with\n\t\ttwo unknowns where equations are r.Formula and s.Formula\n\t\tfrom which we can derive x of intersection point\n\n\t\tstarting with:\n\t\t\tr.V.Y*X - r.V.X*Y - r.V.Y*r.O.X + r.V.X*r.O.Y = 0\n\t\tand:\n\t\t\ts.V.Y*X - s.V.X*Y - s.V.Y*s.O.X + s.V.X*s.O.Y = 0\n\n\t\tget y from first one:\n\t\t\tr.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y = r.V.X*Y\n\t\t\t(r.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y)/r.V.X = Y\n\n\t\tthen we substitute and get x:\n\t\t\ts.V.Y*X - s.V.X * (r.V.Y*X - r.V.Y*r.O.X + r.V.X*r.O.Y) / r.V.X - s.V.Y*s.O.X + s.V.X*s.O.Y = 0 // * r.V.X\n\t\t\ts.V.Y*X*r.V.X - s.V.X*r.V.Y*X + s.V.X*r.V.Y*r.O.X - s.V.X*r.V.X*r.O.Y - s.V.Y*s.O.X*r.V.X + s.V.X*s.O.Y*r.V.X = 0 // - s.V.Y*X*r.V.X + s.V.X*r.V.Y*X\n\t\t\ts.V.X*r.V.Y*r.O.X - s.V.X*r.V.X*r.O.Y - s.V.Y*s.O.X*r.V.X + s.V.X*s.O.Y*r.V.X = s.V.X*r.V.Y*X - s.V.Y*X*r.V.X // simplify\n\t\t\ts.V.X * (r.V.Y*r.O.X + r.V.X * (s.O.Y - r.O.Y)) - s.V.Y*s.O.X*r.V.X = X * (s.V.X*r.V.Y - s.V.Y*r.V.X) // / (s.V.X*r.V.Y - s.V.Y*r.V.X)\n\t\t\t(s.V.X * (r.V.Y*r.O.X + r.V.X * (s.O.Y - r.O.Y)) - s.V.Y*s.O.X*r.V.X) / (s.V.X*r.V.Y - s.V.Y*r.V.X) = X\n\t*/\n\n\tpoint.X = (s.V.X*(r.V.Y*r.O.X+r.V.X*(s.O.Y-r.O.Y)) - s.V.Y*s.O.X*r.V.X) / (s.V.X*r.V.Y - s.V.Y*r.V.X)\n\n\tif r.V.X == 0 {\n\t\tpoint.Y = s.ProjectX(point.X)\n\t} else {\n\t\tpoint.Y = r.ProjectX(point.X)\n\t}\n\n\treturn\n}", "func IntersectPMultiple(primitives []Primitive, ray geometry.Ray) bool {\n\tfor _, pr := range primitives {\n\t\tif intersected := pr.IntersectP(ray); intersected {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (g *Group) LocalIntersect(r *algebra.Ray) ([]*Intersection, bool) {\n\txs := make([]*Intersection, 0, 0)\n\tvar hit bool = false\n\n\t// Get the AABB of the group\n\tmin, max := g.GetBounds()\n\n\tif min == nil {\n\t\treturn xs, false\n\t}\n\tif GetBoundsTransform(min, max, g.GetTransform()).Intersect(r.Transform(g.GetTransform())) == false {\n\t\treturn xs, false\n\t}\n\n\tfor _, s := range g.shapes {\n\t\tm := s.GetTransform()\n\t\tri := r.Transform(m.Inverse())\n\t\tshapeXs, shapeHit := s.LocalIntersect(ri)\n\t\thit = hit || shapeHit\n\t\tfor _, t := range shapeXs {\n\t\t\txs = append(xs, t)\n\t\t}\n\t}\n\treturn xs, hit\n}", "func rprismIntersects(q *rprismIntersectQ) (float64, bool) {\n\tt := (q.bcPlane - q.v[0]) / q.d[0]\n\tif t < 0 {\n\t\treturn 0, false\n\t}\n\tb := q.v[1] + t*q.d[1]\n\tc := q.v[2] + t*q.d[2]\n\tif b >= q.minB && b <= q.maxB && c >= q.minC && c <= q.maxC {\n\t\treturn t, true\n\t}\n\treturn 0, false\n}", "func (s Sphere) rayIntersect(orig, dir vec3) (hit bool, hitpos, normal vec3) {\n\tdir = dir.Norm()\n\toc := s.Center.Sub(orig)\n\tOQ := orig.Add(dir.ScalarProduct(dir.DotProduct(oc)))\n\tCQ := oc.Sub(OQ)\n\tif CQ.Magnitude() > s.Radius {\n\t\treturn false, vec3{}, vec3{}\n\t}\n\tlenPQ := math.Sqrt(s.Radius*s.Radius - CQ.Magnitude()*CQ.Magnitude())\n\tlenOP := OQ.Magnitude() - lenPQ\n\thitpos = orig.Add(dir.ScalarProduct(lenOP))\n\tnorm := hitpos.Sub(oc)\n\n\treturn true, hitpos, norm.Norm()\n}", "func (s Sphere) Intersect(r *Ray) (*Intersection, bool) {\n\n\tl := vector.Subtract(&r.origin, &s.origin)\n\ta := vector.Dot(&r.direction, &r.direction)\n\tb := 2 * vector.Dot(&r.direction, &l)\n\tc := vector.Dot(&l, &l) - s.radius*s.radius\n\n\tr0, r1, err := solveQuadratic(a, b, c)\n\n\tif err {\n\t\treturn nil, false\n\t}\n\n\tt0 := math.Min(r0, r1)\n\tt1 := math.Max(r0, r1)\n\n\tif t0 < 0 && t1 < 0 {\n\t\treturn nil, false\n\t}\n\n\ti := Intersection{thing: s, r: *r, dist: t0}\n\n\treturn &i, true\n}", "func (s *Sphere) Intersect(pt, ur Vector3) float64 {\n\t// if the vector is normalized, a is always 1\n\tb := ur.Scale(2).Dot(pt.Sub(s.point))\n\tc := pt.Sub(s.point).Dot(pt.Sub(s.point)) - s.radius*s.radius\n\tdisc := b*b - 4*c\n\tif disc < 0 {\n\t\treturn math.Inf(0)\n\t}\n\tt0 := (-b - math.Sqrt(disc)) / 2\n\tif t0 > 0 {\n\t\treturn t0 - EPSILON\n\t}\n\tt1 := (-b + math.Sqrt(disc)) / 2\n\treturn t1 - EPSILON\n}", "func (s *Sphere) Intersect(r *Ray, isect *Intersection) (hit bool) {\n\t// -(d . o) +- sqrt((d . o)^2 - (d . d)((o . o) - 1)) / (d . d)\n\tdo := r.Dir.Dot(r.Origin)\n\tdd := r.Dir.Dot(r.Dir)\n\too := r.Origin.Dot(r.Origin)\n\n\tdiscriminant := do*do - dd*(oo-1)\n\tif discriminant < 0 {\n\t\treturn false\n\t}\n\n\tdiscriminant = math.Sqrt(discriminant)\n\n\tt2 := (-do + discriminant) / dd\n\tif t2 <= Rayε {\n\t\treturn false\n\t}\n\n\tt1 := (-do - discriminant) / dd\n\tif t1 > Rayε {\n\t\tisect.T = t1\n\t\t// No need to normalize because it's a unit sphere at the origin\n\t\tisect.Normal = r.At(t1)\n\t\tisect.Material = s.Object.Material\n\t\t// TODO: possible optimization would be to check if we even need uv coordinates\n\t\tu := 0.5 + (math.Atan2(isect.Normal.Y(), isect.Normal.X()) / (2 * math.Pi))\n\t\tv := 0.5 - (math.Asin(isect.Normal.Z()) / math.Pi)\n\t\tisect.UVCoords = mgl64.Vec2{u, v}\n\t\treturn true\n\t}\n\n\tif t2 > Rayε {\n\t\tisect.T = t2\n\t\tisect.Normal = r.At(t2)\n\t\tisect.Material = s.Object.Material\n\t\tu := 0.5 + (math.Atan2(isect.Normal.Y(), isect.Normal.X()) / (2 * math.Pi))\n\t\tv := 0.5 - (math.Asin(isect.Normal.Z()) / math.Pi)\n\t\tisect.UVCoords = mgl64.Vec2{u, v}\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (cone Cone) Intersect(r ray.Ray) *space.Hit {\n\tif vec3.DotProduct(cone.disc.Normal, r.Direction) < 0 {\n\t\tdiscHit := cone.disc.Intersect(r)\n\n\t\tif discHit != nil {\n\t\t\treturn discHit\n\t\t}\n\t}\n\n\tconeHit := cone.walls.Intersect(r)\n\n\treturn coneHit\n}", "func (tri *Triangle) IntersectsPoint(v quadedge.Vertex) bool {\n\te := tri.Qe\n\n\tfor i := 0; i < 3; i++ {\n\t\tlc := v.Classify(e.Orig(), e.Dest())\n\t\tswitch lc {\n\t\t// return true if v is on the edge\n\t\tcase quadedge.ORIGIN:\n\t\t\treturn true\n\t\tcase quadedge.DESTINATION:\n\t\t\treturn true\n\t\tcase quadedge.BETWEEN:\n\t\t\treturn true\n\t\t// return false if v is well outside the triangle\n\t\tcase quadedge.LEFT:\n\t\t\treturn false\n\t\tcase quadedge.BEHIND:\n\t\t\treturn false\n\t\tcase quadedge.BEYOND:\n\t\t\treturn false\n\t\t}\n\t\t// go to the next edge of the triangle.\n\t\te = e.RNext()\n\t}\n\n\t// if v is to the right of all edges, it is inside the triangle.\n\treturn true\n}", "func (pn Plane) DoesRayIntersect(r rays.Ray) (doesIntersect bool, intersectPoint0 rays.Point, intersectPoint1 rays.Point) {\n\tvar p0 rays.Point\n\tsurfaceNormal := pn.NormalAtPoint(intersectPoint0)\n\tdenom := rays.DotProduct(surfaceNormal.Direction, r.Direction)\n\n\tif denom < 1e-6 {\n\t\treturn false, p0, p0\n\t}\n\n\ttop := rays.DotProduct(rays.Subtract(surfaceNormal.Origin, r.Origin), surfaceNormal.Direction)\n\tt := top / denom\n\n\tif t < 0 {\n\t\treturn false, p0, p0\n\t}\n\tp0 = rays.Add(r.Origin, rays.Multiply(r.Direction, t))\n\treturn true, p0, p0\n}", "func (p *Plan) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(p.position)\n\tdefer eye.Add(p.position)\n\n\tif v.Z == 0 {\n\t\treturn 0\n\t}\n\treturn -float64(eye.Z) / v.Z\n}", "func (stri *SmoothTriangle) IntersectWithRay(ray *Ray) (count int, ans []Intersection, intersect bool) {\n\tdeter, _ := stri.Transform.Determinant()\n\tiT := stri.Transform.GetInverse(deter)\n\tnewR := ray.Transform(iT)\n\tdirCrossE2, _ := newR.Direction.CrossProduct(&stri.Edge2)\n\tdet, _ := stri.Edge1.DotProduct(&dirCrossE2)\n\tif math.Abs(det) < 0.00001 {\n\t\treturn 0, ans, intersect\n\t}\n\tf := float64(1) / det\n\tp1ToOrigin, _ := ray.Origin.Subtract(&stri.Point1)\n\tdot, _ := p1ToOrigin.DotProduct(&dirCrossE2)\n\tu := f * dot\n\tif u < 0 || u > 1 {\n\t\treturn 0, ans, intersect\n\t}\n\toriCrossE1, _ := p1ToOrigin.CrossProduct(&stri.Edge1)\n\tdot2, _ := ray.Direction.DotProduct(&oriCrossE1)\n\tv := f * dot2\n\tif v < 0 || (u+v) > 1 {\n\t\treturn 0, ans, intersect\n\t}\n\tdot3, _ := stri.Edge2.DotProduct(&oriCrossE1)\n\tt := f * dot3\n\tinter := stri.IntersectionWithUandV(*newR, t, u, v)\n\tans = append(ans, *inter)\n\treturn 1, ans, true\n}", "func (self *Rectangle) IntersectsI(args ...interface{}) bool{\n return self.Object.Call(\"intersects\", args).Bool()\n}", "func TestIntersect(t *testing.T) {\n\ttype args struct {\n\t\ta interface{}\n\t\tb interface{}\n\t}\n\ttests := []struct {\n\t\tname string\n\t\targs args\n\t\twant interface{}\n\t}{\n\t\t{\n\t\t\tname: \"int64-slice-交集\",\n\t\t\targs: args{\n\t\t\t\ta: []int64{1, 2, 3, 4, 4, 5, 6},\n\t\t\t\tb: []int64{1, 3, 5, 7, 9, 11},\n\t\t\t},\n\t\t\twant: []int64{1, 3, 5},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar ret []int64\n\t\t\tif got := Intersect(tt.args.a, tt.args.b, &ret); !reflect.DeepEqual(ret, tt.want) {\n\t\t\t\tt.Errorf(\"Intersection() = %v, want %v\", got, tt.want)\n\t\t\t}\n\t\t})\n\t}\n}", "func (p *Polygon) ContainsPoint(testPt *Vec) bool {\n\t_, max := p.BoundingBox()\n\trb := &Vec{testPt.X, testPt.Y}\n\trv := (&Vec{max.X+1, testPt.Y}).Sub(rb)\n\t\n\t//fmt.Println(\"ray\", p.IntersectLine(rb, rv)) \n\t\n\tintersections := make(map[Vec]bool)\n\tfor i, pt := range p.Points {\n\t\tab := pt\n\t\tav := p.Points[(i+1)%p.Len()].Sub(ab)\n\t\t//fmt.Println(\"Do intersect ?\", ab, av, rb, rv, \":\", IntersectLines(ab, av, rb, rv))\n\t\tif ip := IntersectLines(ab, av, rb, rv); ip != nil {\n\t\t\t//fmt.Println(\" Is point\", testPt, \"on line\", ab,av,\":\", IntersectLinePoint(ab, av, testPt))\n\t\t\tif IntersectLinePoint(ab, av, testPt) == nil {\t\t\t\n\t\t\t\tintersections[*ip] = true\n\t\t\t} else {\n\t\t\t\t// if the point is on the edges only once,\n\t\t\t\t// return false immediately\n\t\t\t\treturn false\n\t\t\t}\n\t\t\t\n\t\t}\n\t}\n\t\n\t//fmt.Println(\"We have \", intersections)\n\treturn len(intersections)%2 == 1\n}", "func (p *PGeometry) ContainsP(other *Geometry) (bool, error) {\n\treturn p.predicate(\"contains\", cGEOSPreparedContainsProperly, other)\n}", "func (c Contour) Contains(p Point) bool {\n\t// Cast ray from p.x towards the right\n\tintersections := 0\n\tfor i := range c {\n\t\tcurr := c[i]\n\t\tii := i + 1\n\t\tif ii == len(c) {\n\t\t\tii = 0\n\t\t}\n\t\tnext := c[ii]\n\n\t\tif (p.Y >= next.Y || p.Y <= curr.Y) &&\n\t\t\t(p.Y >= curr.Y || p.Y <= next.Y) {\n\t\t\tcontinue\n\t\t}\n\t\t// Edge is from curr to next.\n\n\t\tif p.X >= math.Max(curr.X, next.X) ||\n\t\t\tnext.Y == curr.Y {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Find where the line intersects...\n\t\txint := (p.Y-curr.Y)*(next.X-curr.X)/(next.Y-curr.Y) + curr.X\n\t\tif curr.X != next.X && p.X > xint {\n\t\t\tcontinue\n\t\t}\n\n\t\tintersections++\n\t}\n\n\treturn intersections%2 != 0\n}", "func (self *Rectangle) IntersectsRawI(args ...interface{}) bool{\n return self.Object.Call(\"intersectsRaw\", args).Bool()\n}", "func (e Entities) Intersect(rect pixel.Rect) bool {\n\t// check if any entities returned intersect the given point\n\tfor i := range e {\n\t\t// check for intersect\n\t\tif e[i].Intersects(rect) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (s Sphere) RayIntersects(origin vector.Vector3, direction vector.Vector3, t0 float64) (float64, bool) {\n\t// solve for tc\n\t// find vector from ray origin to sphere center\n\tL := s.Center.Subtract(origin)\n\ttc := L.DotProduct(direction)\n\n\tif tc < 0.0 {\n\t\treturn t0, false\n\t}\n\td2 := L.DotProduct(L) - (tc * tc)\n\tr2 := s.Radius * s.Radius\n\tif d2 > r2 {\n\t\treturn t0, false\n\t}\n\n\t// solve t1c\n\tt1c := math.Sqrt(r2 - d2)\n\n\t// solve intersection points\n\tt0 = tc - t1c\n\tt1 := tc + t1c\n\tif t0 < 0.0 {\n\t\tt0 = t1\n\t}\n\tif t0 < 0.0 {\n\t\treturn t0, false\n\t}\n\treturn t0, true\n}", "func (b *BasicShape) Intersect(geometry.Ray, *DifferentialGeometry) bool {\n\tpanic(\"Intersect is not implemented for basic shape\")\n}", "func Intersect(r1, r2 *Rect) bool {\n\t// There are four cases of overlap:\n\t//\n\t// 1. a1------------b1\n\t// a2------------b2\n\t// p--------q\n\t//\n\t// 2. a1------------b1\n\t// a2------------b2\n\t// p--------q\n\t//\n\t// 3. a1-----------------b1\n\t// a2-------b2\n\t// p--------q\n\t//\n\t// 4. a1-------b1\n\t// a2-----------------b2\n\t// p--------q\n\t//\n\t// Thus there are only two cases of non-overlap:\n\t//\n\t// 1. a1------b1\n\t// a2------b2\n\t//\n\t// 2. a1------b1\n\t// a2------b2\n\t//\n\t// Enforced by constructor: a1 <= b1 and a2 <= b2. So we can just\n\t// check the endpoints.\n\n\tfor i := range r1.p {\n\t\ta1, b1, a2, b2 := r1.p[i], r1.q[i], r2.p[i], r2.q[i]\n\t\tif b2 <= a1 || b1 <= a2 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func (self *Rectangle) IntersectionI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"intersection\", args)}\n}", "func IntersectPlane( plane_p, plane_n Vec3D, lineStart , lineEnd Vec3D ) Vec3D {\n plane_n = plane_n.Normalize()\n plane_d := -plane_n.Dot( plane_p)\n ad := lineStart.Dot(plane_n)\n bd := lineEnd.Dot(plane_n)\n t := (-plane_d - ad) / (bd - ad)\n lineStartToEnd := lineEnd.Sub(lineStart)\n lineToIntersect := lineStartToEnd.Mul(t)\n return lineStart.Add(lineToIntersect)\n}", "func (r *Ray) Intersect(o Ray) (Vector, bool) {\n\tconst width = 0.03\n\n\tclampInRange := func(p Vector) (Vector, bool) {\n\t\tdist := r.Origin.Distance(p)\n\t\tif dist < r.Mint || dist > r.Maxt {\n\t\t\treturn r.Origin, false\n\t\t}\n\n\t\treturn p, true\n\t}\n\n\tif r.Origin == o.Origin {\n\t\treturn r.Origin, true\n\t}\n\n\td3 := r.Direction.Cross(o.Direction)\n\n\tif !d3.Equals(NewVector(0, 0, 0)) {\n\t\tmatrix := [12]float64{\n\t\t\tr.Direction.X,\n\t\t\t-o.Direction.X,\n\t\t\td3.X,\n\t\t\to.Origin.X - r.Origin.X,\n\n\t\t\tr.Direction.Y,\n\t\t\t-o.Direction.Y,\n\t\t\td3.Y,\n\t\t\to.Origin.Y - r.Origin.Y,\n\n\t\t\tr.Direction.Z,\n\t\t\t-o.Direction.Z,\n\t\t\td3.Z,\n\t\t\to.Origin.Z - r.Origin.Z,\n\t\t}\n\n\t\tresult := solve(matrix, 3, 4)\n\n\t\ta := result[3]\n\t\tb := result[7]\n\t\tc := result[11]\n\n\t\tif a >= 0 && b >= 0 {\n\t\t\tdist := d3.MultiplyScalar(c)\n\t\t\tif dist.Length() <= width {\n\t\t\t\treturn clampInRange(r.At(a))\n\t\t\t}\n\t\t\treturn r.Origin, false\n\t\t}\n\t}\n\n\tdP := o.Origin.Multiply(r.Origin)\n\n\ta2 := r.Direction.Dot(dP)\n\tb2 := o.Direction.Dot(dP.Neg())\n\n\tif a2 < 0 && b2 < 0 {\n\t\tdist := r.Origin.Distance(dP)\n\t\tif dP.Length() <= width {\n\t\t\treturn clampInRange(r.At(dist))\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tp3a := r.Origin.Plus(r.Direction.MultiplyScalar(a2))\n\td3a := o.Origin.Minus(p3a)\n\n\tp3b := r.Origin\n\td3b := o.Origin.Plus(o.Direction.MultiplyScalar(b2)).Minus(p3b)\n\n\tif b2 < 0 {\n\t\tif d3a.Length() <= width {\n\t\t\treturn clampInRange(p3a)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif a2 < 0 {\n\t\tif d3b.Length() <= width {\n\t\t\treturn clampInRange(p3b)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif d3a.Length() <= d3b.Length() {\n\t\tif d3a.Length() <= width {\n\t\t\treturn clampInRange(p3a)\n\t\t}\n\t\treturn r.Origin, false\n\t}\n\n\tif d3b.Length() <= width {\n\t\treturn clampInRange(p3b)\n\t}\n\n\treturn r.Origin, false\n}", "func (oCone OpenCone) Intersect(r ray.Ray) *space.Hit {\n\td := r.Direction\n\t// x0 := vec3.Subtract(vec3.Subtract(r.Origin, this.Position), vec3.Vec3{0,this.Height,0})\n\tx0 := vec3.Subtract(vec3.Subtract(r.Origin, oCone.Position), vec3.Multiply(oCone.Height, oCone.Normal))\n\n\ta := d.X*d.X + d.Z*d.Z - (d.Y*d.Y)*(oCone.Radius*oCone.Radius)\n\tb := 2*x0.X*d.X + 2*x0.Z*d.Z - (2*x0.Y*d.Y)*(oCone.Radius*oCone.Radius)\n\tc := x0.X*x0.X + x0.Z*x0.Z - (x0.Y*x0.Y)*(oCone.Radius*oCone.Radius)\n\n\tsqrtOf := b*b - 4*a*c\n\n\tif sqrtOf < 0 {\n\t\treturn nil\n\t}\n\tvar t float64\n\tif sqrtOf == 0 {\n\t\tt = -b / (2 * a)\n\t\tif !r.InRange(t) {\n\t\t\treturn nil\n\t\t}\n\t} else if sqrtOf > 0 {\n\t\tt = (-b - math.Sqrt(sqrtOf)) / (2 * a)\n\t\tif !r.InRange(t) {\n\t\t\tt = (-b + math.Sqrt(sqrtOf)) / (2 * a)\n\t\t\tif !r.InRange(t) {\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\n\tpoint := r.PointAt(t)\n\n\tif point.Y < oCone.Position.Y || point.Y > oCone.Position.Y+oCone.Height {\n\t\treturn nil\n\t}\n\n\ttipToPoint := vec3.Subtract(point, vec3.Add(oCone.Position, vec3.Multiply(oCone.Height, oCone.Normal)))\n\tnormal := vec3.Normalize(vec3.CrossProduct(vec3.CrossProduct(tipToPoint, oCone.Normal), tipToPoint))\n\n\t// it is correct. Don't change it again!\n\tif vec3.DotProduct(r.Direction, normal) > 0 {\n\t\tnormal = vec3.Multiply(-1, normal)\n\t}\n\n\treturn &space.Hit{\n\t\tT: t,\n\t\tPosition: point,\n\t\tNormal: normal,\n\t\tMaterial: oCone.Material,\n\t\t// Material: Material_Normal{},\n\t}\n}", "func (orth *Orthotope) Intersects(o *Orthotope) int32 {\n\tinT := int32(0)\n\toutT := int32(math.MaxInt32)\n\tfor index, p0 := range o.Point {\n\t\tp1 := o.Delta[index] + p0\n\n\t\tif orth.Delta[index] == 0 {\n\t\t\tif orth.Point[index] < p0 || p1 < orth.Point[index] {\n\t\t\t\treturn -1\n\t\t\t}\n\t\t} else {\n\t\t\tif orth.Delta[index] < 0 {\n\t\t\t\t// Swap p0 and p1 for negative directions.\n\t\t\t\tp0, p1 = p1, p0\n\t\t\t}\n\t\t\tp0T := ((p0 - orth.Point[index]) << ACCURACY) / orth.Delta[index]\n\t\t\tinT = disc.Max(inT, p0T)\n\n\t\t\tp1T := ((p1 - orth.Point[index]) << ACCURACY) / orth.Delta[index]\n\t\t\toutT = disc.Min(outT, p1T)\n\t\t}\n\t}\n\n\tif inT < outT && inT >= 0 {\n\t\treturn inT\n\t}\n\treturn -1\n}", "func IntersectMultiple(primitives []Primitive, ray geometry.Ray, in *Intersection) bool {\n\tvar hasHit bool\n\tfor _, pr := range primitives {\n\n\t\tif ok := pr.Intersect(ray, in); !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\thasHit = true\n\t\tray.Maxt = in.DfGeometry.Distance\n\t}\n\n\treturn hasHit\n}", "func (s *Scene) FindIntersection(r raytracing.Ray) (bool, float64, int) {\n\tcurrentObject := -1\n\tt := 20000.0\n\n\tvar intersected bool\n\tfor i, object := range s.Objects {\n\t\tif intersected, t = object.Intersect(r, t); intersected {\n\t\t\tcurrentObject = i\n\t\t}\n\t}\n\n\tintersected = (currentObject != -1)\n\treturn intersected, t, currentObject\n}", "func (p *PGeometry) Intersects(other *Geometry) (bool, error) {\n\treturn p.predicate(\"intersects\", cGEOSPreparedIntersects, other)\n}", "func (p Polygon) Intersection(p2 Polygonal) Polygon {\n\treturn p.op(p2, polyclip.INTERSECTION)\n}", "func _v2dIntersect(p0 *Vec2d, p1 *Vec2d, p2 *Vec2d, p3 *Vec2d, inter *Vec2d) {\n\tvar s1, s2 Vec2d\n\n\ts1.x = p1.x - p0.x\n\ts1.y = p1.y - p0.y\n\ts2.x = p3.x - p2.x\n\ts2.y = p3.y - p2.y\n\n\tt := (s2.x*(p0.y-p2.y) - s2.y*(p0.x-p2.x)) / (-s2.x*s1.y + s1.x*s2.y)\n\n\tinter.x = p0.x + (t * s1.x)\n\tinter.y = p0.y + (t * s1.y)\n}", "func (q QueryData) intersects(g types.Geo) bool {\n\tx.AssertTruef(q.pt != nil || q.loop != nil, \"At least a point or loop should be defined.\")\n\tswitch v := g.T.(type) {\n\tcase *geom.Point:\n\t\tp := pointFromPoint(v)\n\t\tif q.pt != nil {\n\t\t\t// Points only intersect if they are the same. (We allow for small rounding errors)\n\t\t\treturn q.pt.ApproxEqual(p)\n\t\t}\n\t\t// else loop is not nil\n\t\treturn q.loop.ContainsPoint(p)\n\n\tcase *geom.Polygon:\n\t\tl, err := loopFromPolygon(v)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif q.pt != nil {\n\t\t\treturn l.ContainsPoint(*q.pt)\n\t\t}\n\t\t// else loop is not nil\n\t\treturn Intersects(l, q.loop)\n\tdefault:\n\t\t// A type that we don't know how to handle.\n\t\treturn false\n\t}\n}", "func intersects(\n\tm_minx, m_miny, m_maxx, m_maxy float64,\n\to_minx, o_miny, o_maxx, o_maxy float64,\n) bool {\n\t//not disjoint\n\treturn !(o_minx > m_maxx || o_maxx < m_minx || o_miny > m_maxy || o_maxy < m_miny)\n}", "func (p *Ball) Intersection(line *objects.Ray) (position, color,\n\tnormal *objects.Vector, diffuse,\n\tspecularIntensity, specularPower, reflectivity float64) {\n\n\tposition = p.sphere.Intersection(line)\n\tif position == nil {\n\t\treturn\n\t}\n\tcolor = p.Color()\n\tnormal = position.SubtractVector(p.Sphere().Position())\n\tdiffuse = p.Diffuse()\n\tspecularIntensity = p.SpecularIntensity()\n\tspecularPower = p.SpecularPower()\n\treflectivity = p.Reflectivity()\n\treturn\n}", "func (self *Rectangle) IntersectsRaw(left int, right int, top int, bottom int, tolerance int) bool{\n return self.Object.Call(\"intersectsRaw\", left, right, top, bottom, tolerance).Bool()\n}", "func (s *Sphere) Intersect(v objects.Vector, eye objects.Point) float64 {\n\teye.Sub(s.position)\n\tdefer eye.Add(s.position)\n\n\tvar (\n\t\ta = v.X*v.X + v.Y*v.Y + v.Z*v.Z\n\t\tb = 2*float64(eye.X)*v.X + float64(eye.Y)*v.Y + float64(eye.Z)*v.Z\n\t\tc = float64(eye.X*eye.X + eye.Y*eye.Y + eye.Z*eye.Z - s.R*s.R)\n\t)\n\treturn utils.SecondDegree(a, b, c)\n}", "func intersects(p1, q1, p2, q2 *node) bool {\n\tif (equals(p1, q1) && equals(p2, q2)) ||\n\t\t(equals(p1, q2) && equals(p2, q1)) {\n\t\treturn true\n\t}\n\treturn (area(p1, q1, p2) > 0.0) != (area(p1, q1, q2) > 0.0) &&\n\t\t(area(p2, q2, p1) > 0.0) != (area(p2, q2, q1) > 0.0)\n}", "func (tet *Tetrahedron) ContainsPoint(point [3]float64)(bool) {\n\n\tfor idx, v := range tet.Vertices {\n\t\t//contains the three points of the face that does not include v\n\t\tvar opposite []*Vertex3d\n\t\tfor idx2, v2 := range tet.Vertices {\n\t\t\tif idx != idx2 {\n\t\t\t\topposite = append(opposite, v2)\n\t\t\t}\n\t\t}\n\n\t\t//get 3d coordinates of opposite face points\n\t\tfacePt0, facePt1, facePt2 := opposite[0].Vec, opposite[1].Vec, opposite[2].Vec\n\n\t\t//get two vectors contained in the opposite face\n\t\tvec0 := []float64{facePt1[0] - facePt0[0], facePt1[1] - facePt0[1], facePt1[2] - facePt0[2]}\n\n\t\tvec1 := []float64{facePt2[0] - facePt0[0], facePt2[1] - facePt0[1], facePt2[2] - facePt0[2]}\n\n\t\t\n\t\t//get normal of opposite face\n\t\tnormal := []float64{vec0[1] * vec1[2] - vec0[2] * vec1[1], vec0[2] * vec1[0] - vec0[0] * vec1[2],\n\t\t\tvec0[0] * vec1[1] - vec0[1] * vec1[0]}\n\n\n\t\tv4Diff := []float64{v.Vec[0] - facePt0[0], v.Vec[1] - facePt0[1], v.Vec[2] - facePt0[2]}\n\t\tnewPointDiff := []float64{point[0] - facePt0[0], point[1] - facePt0[1], point[2] - facePt0[2]}\n\n\t\tv4Dot := normal[0] * v4Diff[0] + normal[1] * v4Diff[1] + normal[2] * v4Diff[2]\n\t\tnewPointDot := normal[0] * newPointDiff[0] + normal[1] * newPointDiff[1] + normal[2] * newPointDiff[2]\n\n\t\t//log.Println(\"asdf\")\n\t\t//log.Println(v4Dot)\n\t\t//log.Println(newPointDot)\n\n\t\tif v4Dot * newPointDot < 0.0 {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func PointInPolygon(p Point, poly Polygon) bool {\n\tnvert := len(poly.vertices)\n\todd := false\n\tfor i, j := 0, nvert-1; i < nvert; i++ {\n\t\tv1, v2 := poly.vertices[i], poly.vertices[j]\n\t\tif (v1.y <= p.y && p.y < v2.y) || (v2.y <= p.y && p.y < v1.y) {\n\t\t\tif v1.x >= p.x || v2.x >= p.x {\n\t\t\t\t// Compute intersection of ray with edge (v1,v2) at y, where\n\t\t\t\t// v1=(x1,y1) and v2=(x2,y2). Solve for x:\n\t\t\t\t//\n\t\t\t\t//\t\tslope = (y2-y1) / (x2-x1) = (y-y1) / (x-x1)\n\t\t\t\t//\t\t(y2-y1) / (x2-x1) = (y-y1) / (x-x1)\n\t\t\t\t//\t\t(y2-y1) / (x2-x1) * (x-x1) = (y-y1)\n\t\t\t\t//\t\tx = (y-y1) * (x2-x1) / (y2-y1) + x1\n\t\t\t\t//\n\t\t\t\t// Point must be strictly to the right of the edge.\n\t\t\t\tif p.x < (p.y-v1.y)*(v2.x-v1.x)/(v2.y-v1.y)+v1.x {\n\t\t\t\t\todd = !odd\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tj = i // j follows i\n\t}\n\treturn odd\n}", "func (mr *MockListMockRecorder) Intersect(other interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersect\", reflect.TypeOf((*MockList)(nil).Intersect), other)\n}", "func TestIntersection(t *testing.T) {\n\ttests := []struct {\n\t\tnote string\n\t\trules []string\n\t\texpected interface{}\n\t}{\n\t\t{\"intersection_0_sets\", []string{`p = x { intersection(set(), x) }`}, \"[]\"},\n\t\t{\"intersection_2_sets\", []string{`p = x { intersection({set(), {1, 2}}, x) }`}, \"[]\"},\n\t\t{\"intersection_2_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2}; intersection({s1, s2}, x) }`}, \"[2]\"},\n\t\t{\"intersection_3_sets\", []string{`p = x { s1 = {1, 2, 3}; s2 = {2, 3, 4}; s3 = {4, 5, 6}; intersection({s1, s2, s3}, x) }`}, \"[]\"},\n\t\t{\"intersection_4_sets\", []string{`p = x { s1 = {\"a\", \"b\", \"c\", \"d\"}; s2 = {\"b\", \"c\", \"d\"}; s3 = {\"c\", \"d\"}; s4 = {\"d\"}; intersection({s1, s2, s3, s4}, x) }`}, \"[\\\"d\\\"]\"},\n\t}\n\n\tdata := loadSmallTestData()\n\n\tfor _, tc := range tests {\n\t\trunTopDownTestCase(t, data, tc.note, tc.rules, tc.expected)\n\t}\n}", "func (mr *MockEnvoyFilterSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockEnvoyFilterSet)(nil).Intersection), set)\n}", "func (s1 Segment) Intersect(e2 Edge) (Vector, bool) {\n\treturn Intersect(s1, e2)\n}", "func (self *Rectangle) Intersects(b *Rectangle) bool{\n return self.Object.Call(\"intersects\", b).Bool()\n}", "func Intersection(m int, n int, v1 []int, v2 []int) (r float32, err error) {\n\tif err := (m != len(v1) || n != len(v2)); err == true {\n\t\terr := &negativeIntError{err}\n\t\treturn -1, err\n\t}\n\n\tsum := 0\n\tcount := 0\n\n\tfor i := 0; i < m; i++ {\n\t\tfor j := 0; j < n; j++ {\n\t\t\tif err := (v1[i] < 0 || v2[j] < 0); err == true {\n\t\t\t\terr := &negativeIntError{err}\n\t\t\t\treturn -1, err\n\t\t\t}\n\t\t\tif v1[i] == v2[j] {\n\t\t\t\tsum += v1[i]\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\tif count < 1 {\n\t\treturn 0, nil\n\t}\n\treturn float32(sum / count), nil\n}", "func (mr *MockAccessControlPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockAccessControlPolicySet)(nil).Intersection), set)\n}", "func (mr *MockVirtualMeshSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockVirtualMeshSet)(nil).Intersection), set)\n}", "func (intGroup intersectionGroup) Intersect(r ray.Ray) *space.Hit {\n\tvar furthestHit *space.Hit\n\tvar h *space.Hit\n\n\tfor _, shape := range intGroup.shapes {\n\t\th = shape.Intersect(r)\n\t\tif h == nil {\n\t\t\treturn nil\n\t\t}\n\t\tif furthestHit == nil || h.T > furthestHit.T {\n\t\t\tfurthestHit = h\n\t\t}\n\t}\n\n\treturn furthestHit\n}", "func (s *Subject) Contains(pt maths.Pt) bool {\n\n\tline := maths.Line{pt, maths.Pt{pt.X - 1, pt.Y}}\n\tcount := 0\n\tvar lpt maths.Pt\n\tvar haveLpt bool\n\tfor p := s.FirstPair(); p != nil; p = p.Next() {\n\t\tpline := p.AsLine()\n\t\tif ipt, ok := maths.Intersect(line, pline); ok {\n\t\t\tipt = ipt.Truncate()\n\t\t\tif haveLpt {\n\t\t\t\tif lpt.IsEqual(ipt) {\n\t\t\t\t\t// skip repeat intersections points. These may be an intersection point that lies on the end pt.\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\t//log.Println(\"Got Intersect \", count, ipt, pline.InBetween(ipt) && ipt.X < pt.X, pt.X, pline)\n\n\t\t\t// We only care about intersect points that are left of the point being tested.\n\t\t\tif pline.InBetween(ipt) && ipt.X < pt.X {\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tlpt = ipt\n\t\t\thaveLpt = true\n\n\t\t}\n\t}\n\n\tlog.Println(\"Contains Count:\", count)\n\n\t// If it's odd then it's inside of the polygon, otherwise it's outside of the polygon.\n\treturn count%2 != 0\n}", "func (r Rect) IntersectionPoints(l Line) []Vec {\n\t// Use map keys to ensure unique points\n\tpointMap := make(map[Vec]struct{})\n\n\tfor _, edge := range r.Edges() {\n\t\tif intersect, ok := l.Intersect(edge); ok {\n\t\t\tpointMap[intersect] = struct{}{}\n\t\t}\n\t}\n\n\tpoints := make([]Vec, 0, len(pointMap))\n\tfor point := range pointMap {\n\t\tpoints = append(points, point)\n\t}\n\n\t// Order the points\n\tif len(points) == 2 {\n\t\tif points[1].To(l.A).Len() < points[0].To(l.A).Len() {\n\t\t\treturn []Vec{points[1], points[0]}\n\t\t}\n\t}\n\n\treturn points\n}", "func (mr *MockVirtualServiceSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockVirtualServiceSet)(nil).Intersection), set)\n}", "func (mp MultiPolygon) Intersection(p2 Polygonal) Polygon {\n\treturn mp.op(p2, polyclip.INTERSECTION)\n}", "func (poly Polygon) Intersect(poly2 Polygon) bool {\r\n\tvertices := poly.GetWorldVertices()\r\n\tvertices2 := poly2.GetWorldVertices()\r\n\tfor i := 1; i < len(vertices); i++ {\r\n\t\tedgeVec := linalg.Vector2f64{X: vertices[i].X - vertices[i-1].X, Y: vertices[i].Y - vertices[i-1].Y}\r\n\t\taxis := edgeVec.NormalVec()\r\n\t\tseg0 := poly2.ProjectOn(axis)\r\n\t\tseg1 := poly.ProjectOn(axis)\r\n\t\tif !overlap(seg0, seg1) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\tfor i := 1; i < len(vertices2); i++ {\r\n\t\tedgeVec := linalg.Vector2f64{X: vertices2[i].X - vertices2[i-1].X, Y: vertices2[i].Y - vertices2[i-1].Y}\r\n\t\taxis := edgeVec.NormalVec()\r\n\t\tseg0 := poly2.ProjectOn(axis)\r\n\t\tseg1 := poly.ProjectOn(axis)\r\n\t\tif !overlap(seg0, seg1) {\r\n\t\t\treturn false\r\n\t\t}\r\n\t}\r\n\treturn true\r\n}", "func (n *numbers) Intersect() []int {\n\tm := map[int]int{}\n\tfor _, el := range n.nums1 {\n\t\tm[el]++\n\t}\n\tout := make([]int, 0)\n\tfor _, el := range n.nums2 {\n\t\tif m[el] > 0 {\n\t\t\tm[el]--\n\t\t\tout = append(out, el)\n\t\t}\n\t}\n\treturn out\n}", "func (p *Point) In(rect image.Rectangle) bool {\n\treturn image.Point(*p).In(rect)\n}", "func IsPointInside(polygon []shared.Point2d, p shared.Point2d) bool {\n\t// If less than 3, its just a line not a polygon\n\tif len(polygon) < 3 {\n\t\treturn false\n\t}\n\n\t// Create a point far away from p (out of the canvas)\n\tinf := shared.Point2d{X: INF, Y: p.Y}\n\n\t// Count intersections of line p-inf with the edges of the polygon\n\tvar count int\n\tfor i := 0; i < len(polygon)-1; i++ {\n\t\t// Check if the line from p-inf intersects with polygon[i]-polygon[i+1]\n\t\tif IsLineIntersect(polygon[i], polygon[i+1], p, inf) {\n\t\t\t// If p is colinear with i-i+1, and p lies on i-i+1, return true\n\t\t\tif Orientation(polygon[i], p, polygon[i+1]) == 0 {\n\t\t\t\treturn OnLine(polygon[i], p, polygon[i+1])\n\t\t\t}\n\t\t\t// To avoid double counting on colinear Orientation\n\t\t\t// Handles cases where p intersects with the meeting point of the two lines in polygon\n\t\t\tif Orientation(polygon[i+1], p, inf) != 0 {\n\t\t\t\tcount++\n\t\t\t}\n\t\t}\n\t}\n\treturn (count%2 == 1)\n}", "func (self *Rectangle) Intersection(b *Rectangle, out *Rectangle) *Rectangle{\n return &Rectangle{self.Object.Call(\"intersection\", b, out)}\n}", "func (p *intersect) Intersect(nums1 []int, nums2 []int) []int {\n\tsort.Ints(nums1)\n\tsort.Ints(nums2)\n\ti := 0\n\tj := 0\n\tinter := make([]int, 0)\n\tfor i < len(nums1) && j < len(nums2) {\n\t\tif nums1[i] == nums2[j] {\n\t\t\tinter = append(inter, nums1[i])\n\t\t\ti++\n\t\t\tj++\n\t\t} else if nums1[i] > nums2[j] {\n\t\t\tj++\n\t\t} else {\n\t\t\ti++\n\t\t}\n\t}\n\treturn inter\n}", "func TestIntersectionHorizontal(t *testing.T) {\n\tsegment1, err := newLineSegment(point{x: 0, y: 0}, point{x: 10, y: 0})\n\tif err != nil {\n\t\tt.Error(\"error\")\n\t}\n\n\tsegment2, err := newLineSegment(point{x: 5, y: -10}, point{x: 5, y: 10})\n\tif err != nil {\n\t\tt.Error(\"error\")\n\t}\n\n\tintersection, points := doesIntersect(segment1, segment2)\n\n\tif !intersection {\n\t\tt.Error(\"segments should intersect\")\n\t}\n\n\tpoint := points[0]\n\n\tif point.x != 5 && point.y != 0 {\n\t\tt.Error(\"intersection point should be {5, 0}\")\n\t}\n}", "func (mr *MockMutableListMockRecorder) Intersect(other interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersect\", reflect.TypeOf((*MockMutableList)(nil).Intersect), other)\n}", "func HasIntersection(op shared.Operation, shapes map[string]shared.Operation) (bool, string) {\n\treturn collision.CollideWithOtherShapes(op, shapes)\n}", "func (v *Voxel) Add(p primitive.Primitive) {\n\tif p.CanIntersect() {\n\t\tv.primitives = append(v.primitives, p)\n\t} else {\n\t\tgridAccel := NewGrid(p.Refine())\n\t\tv.primitives = append(v.primitives, gridAccel)\n\t}\n}", "func (p *Plane3D) isInside(otherPoint *Vector3D.Vector3D) bool {\n\n\treturn p.isNormalFlipped == !p.isInsideLocal(p.transform.toLocal(otherPoint))\n}", "func intersect(b, c *Block, postnum []int, idom []*Block) *Block {\n\t// TODO: This loop is O(n^2). It used to be used in nilcheck,\n\t// see BenchmarkNilCheckDeep*.\n\tfor b != c {\n\t\tif postnum[b.ID] < postnum[c.ID] {\n\t\t\tb = idom[b.ID]\n\t\t} else {\n\t\t\tc = idom[c.ID]\n\t\t}\n\t}\n\treturn b\n}", "func (s Sphere) Hit(ray geo.Ray) (bool, geo.Point3D) {\n\tp := ray.Endpoint\n\tv := ray.Direction\n\tradius := s.radius\n\tcenter := s.center\n\tb := 2 * ((p.X-center.X)*v.X + (p.Y-center.Y)*v.Y + (p.Z-center.Z)*v.Z)\n\tc := (p.X-center.X)*(p.X-center.X) + (p.Y-center.Y)*(p.Y-center.Y) + (p.Z-center.Z)*(p.Z-center.Z) - radius*radius\n\tdelta := b*b - 4*c\n\tvar isHit bool\n\tvar hitPoint geo.Point3D\n\tif delta >= 0.0 {\n\t\tisHit = true\n\t\tresultA := -(b + math.Sqrt(delta)) / 2.0\n\t\tresultB := -(b - math.Sqrt(delta)) / 2.0\n\t\tvar result float64\n\t\tif resultA*resultA < resultB*resultB {\n\t\t\tresult = resultA\n\t\t} else {\n\t\t\tresult = resultB\n\t\t}\n\n\t\tif result < 0.00001 {\n\t\t\tisHit = false\n\t\t}\n\n\t\thitPoint = geo.Point3D{\n\t\t\tX: result*v.X + p.X,\n\t\t\tY: result*v.Y + p.Y,\n\t\t\tZ: result*v.Z + p.Z,\n\t\t}\n\t} else {\n\t\tisHit = false\n\t\thitPoint = geo.Point3D{}\n\t}\n\n\treturn isHit, hitPoint\n}", "func (i *Result) Intersection() []geom.Coord {\n\treturn i.intersection\n}", "func (i Intersections) Hit() (Intersection, bool) {\n\ti.Sort()\n\n\tfor _, intersection := range i {\n\t\tif intersection.T >= 0 {\n\t\t\treturn intersection, true\n\t\t}\n\t}\n\n\treturn Intersection{}, false\n}", "func (mr *MockAuthorizationPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockAuthorizationPolicySet)(nil).Intersection), set)\n}", "func GetXIntersects(p *Point, a, l float64) []*Point {\n\tad := float64(1)\n\top := math.Tan(a)\n\thy := math.Sqrt(math.Pow(ad, 2) + math.Pow(op, 2))\n\tq := GetQuadrant(a)\n\tif q == 2 || q == 3 {\n\t\top = -op\n\t\tad = -ad\n\t}\n\ts := int(l / hy)\n\tf := GetFirstXIntersect(p, a)\n\tis := []*Point{f}\n\tfor i := 0; i < s; i++ {\n\t\tx := is[len(is)-1].X + ad\n\t\ty := is[len(is)-1].Y + op\n\t\tis = append(is, NewPoint(x, y))\n\t}\n\treturn is\n}", "func Intersection() {\n\n}", "func (dim *Dimensions) isPointInside(p Point) bool {\n\treturn p.X >= dim.BottomLeft.X &&\n\t\tp.X <= dim.TopRight.X &&\n\t\tp.Y >= dim.BottomLeft.Y &&\n\t\tp.Y <= dim.TopRight.Y\n}", "func (l Line) Intersect(k Line) (Vec, bool) {\n\t// Check if the lines are parallel\n\tlDir := l.A.To(l.B)\n\tkDir := k.A.To(k.B)\n\tif lDir.X == kDir.X && lDir.Y == kDir.Y {\n\t\treturn ZV, false\n\t}\n\n\t// The lines intersect - but potentially not within the line segments.\n\t// Get the intersection point for the lines if they were infinitely long, check if the point exists on both of the\n\t// segments\n\tlm, lb := l.Formula()\n\tkm, kb := k.Formula()\n\n\t// Account for vertical lines\n\tif math.IsInf(math.Abs(lm), 1) && math.IsInf(math.Abs(km), 1) {\n\t\t// Both vertical, therefore parallel\n\t\treturn ZV, false\n\t}\n\n\tvar x, y float64\n\n\tif math.IsInf(math.Abs(lm), 1) || math.IsInf(math.Abs(km), 1) {\n\t\t// One line is vertical\n\t\tintersectM := lm\n\t\tintersectB := lb\n\t\tverticalLine := k\n\n\t\tif math.IsInf(math.Abs(lm), 1) {\n\t\t\tintersectM = km\n\t\t\tintersectB = kb\n\t\t\tverticalLine = l\n\t\t}\n\n\t\ty = intersectM*verticalLine.A.X + intersectB\n\t\tx = verticalLine.A.X\n\t} else {\n\t\t// Coordinates of intersect\n\t\tx = (kb - lb) / (lm - km)\n\t\ty = lm*x + lb\n\t}\n\n\tif l.Contains(V(x, y)) && k.Contains(V(x, y)) {\n\t\t// The intersect point is on both line segments, they intersect.\n\t\treturn V(x, y), true\n\t}\n\n\treturn ZV, false\n}", "func (mr *MockTrafficPolicySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockTrafficPolicySet)(nil).Intersection), set)\n}", "func IntersectionPolicy(sub ...GCPolicy) GCPolicy { return intersectionPolicy{sub} }", "func (e Entities) Intersects(rect pixel.Rect) (entities Entities) {\n\t// check if any entities returned intersect the given point and if they do add them to the return list\n\tfor i := range e {\n\t\t// add to list if they intersect\n\t\tif e[i].Intersects(rect) {\n\t\t\tentities = append(entities, e[i])\n\t\t}\n\t}\n\treturn\n}", "func (r Ray) LineIntersectCircle(c Circ) (g, h Vec) {\n\t/*\n\t\t(X - c.C.X)^2 + (Y - c.C.Y)^2 = c.R*c.R\n\t\tr.V.Y*X - r.V.X*Y - r.V.Y*r.O.X + r.V.X*r.O.Y = 0\n\n\t\tX*X - 2*c.C.X*X + c.C.X*c.C.X + Y*Y - 2*c.C.Y*Y + c.C.Y*c.C.Y = c.R*c.R\n\t\t(r.V.X*Y + r.V.Y*r.O.X - r.V.X*r.O.Y) / r.V.Y = X\n\n\t\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\t\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\n\t\tX*X - 2*c.C.X*X + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t(r.V.X*Y + b) / r.V.Y = X\n\n\t\t(r.V.X*Y + b)^2 / r.V.Y*r.V.Y - 2*c.C.X * (r.V.X*Y + b) / r.V.Y + Y*Y - 2*c.C.Y*Y + a = 0\n\t\t// * r.V.Y*r.V.Y\n\t\t(r.V.X*Y + b)^2 - 2*c.C.X*r.V.Y * (r.V.X*Y + b) + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// brackets\n\t\tr.V.X*r.V.X*Y*Y + 2*b*r.V.X*Y + b*b - 2*c.C.X*r.V.Y*r.V.X*Y - 2*c.C.X*r.V.Y*b + Y*Y*r.V.Y*r.V.Y - 2*c.C.Y*Y*r.V.Y*r.V.Y + a*r.V.Y*r.V.Y = 0\n\t\t// simplify\n\t\tY*Y * (r.V.X*r.V.X + r.V.Y*r.V.Y) + Y * (2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y) + b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y = 0\n\n\t\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\t\te := 2*b*r.V.X - 2*c.C.X*r.V.Y*r.V.X - 2*c.C.Y*r.V.Y*r.V.Y\n\t\tf := b*b - 2*c.C.X*r.V.Y*b + a*r.V.Y*r.V.Y\n\n\t\te := 2 * (b*r.V.X - r.V.Y * (c.C.X*r.V.X + c.C.Y*r.V.Y))\n\t*/\n\n\ta := c.C.X*c.C.X + c.C.Y*c.C.Y - c.R*c.R\n\tb := r.V.Y*r.O.X - r.V.X*r.O.Y\n\td := r.V.X*r.V.X + r.V.Y*r.V.Y\n\te := 2 * (b*r.V.X - r.V.Y*(c.C.X*r.V.X+c.C.Y*r.V.Y))\n\tf := b*b - r.V.Y*(2*c.C.X*b-a*r.V.Y)\n\n\tg.Y, h.Y = Polynomial(d, e, f)\n\tif r.V.Y == 0 {\n\t\tg.X, h.X = c.ProjectY(g.Y)\n\t} else {\n\t\tg.X = r.ProjectY(g.Y)\n\t\th.X = r.ProjectY(h.Y)\n\t}\n\n\treturn\n}", "func intersect(a interface{}, b interface{}) []interface{} {\n\tset := make([]interface{}, 0)\n\tav := reflect.ValueOf(a)\n\n\tfor i := 0; i < av.Len(); i++ {\n\t\tel := av.Index(i).Interface()\n\t\tif contains(b, el) {\n\t\t\tset = append(set, el)\n\t\t}\n\t}\n\n\treturn set\n}", "func Intersection(a, b AnySlice) AnySlice {\n\tmustBeSlice(a)\n\tmustBeSlice(b)\n\n\taVal := reflect.ValueOf(a)\n\tbVal := reflect.ValueOf(b)\n\taCount := aVal.Len()\n\tbCount := bVal.Len()\n\toutput := makeFilterSlice(a, 0, aCount+bCount)\n\tkeys := make(map[interface{}]bool)\n\n\tfor i := 0; i < aCount; i++ {\n\t\tkeys[aVal.Index(i).Interface()] = true\n\t}\n\tfor i := 0; i < bCount; i++ {\n\t\tkey := bVal.Index(i)\n\t\tif _, present := keys[key.Interface()]; present {\n\t\t\toutput = reflect.Append(output, key)\n\t\t}\n\t}\n\treturn output.Interface()\n}", "func (m *MockEnvoyFilterSet) Intersection(set v1alpha3sets.EnvoyFilterSet) v1alpha3sets.EnvoyFilterSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Intersection\", set)\n\tret0, _ := ret[0].(v1alpha3sets.EnvoyFilterSet)\n\treturn ret0\n}", "func (intGroup intersectionGroup) Includes(point vec3.Vec3) bool {\n\tfor _, shape := range intGroup.shapes {\n\t\tif !shape.Includes(point) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Test_314(t *testing.T) {\n\ttestName := \"Test_314\"\n\trunStart := time.Now()\n\tfmt.Printf(\"%s BBox Intersections\\n\", testName)\n\tdefer func() {\n\t\tVerbose.Printf(\"%s took %v\\n\", testName, time.Since(runStart))\n\t}()\n\tvar (\n\t\tmybox BBox = BBox{MinX: -76.932480, MinY: 36.549660, MaxX: -76.407532, MaxY: 36.921856}\n\t\trailbox BBox = BBox{MinX: -76.917970, MinY: 36.682432, MaxX: -76.916911, MaxY: 36.684338}\n\t)\n\n\tif !mybox.Sane() || !railbox.Sane() {\n\t\tt.Fatalf(\"Intersects() failed\")\n\t}\n\texpected := true\n\tvalue1 := mybox.Intersects(railbox)\n\tif value1 != expected {\n\t\tt.Errorf(\"Intersects() failed\")\n\t}\n\tvalue2 := railbox.Intersects(mybox)\n\tif value2 != expected {\n\t\tt.Errorf(\"Intersects() failed\")\n\t}\n}", "func (m *MockVirtualServiceSet) Intersection(set v1alpha3sets.VirtualServiceSet) v1alpha3sets.VirtualServiceSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Intersection\", set)\n\tret0, _ := ret[0].(v1alpha3sets.VirtualServiceSet)\n\treturn ret0\n}", "func (m *MockVirtualMeshSet) Intersection(set v1alpha1sets.VirtualMeshSet) v1alpha1sets.VirtualMeshSet {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Intersection\", set)\n\tret0, _ := ret[0].(v1alpha1sets.VirtualMeshSet)\n\treturn ret0\n}", "func (mr *MockFailoverServiceSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockFailoverServiceSet)(nil).Intersection), set)\n}", "func (mr *MockWasmDeploymentSetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockWasmDeploymentSet)(nil).Intersection), set)\n}", "func (mr *MockServiceEntrySetMockRecorder) Intersection(set interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"Intersection\", reflect.TypeOf((*MockServiceEntrySet)(nil).Intersection), set)\n}", "func (pg *Polygon) ConvexContains(x, y float64) bool {\n\n\tp := floatgeom.Point2{x, y}\n\n\tif !pg.Rect2.Contains(p) {\n\t\treturn false\n\t}\n\n\tprev := 0\n\tfor i := 0; i < len(pg.points); i++ {\n\t\ttp1 := pg.points[i]\n\t\ttp2 := pg.points[(i+1)%len(pg.points)]\n\t\ttp3 := tp2.Sub(tp1)\n\t\ttp4 := p.Sub(tp1)\n\t\tcur := getSide(tp3, tp4)\n\t\tif cur == 0 {\n\t\t\treturn false\n\t\t} else if prev == 0 {\n\t\t} else if prev != cur {\n\t\t\treturn false\n\t\t}\n\t\tprev = cur\n\t}\n\treturn true\n}", "func (p Point) In(r Rectangle) bool {\n\treturn p.X >= r.Min.X && p.X < r.Max.X &&\n\t\tp.Y >= r.Min.Y && p.Y < r.Max.Y\n}", "func (diffGroup differenceGroup) Intersect(r ray.Ray) *space.Hit {\n\thit := diffGroup.minuend.Intersect(r)\n\tif hit == nil {\n\t\treturn nil\n\t}\n\tif diffGroup.subtrahend.Includes(hit.Position) {\n\t\torignalT := hit.T\n\t\tr.Origin = hit.Position\n\t\t// r.T0 = 0.1\n\t\thit = diffGroup.subtrahend.Intersect(r)\n\t\tif hit == nil { // Should not happen. But it can when t.T0 is not 0\n\t\t\treturn nil\n\t\t}\n\t\tif !diffGroup.minuend.Includes(hit.Position) {\n\t\t\treturn nil\n\t\t}\n\t\thit.Normal = vec3.Multiply(-1, hit.Normal)\n\t\thit.T += orignalT\n\t}\n\treturn hit\n}", "func (g Object) Intersects(o Object) bool {\n\treturn g.bridge().Intersects(o.bridge())\n}" ]
[ "0.7775079", "0.7065693", "0.67297965", "0.66862243", "0.6208699", "0.6199219", "0.61559594", "0.61425704", "0.59394807", "0.58741903", "0.5868859", "0.5808127", "0.5806075", "0.56962264", "0.56702805", "0.5662324", "0.5646821", "0.5638325", "0.563644", "0.5608107", "0.55516326", "0.55066925", "0.54916406", "0.5442525", "0.53922117", "0.5384309", "0.53735715", "0.53709775", "0.5360459", "0.5327705", "0.53165305", "0.530051", "0.52921283", "0.52828866", "0.5280502", "0.52689624", "0.5262743", "0.52492553", "0.52218586", "0.5216221", "0.51980555", "0.518184", "0.51454043", "0.5140312", "0.5119266", "0.5117772", "0.5063587", "0.5041648", "0.50382113", "0.5032639", "0.49980268", "0.49930957", "0.49802494", "0.4977179", "0.4976471", "0.49565428", "0.49548793", "0.4946182", "0.49358308", "0.49328294", "0.49313176", "0.49298477", "0.49275938", "0.49235988", "0.49104816", "0.4902869", "0.4902453", "0.49015674", "0.4890469", "0.48859957", "0.4874465", "0.48685646", "0.48631477", "0.48596528", "0.48577714", "0.48536512", "0.4846047", "0.48355162", "0.48238048", "0.4812759", "0.47799197", "0.47751325", "0.47524238", "0.474494", "0.47400147", "0.47255492", "0.47234255", "0.47212207", "0.4714915", "0.47149137", "0.4713186", "0.47028276", "0.46942374", "0.46855593", "0.46798554", "0.4678706", "0.46775216", "0.46703613", "0.46639377", "0.4661968" ]
0.82112455
0
Add inserts a primitive in this voxel
func (v *Voxel) Add(p primitive.Primitive) { if p.CanIntersect() { v.primitives = append(v.primitives, p) } else { gridAccel := NewGrid(p.Refine()) v.primitives = append(v.primitives, gridAccel) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (v *Vertex) Add(d int, f float64) {\n\tv.Point[d] += f\n}", "func (r *ImageRef) Add(addend *ImageRef) error {\n\tout, err := vipsAdd(r.image, addend.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (_m *MockEStore) Add(object EObject, feature EStructuralFeature, index int, value interface{}) {\n\t_m.Called(object, feature, index, value)\n}", "func (geom Geometry) AddPoint(x, y, z float64) {\n\tC.OGR_G_AddPoint(geom.cval, C.double(x), C.double(y), C.double(z))\n}", "func (gdt *Vector3) OperatorAdd(b Vector3) Vector3 {\n\targ0 := gdt.getBase()\n\targ1 := b.getBase()\n\n\tret := C.go_godot_vector3_operator_add(GDNative.api, arg0, arg1)\n\n\treturn Vector3{base: &ret}\n\n}", "func (v *V) Add(x *V) *V {\n\tif !IsVSameShape(x, v) {\n\t\tpanic(ErrShape)\n\t}\n\tfor i, e := range x.Data {\n\t\tv.Data[i] += e\n\t}\n\treturn v\n}", "func (p PointI) Add(v VecI) PointI {\n\treturn PointI(VecI(p).Add(v))\n}", "func (v *Vec4) Add(x *Vec4) {\n\tv.X += x.X\n\tv.Y += x.Y\n\tv.Z += x.Z\n\tv.W += x.W\n}", "func (c *ClusterFixture) AddOne(object runtime.Object) {\n\tc.objects = append(c.objects, object)\n}", "func add(context *Context) {\n x := context.opcode & 0x0F00 >> 8\n y := context.opcode & 0x00F0 >> 4\n sum := uint16(context.cpu.v[x]) + uint16(context.cpu.v[y])\n if sum > 255 {\n context.cpu.v[0xF] = 1\n } else {\n context.cpu.v[0xF] = 0\n }\n context.cpu.v[x] = byte(sum & 0xFF)\n}", "func (c ClusterNodes) Add() {\n\n}", "func (p *IntVector) Push(x int)\t{ p.Vector.Push(x) }", "func (v Vec3i) Add(other Vec3i) Vec3i {\n\treturn Vec3i{v.X + other.X, v.Y + other.Y, v.Z + other.Z}\n}", "func (spriteBatch *SpriteBatch) Add(args ...float32) error {\n\treturn spriteBatch.addv(spriteBatch.texture.getVerticies(), generateModelMatFromArgs(args), -1)\n}", "func (p *Polygon) Add(x, y float64) *PolygonVertex {\n\treturn p.AddV2(v2.Vec{x, y})\n}", "func (v *Vector) AddTo(e *Vector) {\n\tv.X += e.X\n\tv.Y += e.Y\n\tv.Z += e.Z\n}", "func (this *NestedInteger) Add(elem NestedInteger) {}", "func (this *NestedInteger) Add(elem NestedInteger) {}", "func (this *NestedInteger) Add(elem NestedInteger) {}", "func (v Vec3i) AddScalar(s int32) Vec3i {\n\treturn Vec3i{v.X + s, v.Y + s, v.Z + s}\n}", "func (p *IntVector) Insert(i int, x int)\t{ p.Vector.Insert(i, x) }", "func (c *Contour) Add(p Point) {\n\t*c = append(*c, p)\n}", "func (v *Vec3i) SetAddScalar(s int32) {\n\tv.X += s\n\tv.Y += s\n\tv.Z += s\n}", "func (c Cluster) AddPoint(p int) {\n\tc.indices = append(c.indices, p)\n}", "func (s *Scalar) Add(x, y *Scalar) *Scalar {\n\ts.s.Add(&x.s, &y.s)\n\treturn s\n}", "func (t *Indexed) Add(x int, i, j int) {\n\n}", "func NewPrimitives() Primitives {\n\treturn Primitives{\n\t\t\"vtxs\": NewAttributes(Int, 0),\n\t}\n}", "func (g *Gini) Add(m z.Lit) {\n\tg.xo.Add(m)\n}", "func Add(z, x, y *Elt)", "func (p thinPoly) Add(a, b []int32) thinPoly {\n\tfor i := range a {\n\t\tp[i] = Freeze(a[i] + b[i])\n\t}\n\treturn p\n}", "func (r *ImageRef) Insert(sub *ImageRef, x, y int, expand bool, background *ColorRGBA) error {\n\tout, err := vipsInsert(r.image, sub.image, x, y, expand, background)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (r *Renderer) Add(o Object) {\n\tr.objects = append(r.objects, o)\n}", "func (t Table) Add(b box) error {\n\n\t// this also covers the case of an emptybox\n\tif !b.HasValidDimensions() {\n\t\treturn errors.New(\"Add box to table: Box has invalid size.\")\n\t}\n\n\thash, errHash := HashBox(&b)\n\n\tif errHash == nil {\n\t\tt[hash].Push(b)\n\t\treturn nil\n\t}\n\treturn errHash\n}", "func Add( a *context.Value, b *context.Value ) (*context.Value,error) {\n if a != nil && b != nil {\n switch a.OperationType( b ) {\n case context.VAR_BOOL:\n return context.IntValue( a.Int() + b.Int() ), nil\n case context.VAR_INT:\n return context.IntValue( a.Int() + b.Int() ), nil\n case context.VAR_FLOAT:\n return context.FloatValue( a.Float() + b.Float() ), nil\n case context.VAR_STRING:\n return context.StringValue( a.String() + b.String() ), nil\n case context.VAR_COMPLEX:\n return context.ComplexValue( a.Complex() + b.Complex() ), nil\n }\n }\n\n return nil, errors.New( \"Unsupported type for add\" )\n}", "func (a *Vec4) Add(b Vec4) {\n\ta.X += b.X\n\ta.Y += b.Y\n\ta.Z += b.Z\n\ta.W += b.W\n}", "func (v *Vector2) Add(b Vector2) {\r\n\tv.x += b.x\r\n\tv.y += b.y\r\n}", "func Add(v, u *Vec) *Vec {\n\treturn &Vec{\n\t\tv.X + u.X,\n\t\tv.Y + u.Y,\n\t}\n}", "func (c *Components) Add(object runtime.Object) *Vertex {\n\tmo, ok := object.(metav1.Object)\n\tif !ok {\n\t\tpanic(\"trying to add an object which does not implement metav1.Object\")\n\t}\n\n\tgvk, found, err := schema.GetGroupKindVersion(object)\n\tif err != nil || !found {\n\t\tpanic(\"trying to find the gvk of the resource \" + err.Error())\n\t}\n\n\tv := &Vertex{\n\t\tID: fmt.Sprintf(\"%s/%s/%s/%s/%s\",\n\t\t\tgvk.Group,\n\t\t\tgvk.Version,\n\t\t\tgvk.Kind,\n\t\t\tmo.GetNamespace(),\n\t\t\tmo.GetName(),\n\t\t),\n\t\tName: fmt.Sprintf(\"%s/%s\", gvk.Kind, mo.GetName()),\n\t\tObject: object,\n\t}\n\n\tif err := c.graph.AddVertex(v); err != nil {\n\t\tpanic(\"trying to add the object to the graph\")\n\t}\n\n\tif c.graph.GetSize() <= 0 {\n\t\t_ = c.graph.AddEdge(c.root, v)\n\t}\n\n\treturn v\n}", "func (array *Array) Add(object interface{}) {\n\tarray.data = append(array.data, object)\n}", "func (v *Vec3i) SetAdd(other Vec3i) {\n\tv.X += other.X\n\tv.Y += other.Y\n\tv.Z += other.Z\n}", "func (v1 *Vector3) Add(v2 *Vector3) Vector3 {\n\treturn Vector3{v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z}\n}", "func (m *Model) Add(t *Tree, stepSize float32) {\n\tt.Scale(stepSize)\n\tm.Trees = append(m.Trees, t)\n\tm.ExtraFeatures += t.NumFeatures()\n}", "func (h Handler) Add(obj runtime.Object) error {\n\tnode := obj.(*corev1.Node)\n\terr := h.nodeReaper.Run(node)\n\tif err != nil {\n\t\th.logger.Errorf(\"Error processing node %q: %s\", node.Name, err)\n\t}\n\treturn nil\n}", "func (v Vec3) Add(w Vec3) Vec3 {\n\treturn Vec3{v[0] + w[0], v[1] + w[1], v[2] + w[2]}\n}", "func (self *Vector) Add(other *Vector) {\n\tself.X = self.X + other.X\n\tself.Y = self.Y + other.Y\n}", "func (u *Vec3) Add(v *Vec3) *Vec3 {\n\ts := Vec3{\n\t\tu.X + v.X,\n\t\tu.Y + v.Y,\n\t\tu.Z + v.Z,\n\t}\n\treturn &s\n}", "func (i *Index) Add(key string, tags string, filepath string, isNew bool) {\n\ti.Objects = append(i.Objects, &Object{key, tags, filepath, isNew})\n}", "func Vadd(input1 []float32, input1Stride int, input2 []float32, input2Stride int, output []float32, outputStride int) {\n\tC.vDSP_vadd((*C.float)(&input1[0]), C.vDSP_Stride(input1Stride), (*C.float)(&input2[0]), C.vDSP_Stride(input2Stride), (*C.float)(&output[0]), C.vDSP_Stride(outputStride), minLen(len(input1)/input1Stride, len(input2)/input2Stride, len(output)/outputStride))\n}", "func (z *Big) Add(x, y *Big) *Big { return z.Context.Add(z, x, y) }", "func vectorAddScalar(v []*operation.Scalar, s *operation.Scalar) []*operation.Scalar {\n\tresult := make([]*operation.Scalar, len(v))\n\tfor i := range v {\n\t\tresult[i] = new(operation.Scalar).Add(v[i], s)\n\t}\n\treturn result\n}", "func Add(v1, v2 Vector) Vector {\n\treturn Vector{\n\t\tX: v1.X + v2.X,\n\t\tY: v1.Y + v2.Y,\n\t\tZ: v1.Z + v2.Z,\n\t}\n}", "func (p *Polygon) Add(c Contour) {\n\t*p = append(*p, c)\n}", "func Add(s Spot) {\n\tpersist(s, add)\n}", "func (v Posit8x4) Add(x Posit8x4) Posit8x4 {\n\tout := Posit8x4{impl: make([]Posit8, 4)}\n\tfor i, posit := range v.impl {\n\t\tout.impl[i] = posit.Add(x.impl[i])\n\t}\n\treturn out\n}", "func (v Vector3D) Add(other Vector3D) Vector3D {\n\treturn Vector3D{\n\t\tx: v.x + other.x,\n\t\ty: v.y + other.y,\n\t\tz: v.z + other.z,\n\t}\n}", "func (o *FloatObject) Add(r Object) (Object) {\n result := new (FloatObject)\n result.Value = o.Value + r.AsFloat()\n \n return result\n}", "func (v *Vector) Add(u *Vector) *Vector {\n\n\tx := (v.X + u.X)\n\ty := (v.Y + u.Y)\n\treturn &Vector{\n\t\tX: (x),\n\t\tY: (y),\n\t}\n}", "func VHADDPD(mxy, xy, xy1 operand.Op) { ctx.VHADDPD(mxy, xy, xy1) }", "func Primitive(name string, fun PrimitiveFunction, result *Object, args []*Object, rest *Object, defaults []*Object, keys []*Object) *Object {\n\t// the rest type indicates arguments past the end of args will all have the given type. the length must be checked by primitive\n\t// -> they are all optional, then. So, (<any>+) must be expressed as (<any> <any>*)\n\tidx := len(primitives)\n\targc := len(args)\n\tif defaults != nil {\n\t\tdefc := len(defaults)\n\t\tif defc > argc {\n\t\t\tpanic(\"more default argument values than types: \" + name)\n\t\t}\n\t\tif keys != nil {\n\t\t\tif len(keys) != defc {\n\t\t\t\tpanic(\"Argument keys must have same length as argument defaults\")\n\t\t\t}\n\t\t}\n\t\targc = argc - defc\n\t\tfor i := 0; i < defc; i++ {\n\t\t\tt := args[argc+i]\n\t\t\tif t != AnyType && defaults[i].Type != t {\n\t\t\t\tpanic(\"argument default's type (\" + defaults[i].Type.text + \") doesn't match declared type (\" + t.text + \")\")\n\t\t\t}\n\t\t}\n\t} else {\n\t\tif keys != nil {\n\t\t\tpanic(\"Cannot have argument keys without argument defaults\")\n\t\t}\n\t}\n\tsignature := functionSignatureFromTypes(result, args, rest) // functionSignatureFromTypes was defined in runtime.go - 184 line\n\tprim := &primitive{name, fun, signature, idx, argc, result, args, rest, defaults, keys}\n\tprimitives = append(primitives, prim)\n\treturn &Object{Type: FunctionType, primitive: prim}\n}", "func VADDPD(ops ...operand.Op) { ctx.VADDPD(ops...) }", "func (c *Compound) Add(k string, v Modifiable) (err error) {\n\tif _, ok := c.subRenderables[k]; ok {\n\t\terr = errors.New(\"Key already defined. Overwriting\")\n\t}\n\tc.lock.Lock()\n\tc.subRenderables[k] = v\n\tc.lock.Unlock()\n\treturn err\n}", "func VINSERTPS(i, mx, x, x1 operand.Op) { ctx.VINSERTPS(i, mx, x, x1) }", "func (m *Matrix) Add(x, y int, v int64) {\n\tov, _ := m.Get(x, y)\n\tm.Set(x, y, int64(ov)+v)\n}", "func (w *World) Add(h Hitable) {\n\tw.elements = append(w.elements, h)\n}", "func Add(db sql.Executor, ref types.PoetProofRef, poet, serviceID []byte, roundID string) error {\n\tenc := func(stmt *sql.Statement) {\n\t\tstmt.BindBytes(1, ref[:])\n\t\tstmt.BindBytes(2, poet)\n\t\tstmt.BindBytes(3, serviceID)\n\t\tstmt.BindBytes(4, []byte(roundID))\n\t}\n\t_, err := db.Exec(`\n\t\tinsert into poets (ref, poet, service_id, round_id) \n\t\tvalues (?1, ?2, ?3, ?4);`, enc, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"exec: %w\", err)\n\t}\n\n\treturn nil\n}", "func GxTourPrimitive(children ...Element) *CompoundElement { return newCE(\"gx:TourPrimitive\", children) }", "func (vm *VM) opAdd(instr []uint16) int {\n\ta, b, c := vm.getAbc(instr)\n\n\tvm.registers[a] = (b + c) % 32768\n\treturn 4\n}", "func (inj Injections) Add(i interface{}) {\n\tinj[reflect.TypeOf(i)] = i\n}", "func (v Vector3) Add(other Vector3) Vector3 {\n\treturn Vector3{X: v.X + other.X, Y: v.Y + other.Y, Z: v.Z + other.Z}\n}", "func (a *Vector3) Plus(b Vector3) {\n\t*a = Vector3{a.X + b.X, a.Y + b.Y, a.Z + b.Z}\n}", "func (s *ParticlePhysicsSystem) Add(entity particle) {\n\ts.ParticleEngine.Add(entity)\n}", "func (v *Vector3D) Add(v2 Vector3D) Vector3D {\n\treturn Vector3D{v.E1 + v2.E1, v.E2 + v2.E2, v.E3 + v2.E3}\n}", "func addb(context *Context) {\n x := context.opcode & 0x0F00 >> 8\n b := byte(context.opcode & 0x00FF)\n context.cpu.v[x] += b\n context.cpu.pc += 2\n}", "func (o *WlRegion) Add(x wire.Int, y wire.Int, width wire.Int, height wire.Int) error {\n\tmsg, err := wire.NewMessage(o.ID(), 1)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err = msg.Write(x); err != nil {\n\t\treturn err\n\t}\n\n\tif err = msg.Write(y); err != nil {\n\t\treturn err\n\t}\n\n\tif err = msg.Write(width); err != nil {\n\t\treturn err\n\t}\n\n\tif err = msg.Write(height); err != nil {\n\t\treturn err\n\t}\n\n\tif err = o.Base.Conn.Write(msg); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *Point) Add(p2 Point) {\n\tp.X += p2.X\n\tp.Y += p2.Y\n\tp.Z += p2.Z\n}", "func appendInc(inPtr *treeNode) {\n\t// Add the element's memory address to the collection array\n\tmyTree = append(myTree, inPtr)\n\n\t// Add the node's value to a running total\n\tmyTreeTotal = myTreeTotal + inPtr.Value\n\n\treturn\n}", "func (c *Changer) Add(v interface{}) error {\n\tif c.err != nil {\n\t\treturn c.err\n\t}\n\t_, err := c.node.addChild(justValue{v})\n\treturn err\n}", "func (l *Int32) Add(value int32) {\n\tl.values = append(l.values, value)\n}", "func VPHADDSW(mxy, xy, xy1 operand.Op) { ctx.VPHADDSW(mxy, xy, xy1) }", "func (c *Calculator) AddVertex(id string) {\n\tc.g.AddVertex(id, nil)\n}", "func (obj *Device) DrawPrimitive(\n\ttyp PRIMITIVETYPE,\n\tstartVertex uint,\n\tprimitiveCount uint,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.DrawPrimitive,\n\t\t4,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(typ),\n\t\tuintptr(startVertex),\n\t\tuintptr(primitiveCount),\n\t\t0,\n\t\t0,\n\t)\n\treturn toErr(ret)\n}", "func Add() {\n\tMatch('+')\n\tTerm()\n\tEmitLn(\"ADD (SP)+,D0\")\n}", "func add(this js.Value, i []js.Value) interface{} {\n\tin1, in2 := getInputValues(i)\n\tsetValueById(i[2].String(), in1+in2)\n\treturn nil\n}", "func Add(valueA gcv.Value, valueB gcv.Value) gcv.Value {\n\tif valueA.Type() == gcv.Complex || valueB.Type() == gcv.Complex {\n\t\treturn gcv.MakeValue(valueA.Complex() + valueB.Complex())\n\t}\n\treturn gcv.MakeValue(valueA.Real() + valueB.Real())\n}", "func (a *World) Add(obj geo.Hittable) *World {\n\ta.Objs = append(a.Objs, obj)\n\treturn a\n}", "func (p Point) Add(v Vec) Point {\n\treturn Point(Vec(p).Add(v))\n}", "func (spriteBatch *SpriteBatch) addv(verts []float32, mat *mgl32.Mat4, index int) error {\n\tif index == -1 && spriteBatch.count >= spriteBatch.size {\n\t\treturn fmt.Errorf(\"Sprite Batch Buffer Full\")\n\t}\n\n\tsprite := make([]float32, 8*4)\n\tfor i := 0; i < 32; i += 8 {\n\t\tj := (i / 2)\n\t\tsprite[i+0] = (mat[0] * verts[j+0]) + (mat[4] * verts[j+1]) + mat[12]\n\t\tsprite[i+1] = (mat[1] * verts[j+0]) + (mat[5] * verts[j+1]) + mat[13]\n\t\tsprite[i+2] = verts[j+2]\n\t\tsprite[i+3] = verts[j+3]\n\t\tsprite[i+4] = spriteBatch.color[0]\n\t\tsprite[i+5] = spriteBatch.color[1]\n\t\tsprite[i+6] = spriteBatch.color[2]\n\t\tsprite[i+7] = spriteBatch.color[3]\n\t}\n\n\tif index == -1 {\n\t\tspriteBatch.arrayBuf.fill(spriteBatch.count*4*8, sprite)\n\t\tspriteBatch.count++\n\t} else {\n\t\tspriteBatch.arrayBuf.fill(index*4*8, sprite)\n\t}\n\n\treturn nil\n}", "func (l *LifeSystem) Add(\n\tbasic *ecs.BasicEntity,\n\trender *common.RenderComponent,\n\tspace *common.SpaceComponent,\n\talive *AliveComponent,\n) {\n\tl.entities = append(l.entities, AliveEntity{\n\t\tbasic,\n\t\trender,\n\t\tspace,\n\t\talive,\n\t})\n}", "func (p Point) add(p1 Point) Point {\n\tp.x = p.x + p1.x\n\tp.y = p.y + p1.y\n\treturn p\n}", "func addi(context *Context) {\n x := context.opcode & 0x0F00 >> 8\n context.cpu.i += uint16(context.cpu.v[x])\n}", "func InplaceAdd(scope *Scope, x tf.Output, i tf.Output, v tf.Output) (y tf.Output) {\n\tif scope.Err() != nil {\n\t\treturn\n\t}\n\topspec := tf.OpSpec{\n\t\tType: \"InplaceAdd\",\n\t\tInput: []tf.Input{\n\t\t\tx, i, v,\n\t\t},\n\t}\n\top := scope.AddOperation(opspec)\n\treturn op.Output(0)\n}", "func (u Vec) Add(v Vec) Vec {\n\treturn Vec{\n\t\tu.X + v.X,\n\t\tu.Y + v.Y,\n\t}\n}", "func (n *NestedInteger) Add(elem NestedInteger) {\n\tn.Ns = append(n.Ns, &elem)\n}", "func VPHADDW(mxy, xy, xy1 operand.Op) { ctx.VPHADDW(mxy, xy, xy1) }", "func (v Vector) Add(o Vector) *Vector {\n\treturn &Vector{v[0] + o[0], v[1] + o[1], v[2] + o[2]}\n}", "func (i *Int32) Add(delta int32) (new int32) {\n\treturn atomic.AddInt32(&i.v, delta)\n}", "func add1(x, y int64) int64", "func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} }", "func (p Point) Add(q Point) Point { return Point{p.X + q.X, p.Y + q.Y} }", "func (c CRImage) Add() error {\n\terr := dbmap.Insert(&c)\n\treturn err\n}" ]
[ "0.563763", "0.559073", "0.55426115", "0.5488095", "0.5476816", "0.5421942", "0.537828", "0.5371698", "0.53610176", "0.53507894", "0.53249985", "0.5315086", "0.5261477", "0.5239808", "0.5230816", "0.5224738", "0.5216043", "0.5216043", "0.5216043", "0.5214102", "0.52044046", "0.51951396", "0.5186022", "0.5184941", "0.5135834", "0.5128192", "0.51205474", "0.51138276", "0.51126033", "0.50943905", "0.5094143", "0.50940675", "0.5088631", "0.5088426", "0.50877064", "0.5080186", "0.5078461", "0.50677204", "0.50465846", "0.50422645", "0.50413656", "0.5041334", "0.50051475", "0.5003005", "0.49993396", "0.4996936", "0.49900642", "0.49881142", "0.49867758", "0.49838838", "0.4981251", "0.49698454", "0.49587238", "0.4958366", "0.49574012", "0.49483657", "0.49470103", "0.49454296", "0.49450332", "0.49427864", "0.49347425", "0.49305362", "0.49300966", "0.492019", "0.4917745", "0.49163395", "0.49153775", "0.4907506", "0.4905734", "0.4903665", "0.49024037", "0.49002248", "0.4899835", "0.4894628", "0.4892884", "0.48917753", "0.4889335", "0.48855892", "0.48826054", "0.48822245", "0.4867171", "0.48537078", "0.48524496", "0.4842953", "0.48388392", "0.48380727", "0.4830726", "0.48295695", "0.48272625", "0.48173955", "0.48077354", "0.4807465", "0.48023543", "0.4798363", "0.47965297", "0.47926623", "0.4786902", "0.47844982", "0.47844982", "0.4782042" ]
0.78058416
0
Recover verifies signature with the data base provided. It is using `btcec.RecoverCompact` function
func Recover(signature, data []byte) (*ecdsa.PublicKey, error) { p, _, err := btcec.RecoverCompact(btcec.S256(), signature, data) return (*ecdsa.PublicKey)(p), err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TestRecoverSanity(t *testing.T) {\n\tmsg, _ := hex.DecodeString(\"ce0677bb30baa8cf067c88db9811f4333d131bf8bcf12fe7065d211dce971008\")\n\tsig, _ := hex.DecodeString(\"90f27b8b488db00b00606796d2987f6a5f59ae62ea05effe84fef5b8b0e549984a691139ad57a3f0b906637673aa2f63d1f55cb1a69199d4009eea23ceaddc9301\")\n\tpubkey1, _ := hex.DecodeString(\"04e32df42865e97135acfb65f3bae71bdc86f4d49150ad6a440b6f15878109880a0a2b2667f7e725ceea70c673093bf67663e0312623c8e091b13cf2c0f11ef652\")\n\tpubkey2, err := RecoverPubkey(msg, sig)\n\tif err != nil {\n\t\tt.Fatalf(\"recover error: %s\", err)\n\t}\n\tif !bytes.Equal(pubkey1, pubkey2) {\n\t\tt.Errorf(\"pubkey mismatch: want: %x have: %x\", pubkey1, pubkey2)\n\t}\n}", "func RecoverCompact(signature, hash []byte) (*PublicKey, bool, error) {\n\tbitlen := (S256().BitSize + 7) / 8\n\tif len(signature) != 1+bitlen*2 {\n\t\treturn nil, false, errors.New(\"invalid compact signature size\")\n\t}\n\n\titeration := int((signature[0] - 27) & ^byte(4))\n\n\t// format is <header byte><bitlen R><bitlen S>\n\tsig := &Signature{\n\t\tR: new(big.Int).SetBytes(signature[1 : bitlen+1]),\n\t\tS: new(big.Int).SetBytes(signature[bitlen+1:]),\n\t}\n\t// The iteration used here was encoded\n\tkey, err := recoverKeyFromSignature(sig, hash, iteration, false)\n\tif err != nil {\n\t\treturn nil, false, err\n\t}\n\n\treturn key, ((signature[0] - 27) & 4) == 4, nil\n}", "func SolidityRecover(hash []byte, sig []byte) (common.Address, error) {\n\tif len(sig) != 65 {\n\t\treturn common.Address{}, fmt.Errorf(\"signature must be 65 bytes, got %d bytes\", len(sig))\n\t}\n\tstdSig := make([]byte, 65)\n\tcopy(stdSig[:], sig[:])\n\tstdSig[len(sig)-1] -= 27\n\n\tvar signer common.Address\n\tpubKey, err := crypto.Ecrecover(hash, stdSig)\n\tif err != nil {\n\t\treturn signer, err\n\t}\n\n\tcopy(signer[:], crypto.Keccak256(pubKey[1:])[12:])\n\treturn signer, nil\n}", "func BitcoinRecover(hash []byte, sig []byte) (common.Address, error) {\n\tif len(sig) != 65 {\n\t\treturn common.Address{}, fmt.Errorf(\"signature must be 65 bytes, got %d bytes\", len(sig))\n\t}\n\tstdSig := make([]byte, 65)\n\tcopy(stdSig[:], sig[:])\n\tstdSig[len(sig)-1] -= 27\n\n\tvar signer common.Address\n\tpubKey, err := crypto.SigToPub(hash, stdSig)\n\tif err != nil {\n\t\treturn signer, err\n\t}\n\n\tpubKeyBytes := secp256k1.CompressPubkey(pubKey.X, pubKey.Y)\n\tsigner = BitcoinAddress(pubKeyBytes)\n\n\treturn signer, nil\n}", "func finalRecover() {\n\tif p := recover(); p != nil {\n\t\tfmt.Fprintln(os.Stderr, \"ERROR: Something terrible has happened. Please file a ticket with this info:\")\n\t\tfmt.Fprintf(os.Stderr, \"ERROR: %v\\n%v\\n\", p, string(debug.Stack()))\n\t\tfailureExit(nil)\n\t}\n\tsuccessExit()\n}", "func Verify(data []byte, options VerifyOptions) (*Result, error) {\n\tcose := cosePayload{}\n\n\terr := cbor.Unmarshal(data, &cose)\n\tif nil != err {\n\t\treturn nil, ErrBadCOSESign1Structure\n\t}\n\n\tif nil == cose.Protected || 0 == len(cose.Protected) {\n\t\treturn nil, ErrCOSESign1EmptyProtectedSection\n\t}\n\n\tif nil == cose.Payload || 0 == len(cose.Payload) {\n\t\treturn nil, ErrCOSESign1EmptyPayloadSection\n\t}\n\n\tif nil == cose.Signature || 0 == len(cose.Signature) {\n\t\treturn nil, ErrCOSESign1EmptySignatureSection\n\t}\n\n\theader := coseHeader{}\n\terr = cbor.Unmarshal(cose.Protected, &header)\n\tif nil != err {\n\t\treturn nil, ErrBadCOSESign1Structure\n\t}\n\n\tif \"ECDSA384\" != header.Algorithm {\n\t\treturn nil, ErrCOSESign1BadAlgorithm\n\t}\n\n\tdoc := Document{}\n\n\terr = cbor.Unmarshal(cose.Payload, &doc)\n\tif nil != err {\n\t\treturn nil, ErrBadAttestationDocument\n\t}\n\n\tif \"\" == doc.ModuleID || \"\" == doc.Digest || 0 == doc.Timestamp || nil == doc.PCRs || nil == doc.Certificate || nil == doc.CABundle {\n\t\treturn nil, ErrMandatoryFieldsMissing\n\t}\n\n\tif \"SHA384\" != doc.Digest {\n\t\treturn nil, ErrBadDigest\n\t}\n\n\tif doc.Timestamp < 1 {\n\t\treturn nil, ErrBadTimestamp\n\t}\n\n\tif len(doc.PCRs) < 1 || len(doc.PCRs) > 32 {\n\t\treturn nil, ErrBadPCRs\n\t}\n\n\tfor key, value := range doc.PCRs {\n\t\tif key < 0 || key > 31 {\n\t\t\treturn nil, ErrBadPCRIndex\n\t\t}\n\n\t\tif nil == value || 32 != len(value) || 48 != len(value) || 64 != len(value) {\n\t\t\treturn nil, ErrBadPCRValue\n\t\t}\n\t}\n\n\tif len(doc.CABundle) < 1 {\n\t\treturn nil, ErrBadCABundle\n\t}\n\n\tfor _, item := range doc.CABundle {\n\t\tif nil == item || len(item) < 1 || len(item) > 1024 {\n\t\t\treturn nil, ErrBadCABundleItem\n\t\t}\n\t}\n\n\tif nil != doc.PublicKey && (len(doc.PublicKey) < 1 || len(doc.PublicKey) > 1024) {\n\t\treturn nil, ErrBadPublicKey\n\t}\n\n\tif nil != doc.UserData && (len(doc.UserData) < 1 || len(doc.UserData) > 512) {\n\t\treturn nil, ErrBadUserData\n\t}\n\n\tif nil != doc.Nonce && (len(doc.Nonce) < 1 || len(doc.Nonce) > 512) {\n\t\treturn nil, ErrBadNonce\n\t}\n\n\tcertificates := make([]*x509.Certificate, 0, len(doc.CABundle)+1)\n\n\tcert, err := x509.ParseCertificate(doc.Certificate)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tif x509.ECDSA != cert.PublicKeyAlgorithm {\n\t\treturn nil, ErrBadCertificatePublicKeyAlgorithm\n\t}\n\n\tif x509.ECDSAWithSHA384 != cert.SignatureAlgorithm {\n\t\treturn nil, ErrBadCertificateSigningAlgorithm\n\t}\n\n\tcertificates = append(certificates, cert)\n\n\tintermediates := x509.NewCertPool()\n\n\tfor _, item := range doc.CABundle {\n\t\tcert, err := x509.ParseCertificate(item)\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tintermediates.AddCert(cert)\n\t\tcertificates = append(certificates, cert)\n\t}\n\n\troots := options.Roots\n\tif nil == roots {\n\t\troots = defaultRoot\n\t}\n\n\tcurrentTime := options.CurrentTime\n\tif currentTime.IsZero() {\n\t\tcurrentTime = time.Now()\n\t}\n\n\t_, err = cert.Verify(x509.VerifyOptions{\n\t\tIntermediates: intermediates,\n\t\tRoots: roots,\n\t\tCurrentTime: currentTime,\n\t\tKeyUsages: []x509.ExtKeyUsage{\n\t\t\tx509.ExtKeyUsageAny,\n\t\t},\n\t})\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tsigStruct, err := cbor.Marshal(&coseSignature{\n\t\tContext: \"Signature1\",\n\t\tProtected: cose.Protected,\n\t\tExternalAAD: []byte{},\n\t\tPayload: cose.Payload,\n\t})\n\tif nil != err {\n\t\tpanic(fmt.Sprintf(\"Failed to marshal a cbor signature structure %v\", err))\n\t}\n\n\terr = cert.CheckSignature(x509.ECDSAWithSHA384, sigStruct, cose.Signature)\n\tif nil != err {\n\t\treturn nil, ErrBadSignature\n\t}\n\n\treturn &Result{\n\t\tDocument: &doc,\n\t\tCertificates: certificates,\n\t\tProtected: cose.Protected,\n\t\tUnprotected: cose.Unprotected,\n\t\tPayload: cose.Payload,\n\t\tSignature: cose.Signature,\n\t\tCOSESign1: sigStruct,\n\t}, nil\n}", "func Recover(params PrivateParameters, digest *Digest) ([]byte, error) {\n\tif digest.PreHash || digest.PostHashLen > 0 {\n\t\treturn nil, errors.New(\"password cannot be recovered\")\n\t}\n\n\tif !bytes.Equal(digest.ModulusID, params.ModulusID()) {\n\t\treturn nil, ErrWrongParams\n\t}\n\n\ty := new(big.Int).SetBytes(digest.Hash)\n\tp := params.P\n\tq := params.Q\n\tiq := new(big.Int).ModInverse(q, p)\n\tep := sqrtExp(p, digest.WorkFactor+1)\n\teq := sqrtExp(q, digest.WorkFactor+1)\n\n\tx1p := new(big.Int).Mod(y, p)\n\tx1p = x1p.Exp(x1p, ep, p)\n\n\tx1q := new(big.Int).Mod(y, q)\n\tx1q = x1q.Exp(x1q, eq, q)\n\n\tx2p := new(big.Int).Sub(p, x1p)\n\tx2p = x2p.Mod(x2p, p)\n\n\tx2q := new(big.Int).Sub(q, x1q)\n\tx2q = x2q.Mod(x2q, q)\n\n\txc := []*big.Int{\n\t\tcrt(p, q, iq, x1p, x1q),\n\t\tcrt(p, q, iq, x1p, x2q),\n\t\tcrt(p, q, iq, x2p, x1q),\n\t\tcrt(p, q, iq, x2p, x2q),\n\t}\n\n\tfor _, v := range xc {\n\t\tbuf := pad(params.N, v)\n\n\t\tif buf[0] != 0x00 {\n\t\t\tcontinue\n\t\t}\n\n\t\tk := len(buf)\n\t\tu := int(buf[k-1]) & 0xFF\n\t\tif u > (k - 32) {\n\t\t\tcontinue\n\t\t}\n\n\t\tpassword := buf[k-u-1 : len(buf)-1]\n\n\t\tx := kdf(params.Hash, append(append(digest.Salt, password...), byte(u)), k-2-u)\n\t\tx = append(append(append([]byte{0x00}, x...), password...), byte(u))\n\n\t\tif subtle.ConstantTimeCompare(x, buf) == 1 {\n\t\t\treturn password, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"password cannot be recovered\")\n}", "func RecoverBlockchainMetadata(ledgerFilename string, metadataFilename string, accountBalanceTable string) error {\n\t//check if metadata file exists\n\terr := emptyFile(metadataFilename)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create an empty metadata file: %s\", err.Error())\n\t\treturn errors.New(\"Failed to create an empty metadata file\")\n\t}\n\t//check if account balance file exists\n\terr = emptyFile(accountBalanceTable)\n\tif err != nil {\n\t\tlog.Printf(\"Failed to create an empty account file: %s\", err.Error())\n\t\treturn errors.New(\"Failed to create an empty account file\")\n\t}\n\n\t//set up the two database tables\n\tmetaDb, err := sql.Open(\"sqlite3\", metadataFilename)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open newly created metadata db\")\n\t}\n\tdefer metaDb.Close()\n\t_, err = metaDb.Exec(sqlstatements.CREATE_METADATA_TABLE)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to create metadata table\")\n\t}\n\n\taccDb, err := sql.Open(\"sqlite3\", accountBalanceTable)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open newly created accounts db\")\n\t}\n\tdefer accDb.Close()\n\t_, err = accDb.Exec(sqlstatements.CREATE_ACCOUNT_BALANCES_TABLE)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to create acount_balances table\")\n\t}\n\n\t// open ledger file\n\tledgerFile, err := os.OpenFile(ledgerFilename, os.O_RDONLY, 0644)\n\tif err != nil {\n\t\treturn errors.New(\"Failed to open ledger file\")\n\t}\n\tdefer ledgerFile.Close()\n\n\t// loop that adds blocks' metadata into database\n\tbPosition := int64(0)\n\tfor {\n\t\tbOldPos := bPosition\n\t\tdeserializedBlock, bLen, err := extractBlock(ledgerFile, &bPosition)\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t} else if err != nil {\n\t\t\tlog.Printf(\"Failed to extract block from ledger: %s\", err.Error())\n\t\t\treturn errors.New(\"Failed to extract block from ledger\")\n\t\t}\n\n\t\t//update the metadata table\n\t\terr = insertMetadata(metaDb, deserializedBlock, bLen, bOldPos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t//update the account table\n\t\terr = accountstable.UpdateAccountTable(accDb, deserializedBlock)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn err\n}", "func (mr *MockRecoverer) Ecrecover(data []byte, sig Signature) ([]byte, error) {\n\treturn wutil.Ecrecover(data, sig)\n}", "func (c CouchbaseFleet) verifyCleanSlate() error {\n\n\tif c.SkipCleanSlateCheck {\n\t\treturn nil\n\t}\n\n\tkey := path.Join(KEY_NODE_STATE)\n\n\t_, err := c.etcdClient.Get(key, false, false)\n\n\t// if that key exists, there is residue and we should abort\n\tif err == nil {\n\t\treturn fmt.Errorf(\"Found residue -- key: %v in etcd. You should destroy the cluster first, then try again.\", KEY_NODE_STATE)\n\t}\n\n\t// if we get an error with \"key not found\", then we are starting\n\t// with a clean slate\n\tif strings.Contains(err.Error(), \"Key not found\") {\n\t\treturn nil\n\t}\n\n\t// if we got a different error rather than \"Key not found\", treat that as\n\t// an error as well.\n\treturn fmt.Errorf(\"Unexpected error trying to get key: %v: %v\", KEY_NODE_STATE, err)\n\n}", "func main() {\n\ttryRecover()\n}", "func (_DelegatableDai *DelegatableDaiCallerSession) Recover(hash [32]byte, sig []byte) (common.Address, error) {\n\treturn _DelegatableDai.Contract.Recover(&_DelegatableDai.CallOpts, hash, sig)\n}", "func (c CouchbaseFleet) verifyCleanSlate() error {\n\n\tif c.SkipCleanSlateCheck {\n\t\treturn nil\n\t}\n\n\tkey := path.Join(KEY_NODE_STATE)\n\n\t_, err := c.etcdClient.Get(key, false, false)\n\n\t// if that key exists, there is residue and we should abort\n\tif err == nil {\n\t\treturn fmt.Errorf(\"Found residue -- key: %v in etcd. Destroy cluster first\", KEY_NODE_STATE)\n\t}\n\n\t// if we get an error with \"key not found\", then we are starting\n\t// with a clean slate\n\tif strings.Contains(err.Error(), \"Key not found\") {\n\t\treturn nil\n\t}\n\n\t// if we got a different error rather than \"Key not found\", treat that as\n\t// an error as well.\n\treturn fmt.Errorf(\"Unexpected error trying to get key: %v: %v\", KEY_NODE_STATE, err)\n\n}", "func (_DelegatableDai *DelegatableDaiSession) Recover(hash [32]byte, sig []byte) (common.Address, error) {\n\treturn _DelegatableDai.Contract.Recover(&_DelegatableDai.CallOpts, hash, sig)\n}", "func checkSignature(s string) ([]byte, error) {\n\tif 128 != len(s) {\n\t\treturn nil, fault.TransactionIdIsRequired\n\t}\n\th, err := hex.DecodeString(s)\n\tif nil != err {\n\t\treturn nil, err\n\n\t}\n\treturn h, nil\n}", "func (_DelegatableDai *DelegatableDaiCaller) Recover(opts *bind.CallOpts, hash [32]byte, sig []byte) (common.Address, error) {\n\tvar (\n\t\tret0 = new(common.Address)\n\t)\n\tout := ret0\n\terr := _DelegatableDai.contract.Call(opts, out, \"recover\", hash, sig)\n\treturn *ret0, err\n}", "func wronglySignDigestedRef(manifestRef name.Digest, key *cosign.KeysBytes) (oci.Signature, error) {\n\tmanifestRefNoHash := strings.Split(manifestRef.String(), \"@\")[0]\n\twrongManifest, err := name.NewDigest(manifestRefNoHash + \"@sha256:\" + wrongHash)\n\tif err != nil {\n\t\treturn nil, trace.Wrap(err)\n\t}\n\tsigPayload := payload.Cosign{\n\t\tImage: wrongManifest,\n\t}\n\n\treturn signPayload(sigPayload, key)\n}", "func RecoverVerifyingTortoise(mdb retriever) (interface{}, error) {\n\treturn mdb.Retrieve(mesh.TORTOISE, &turtle{})\n}", "func recoverfunc2() {\n\tif rx := recover(); rx != nil {\n\t\tfmt.Println(\"recovered from \", rx)\n\t}\n}", "func tcRecover(n *ir.CallExpr) ir.Node {\n\tif len(n.Args) != 0 {\n\t\tbase.Errorf(\"too many arguments to recover\")\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\n\tn.SetType(types.Types[types.TINTER])\n\treturn n\n}", "func verifyAndDecode(data []byte, kr openpgp.KeyRing) (*openpgp.Entity, []byte, []byte, error) {\n\t// Decode clearsign block.\n\tb, rest := clearsign.Decode(data)\n\tif b == nil {\n\t\treturn nil, nil, rest, errClearsignedMsgNotFound\n\t}\n\n\t// Check signature.\n\te, err := openpgp.CheckDetachedSignature(kr, bytes.NewReader(b.Bytes), b.ArmoredSignature.Body, nil)\n\treturn e, b.Plaintext, rest, err\n}", "func Recover(hash []byte, sig []byte) (*ecdsa.PublicKey, error) {\n\treturn crypto.SigToPub(hash, sig)\n}", "func recoverAddress(signature, digest []byte) ([]byte, error) {\n\trecoveredPublicKey, err := crypto.Recover(signature, digest)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trecoveredEthereumAddress, err := crypto.NewEthereumAddress(*recoveredPublicKey)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn recoveredEthereumAddress, nil\n}", "func recover() interface{} {\n\treturn nil\n}", "func (syncer *MerkleSyncer) recover(begin, end uint64) {\n\tlogger.WithFields(logrus.Fields{\n\t\t\"begin\": begin,\n\t\t\"end\": end,\n\t}).Info(\"Syncer recover\")\n\n\tch, err := syncer.agent.GetMerkleWrapper(begin, end)\n\tif err != nil {\n\t\tlogger.WithFields(logrus.Fields{\n\t\t\t\"begin\": begin,\n\t\t\t\"end\": end,\n\t\t\t\"error\": err,\n\t\t}).Warn(\"get merkle wrapper\")\n\t}\n\n\tfor w := range ch {\n\t\tsyncer.handleMerkleWrapper(w)\n\t}\n}", "func Recover(IdentityFile, Password, ShareFile, ResponseFile string, verbosity int) (string, error) {\n\tvar out, pubkey []byte\n\tpubk, privk, err := ReadKey(IdentityFile, Password)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmyShares, err := ReadFile(ShareFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmyResponses, err := ReadFile(ResponseFile)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tmessagesReconstruct, err := shares.DecodeShareMessageFromList(pubk, privk, myShares)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tout = printVerbose(out, verbosity, 3, fmt.Sprintf(\"My PubKey: %s\", hex.EncodeToString(pubk)))\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"Share configuration:\"))\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"\\tSecretShare ID: %s\", hex.EncodeToString(messagesReconstruct.CommonMessageHeader.SigPubKeyHash)))\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"\\tComment: %s\", string(messagesReconstruct.CommonMessageHeader.Comment)))\n\n\tout = printVerbose(out, verbosity, 1, fmt.Sprintf(\"Adding responses:\"))\n\ti := 0\n\tfor _, s := range bytes.Split(myResponses, []byte(\"\\n\")) {\n\t\tif len(s) > 1 {\n\t\t\ti++\n\t\t\tpubkey, err = messagesReconstruct.InsertShareReplies(s, pubk, privk)\n\t\t\tif err == nil {\n\t\t\t\tout = printVerbose(out, verbosity, 1, fmt.Sprintf(\"\\tAdded response %d: %s\", i, hex.EncodeToString(pubkey)))\n\t\t\t} else {\n\t\t\t\tout = printVerbose(out, verbosity, 1, fmt.Sprintf(\"\\tResponse %d (%s) failed: %s\", i, hex.EncodeToString(pubkey), err))\n\t\t\t}\n\t\t}\n\t}\n\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"Recovery Parameters:\"))\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"\\tThreshhold: %d\", messagesReconstruct.EncryptedCommonHeader.Threshhold))\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"\\tMembers participating: %d\", len(messagesReconstruct.MemberMessages)))\n\tsharecount := 0\n\tfor _, m := range messagesReconstruct.MemberMessages {\n\t\tsharecount = sharecount + len(m.Shares)\n\t}\n\tout = printVerbose(out, verbosity, 2, fmt.Sprintf(\"\\tShares available: %d\", sharecount))\n\tsecret, err := messagesReconstruct.Combine()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tout = printVerbose(out, verbosity, 1, fmt.Sprintf(\"Recovered secret: %s\", string(secret)))\n\tif verbosity == 0 {\n\t\tout = printVerbose(out, verbosity, 0, fmt.Sprintf(\"%s\", string(secret)))\n\t}\n\treturn string(out), nil\n}", "func (kv *RaftKV) recoverFromSnapshot(snapshot []byte){\n\tkv.mu.Lock()\n\tdefer kv.mu.Unlock()\n\tif snapshot != nil{\n\t\tr := bytes.NewBuffer(snapshot)\n\t\td := gob.NewDecoder(r)\n\t\td.Decode(&kv.commited)\n\t\tkv.Log(\"recover from snapshot\\n\")\n\t\tfor k, v := range kv.commited{\n\t\t\tkv.Log(\"recover key:%s value:%s\\n\", k, v.Value)\n\t\t}\n\t}\n\tkv.Log(\"recover from snapshot\\n\")\n}", "func (e *engineImpl) VerifySeal(chain engine.ChainReader, header *block.Header) error {\n\tif chain.CurrentHeader().Number().Uint64() <= uint64(1) {\n\t\treturn nil\n\t}\n\tpublicKeys, err := ReadPublicKeysFromLastBlock(chain, header)\n\n\tif err != nil {\n\t\treturn ctxerror.New(\"[VerifySeal] Cannot retrieve publickeys from last block\").WithCause(err)\n\t}\n\tsig := header.LastCommitSignature()\n\tpayload := append(sig[:], header.LastCommitBitmap()...)\n\taggSig, mask, err := ReadSignatureBitmapByPublicKeys(payload, publicKeys)\n\tif err != nil {\n\t\treturn ctxerror.New(\n\t\t\t\"[VerifySeal] Unable to deserialize the LastCommitSignature\" +\n\t\t\t\t\" and LastCommitBitmap in Block Header\",\n\t\t).WithCause(err)\n\t}\n\tparentHash := header.ParentHash()\n\tparentHeader := chain.GetHeader(parentHash, header.Number().Uint64()-1)\n\tif chain.Config().IsStaking(parentHeader.Epoch()) {\n\t\tslotList, err := chain.ReadShardState(parentHeader.Epoch())\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"cannot decoded shard state\")\n\t\t}\n\t\td := quorum.NewDecider(quorum.SuperMajorityStake)\n\t\td.SetShardIDProvider(func() (uint32, error) {\n\t\t\treturn parentHeader.ShardID(), nil\n\t\t})\n\t\td.SetMyPublicKeyProvider(func() (*bls.PublicKey, error) {\n\t\t\treturn nil, nil\n\t\t})\n\t\td.SetVoters(slotList.FindCommitteeByID(parentHeader.ShardID()).Slots, true)\n\t\tif !d.IsQuorumAchievedByMask(mask, true) {\n\t\t\treturn ctxerror.New(\n\t\t\t\t\"[VerifySeal] Not enough voting power in LastCommitSignature from Block Header\",\n\t\t\t)\n\t\t}\n\t} else {\n\t\tparentQuorum, err := QuorumForBlock(chain, parentHeader, false)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err,\n\t\t\t\t\"cannot calculate quorum for block %s\", header.Number())\n\t\t}\n\t\tif count := utils.CountOneBits(mask.Bitmap); count < int64(parentQuorum) {\n\t\t\treturn ctxerror.New(\n\t\t\t\t\"[VerifySeal] Not enough signature in LastCommitSignature from Block Header\",\n\t\t\t\t\"need\", parentQuorum, \"got\", count,\n\t\t\t)\n\t\t}\n\t}\n\n\tblockNumHash := make([]byte, 8)\n\tbinary.LittleEndian.PutUint64(blockNumHash, header.Number().Uint64()-1)\n\tlastCommitPayload := append(blockNumHash, parentHash[:]...)\n\n\tif !aggSig.VerifyHash(mask.AggregatePublic, lastCommitPayload) {\n\t\treturn ctxerror.New(\"[VerifySeal] Unable to verify aggregated signature from last block\", \"lastBlockNum\", header.Number().Uint64()-1, \"lastBlockHash\", parentHash)\n\t}\n\treturn nil\n}", "func (c *BlockCache) recoverFromCorruption(height int) {\n\tLog.Warning(\"CORRUPTION detected in db blocks-cache files, height \", height, \" redownloading\")\n\n\t// Save the corrupted files for post-mortem analysis.\n\tsave := c.lengthsName + \"-corrupted\"\n\tif err := copyFile(c.lengthsName, save); err != nil {\n\t\tLog.Warning(\"Could not copy db lengths file: \", err)\n\t}\n\tsave = c.blocksName + \"-corrupted\"\n\tif err := copyFile(c.blocksName, save); err != nil {\n\t\tLog.Warning(\"Could not copy db lengths file: \", err)\n\t}\n\n\tc.setDbFiles(height)\n}", "func (e *recoverableError) recover() {\n}", "func CompactSigTest(sig []byte) {\n\n\tvar b int = int(sig[32])\n\tif b < 0 {\n\t\tlog.Panic()\n\t}\n\tif ((b >> 7) == 1) != ((b & 0x80) == 0x80) {\n\t\tlog.Panic(\"b= %v b2= %v \\n\", b, b>>7)\n\t}\n\tif (b & 0x80) == 0x80 {\n\t\tlog.Panic(\"b= %v b2= %v \\n\", b, b&0x80)\n\t}\n}", "func (broadcast *Broadcast) Recover(ctx context.Context, username, newResetPubKeyHex,\n\tnewTransactionPubKeyHex, newAppPubKeyHex, privKeyHex string, seq int64) (*model.BroadcastResponse, error) {\n\tresetPubKey, err := transport.GetPubKeyFromHex(newResetPubKeyHex)\n\tif err != nil {\n\t\treturn nil, errors.FailedToGetPubKeyFromHexf(\"Recover: failed to get Reset pub key\").AddCause(err)\n\t}\n\ttxPubKey, err := transport.GetPubKeyFromHex(newTransactionPubKeyHex)\n\tif err != nil {\n\t\treturn nil, errors.FailedToGetPubKeyFromHexf(\"Recover: failed to get Tx pub key\").AddCause(err)\n\t}\n\tappPubKey, err := transport.GetPubKeyFromHex(newAppPubKeyHex)\n\tif err != nil {\n\t\treturn nil, errors.FailedToGetPubKeyFromHexf(\"Recover: failed to get App pub key\").AddCause(err)\n\t}\n\n\tmsg := model.RecoverMsg{\n\t\tUsername: username,\n\t\tNewResetPubKey: resetPubKey,\n\t\tNewTransactionPubKey: txPubKey,\n\t\tNewAppPubKey: appPubKey,\n\t}\n\treturn broadcast.broadcastTransaction(ctx, msg, privKeyHex, seq, \"\", false)\n}", "func CompactSigTest(sig []byte) {\n\tvar b int = int(sig[32])\n\tif b < 0 {\n\t\tlog.Panic()\n\t}\n\tif ((b >> 7) == 1) != ((b & 0x80) == 0x80) {\n\t\tlog.Panic(\"b= %v b2= %v \\n\", b, b>>7)\n\t}\n\tif (b & 0x80) == 0x80 {\n\t\tlog.Panic(\"b= %v b2= %v \\n\", b, b&0x80)\n\t}\n}", "func verifyTransaction(inc *Transaction) {\n\tif verifySignature(inc) {\n\t\t\texecuteTransaction(inc)\n\t} else {\n\t\treturn\n\t}\n}", "func (bft *ProtocolBFTCoSi) Signature() *BFTSignature {\n\tbftSig := &BFTSignature{\n\t\tSig: bft.commit.Signature(),\n\t\tMsg: bft.Msg,\n\t\tExceptions: nil,\n\t}\n\tif bft.signRefusal {\n\t\tbftSig.Sig = nil\n\t\tbftSig.Exceptions = bft.tempExceptions\n\t}\n\n\t// This is a hack to include exceptions which are the result of offline\n\t// nodes rather than nodes that refused to sign.\n\tif bftSig.Exceptions == nil {\n\t\tfor _, ex := range bft.tempExceptions {\n\t\t\tif ex.Commitment.Equal(bft.Suite().Point().Null()) {\n\t\t\t\tbftSig.Exceptions = append(bftSig.Exceptions, ex)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn bftSig\n}", "func (d Dependency) DoRecover() (interface{}, error) {\n\tdLog.V(utils.Debug).Info(\"can not recover dependency now\", \"name\", d.Name, \"version\", d.Version)\n\treturn \"\", nil\n}", "func signatureHelper(t *testing.T, failure bool) {\n\t// Setup\n\tstop, clients, contractPath, contractFilePath := setupSignature(t)\n\tdefer stop()\n\n\tstopBefore, expectedProofFile1, expectedProofFile2 := \"1\", 0, 0\n\tif !failure {\n\t\tstopBefore, expectedProofFile1, expectedProofFile2 = \"2\", 2, 1\n\t}\n\n\t// Configure client3 to be faulty\n\tsetLastArg(clients[2], \"--stopbefore\", true)\n\tsetLastArg(clients[2], stopBefore, false)\n\tsetLastArg(clients[2], \"sign\", false)\n\n\t// Sign!\n\tcloseChannel := make(chan []byte, 3)\n\tfor i := 0; i < 3; i++ {\n\t\tsetLastArg(clients[i], \"sign\", true)\n\t\tsetLastArg(clients[i], contractPath, false)\n\t\tgo func(c *exec.Cmd, i int) {\n\t\t\tc.Stdin = strings.NewReader(contractFilePath + \"\\npassword\\nyes\\n\")\n\t\t\tc.Stderr = bufio.NewWriter(os.Stdout)\n\t\t\toutput, _ := c.Output()\n\t\t\tcloseChannel <- output\n\t\t}(clients[i], i)\n\t}\n\n\tfor i := 0; i < 3; i++ {\n\t\t// TODO check stderr?\n\t\t<-closeChannel\n\t}\n\n\tcheckProofFile(t, expectedProofFile1)\n\tfilename := checkRecoverFile(t, \"[email protected]\")\n\tcallRecover(newClient(clients[2]), filename)\n\t_ = os.Remove(filename)\n\tcheckProofFile(t, expectedProofFile2)\n\n\ttime.Sleep(time.Second)\n\treturn\n}", "func Recover() {\n\tif err := recover(); err != nil {\n\t\tconst size = 64 << 10\n\t\tbuf := make([]byte, size)\n\t\tbuf = buf[:runtime.Stack(buf, false)]\n\t\tlog.Error(\"runtime error: %v\\ntraceback:\\n%v\\n\", err, *(*string)(unsafe.Pointer(&buf)))\n\t}\n}", "func (client IdentityClient) recoverCompartment(ctx context.Context, request common.OCIRequest, binaryReqBody *common.OCIReadSeekCloser, extraHeaders map[string]string) (common.OCIResponse, error) {\n\n\thttpRequest, err := request.HTTPRequest(http.MethodPost, \"/compartments/{compartmentId}/actions/recoverCompartment\", binaryReqBody, extraHeaders)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar response RecoverCompartmentResponse\n\tvar httpResponse *http.Response\n\thttpResponse, err = client.Call(ctx, &httpRequest)\n\tdefer common.CloseBodyIfValid(httpResponse)\n\tresponse.RawResponse = httpResponse\n\tif err != nil {\n\t\treturn response, err\n\t}\n\n\terr = common.UnmarshalResponse(httpResponse, &response)\n\treturn response, err\n}", "func Recover() {\n\tdoRecover(recover())\n}", "func Recover() {\n\tdoRecover(recover(), false)\n}", "func GenerateEvidenceFile(\n\tidentity string,\n\tfileName string,\n\tevidencefilepath string,\n\tevidencenouncefile string,\n\treadbitlen int64) {\n\tvar readiter int64 = 0\n\tvar previoushash string\n\tvar tyrnum int64 = 0\n\t//fmt.Println(\"filesize is \", filesize)\n\tvar blocknum int64\n\n\tvar blockbytebuffer bytes.Buffer\n\t//var blockbyte []byte\n\tvar noncestring string\n\tif exists(evidencefilepath) {\n\n\t\tdel := os.Remove(evidencefilepath)\n\t\tif del != nil {\n\t\t\tfmt.Println(del)\n\t\t}\n\t}\n\n\tif exists(evidencenouncefile) {\n\n\t\tdel := os.Remove(evidencenouncefile)\n\t\tif del != nil {\n\t\t\tfmt.Println(del)\n\t\t}\n\t}\n\n\tfilesize := GetFileSize(fileName)\n\tif (filesize * 8 / readbitlen) > 0 {\n\t\tblocknum = (filesize*8/readbitlen + 1)\n\t} else {\n\t\tblocknum = (filesize * 8 / readbitlen)\n\t}\n\tfmt.Println(\"blocknum is \", blocknum)\n\t//filename := getFileName(fileName)\n\tfor readiter = 0; readiter < blocknum; readiter++ {\n\t\t//fmt.Println(\"readiter is \", readiter)\n\t\tretdata, _ := ReadBlock(fileName, readbitlen, readiter*readbitlen)\n\t\t//fmt.Println(\"retdata is \", retdata)\n\t\tif 0 == readiter {\n\t\t\tfor tyrnum = 0; ; tyrnum++ {\n\t\t\t\tvar trys string\n\t\t\t\ttrys += identity\n\t\t\t\ttrys += strconv.FormatInt(tyrnum, 10)\n\t\t\t\t//fmt.Println(\"trys is \",trys)\n\t\t\t\t//t1:=time.Now()\n\t\t\t\tcalc_hash := GetSHA256HashCode([]byte(trys))\n\t\t\t\t//t2:=time.Now()\n\t\t\t\t//d:=t2.Sub(t1)\n\t\t\t\t//fmt.Println(\"calc_hash is \",calc_hash)\n\t\t\t\tvar comparebyte []byte\n\t\t\t\tcomparebyte, _ = hex.DecodeString(calc_hash)\n\t\t\t\tret, _ := bitcompare(retdata, comparebyte, readbitlen)\n\t\t\t\tif ret {\n\t\t\t\t\t//fmt.Println(\"calc_hash is \", calc_hash)\n\t\t\t\t\t//fmt.Println(\"retdata is \", retdata)\n\t\t\t\t\t//fmt.Println(\"comparebyte is \", comparebyte)\n\t\t\t\t\t//fmt.Println(\"tyrnum is \", tyrnum)\n\n\t\t\t\t\tprevioushash = calc_hash\n\t\t\t\t\t//blockbyte = blockbyte + comparebyte\n\t\t\t\t\tblockbytebuffer.Write(comparebyte)\n\t\t\t\t\tnoncestring += strconv.FormatInt(tyrnum, 10)\n\n\t\t\t\t\t//WriteBlock(evidencefilepath, comparebyte)\n\t\t\t\t\t//WriteNounce(evidencenouncefile, strconv.FormatInt(tyrnum, 10))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tfor tyrnum = 0; ; tyrnum++ {\n\t\t\t\tvar trys string\n\t\t\t\ttrys += identity\n\t\t\t\ttrys += previoushash\n\t\t\t\ttrys += strconv.FormatInt(tyrnum, 10)\n\t\t\t\t//fmt.Println(\"trys is \",trys)\n\t\t\t\tcalc_hash := GetSHA256HashCode([]byte(trys))\n\t\t\t\t//fmt.Println(\"calc_hash is \",calc_hash)\n\t\t\t\tvar comparebyte []byte\n\t\t\t\tcomparebyte, _ = hex.DecodeString(calc_hash)\n\t\t\t\tret, _ := bitcompare(retdata, comparebyte, readbitlen)\n\t\t\t\tif ret {\n\t\t\t\t\t//fmt.Println(\"trys is \",trys)\n\t\t\t\t\t//fmt.Println(\"tyrnum is \", tyrnum)\n\t\t\t\t\t//fmt.Println(\"retdata is \", retdata)\n\t\t\t\t\t//fmt.Println(\"comparebyte is \", comparebyte)\n\t\t\t\t\tprevioushash = calc_hash\n\t\t\t\t\tblockbytebuffer.Write(comparebyte)\n\t\t\t\t\tnoncestring += \",\"+strconv.FormatInt(tyrnum, 10)\n\n\t\t\t\t\t//WriteBlock(evidencefilepath, comparebyte)\n\t\t\t\t\t//WriteNounce(evidencenouncefile, \",\"+strconv.FormatInt(tyrnum, 10))\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tWriteBlock(evidencefilepath, blockbytebuffer.Bytes() )\n\tWriteNounce(evidencenouncefile, noncestring)\n\n\n}", "func (b SignDetail) Digest() (common.Hash, error) {\n\tvar hash common.Hash\n\tvar signFormatData apitypes.TypedData\n\tif err := json.Unmarshal([]byte(b.SignSchema.Schema), &signFormatData); err != nil {\n\t\treturn hash, err\n\t}\n\tparams, err := b.GetContractParams()\n\tif err != nil {\n\t\treturn hash, err\n\t}\n\tdata, err := buildTypedData(signFormatData, params)\n\n\tif err != nil {\n\t\treturn hash, err\n\t}\n\thash, err = crypto2.Keccak256HashEIP712(data)\n\treturn hash, err\n}", "func (a *API) Recover(w http.ResponseWriter, r *http.Request) error {\n\tctx := r.Context()\n\tconfig := a.getConfig(ctx)\n\tinstanceID := getInstanceID(ctx)\n\tparams := &RecoverParams{}\n\tjsonDecoder := json.NewDecoder(r.Body)\n\terr := jsonDecoder.Decode(params)\n\tif err != nil {\n\t\treturn badRequestError(\"Could not read verification params: %v\", err)\n\t}\n\n\tif params.Email == \"\" {\n\t\treturn unprocessableEntityError(\"Password recovery requires an email\")\n\t}\n\n\taud := a.requestAud(ctx, r)\n\tuser, err := models.FindUserByEmailAndAudience(a.db, instanceID, params.Email, aud)\n\tif err != nil {\n\t\tif models.IsNotFoundError(err) {\n\t\t\treturn notFoundError(err.Error())\n\t\t}\n\t\treturn internalServerError(\"Database error finding user\").WithInternalError(err)\n\t}\n\n\terr = a.db.Transaction(func(tx *storage.Connection) error {\n\t\tif terr := models.NewAuditLogEntry(tx, instanceID, user, models.UserRecoveryRequestedAction, nil); terr != nil {\n\t\t\treturn terr\n\t\t}\n\n\t\tmailer := a.Mailer(ctx)\n\t\treferrer := a.getReferrer(r)\n\t\treturn a.sendPasswordRecovery(tx, user, mailer, config.SMTP.MaxFrequency, referrer)\n\t})\n\tif err != nil {\n\t\treturn internalServerError(\"Error recovering user\").WithInternalError(err)\n\t}\n\n\treturn sendJSON(w, http.StatusOK, &map[string]string{})\n}", "func (lf *logFile) recover() error {\n\terr := lf.scan(0, func(vp valuePointer, r *Record) error {\n\t\t// save ts in header to avoid this?\n\t\tb := new(pb.Binlog)\n\t\terr := b.Unmarshal(r.payload)\n\t\tif err != nil {\n\t\t\treturn errors.Trace(err)\n\t\t}\n\n\t\tif b.CommitTs > lf.maxTS {\n\t\t\tlf.maxTS = b.CommitTs\n\t\t}\n\n\t\tif b.StartTs > lf.maxTS {\n\t\t\tlf.maxTS = b.StartTs\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn errors.Trace(err)\n}", "func TestEncodeFile4_NoCompression(t *testing.T) {\n\t// Open file\n\tfile, err := os.Open(\"tests/kdbx4/example-nocompression.kdbx\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open keepass file: %s\", err)\n\t}\n\tdefer file.Close()\n\n\t// Decode database\n\tdb := NewDatabase()\n\tdb.Credentials = NewPasswordCredentials(\"abcdefg12345678\")\n\terr = NewDecoder(file).Decode(db)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to decode file: %s\", err)\n\t}\n\n\t// Unlock entries\n\terr = db.UnlockProtectedEntries()\n\tif err != nil {\n\t\tt.Fatalf(\"Problem unlocking entries. %s\", err)\n\t}\n\n\t//\n\t// Test encode system on opened database\n\t//\n\tf, err := os.Create(\"tests/kdbx4/tmp.kdbx\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open file for writing: %s\", err)\n\t}\n\n\t// Change the value of an entry element to see if the change stays after decoding\n\tdb.Content.Root.Groups[0].Groups[0].Entries[0].Get(\"URL\").Value.Content = \"http://github.com\"\n\n\t// Lock entries\n\terr = db.LockProtectedEntries()\n\tif err != nil {\n\t\tt.Fatalf(\"Problem locking entries. %s\", err)\n\t}\n\n\t// Test encoding\n\tenc := NewEncoder(f)\n\terr = enc.Encode(db)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to encode file: %s\", err)\n\t}\n\n\t// Open the new database\n\ttmpfile, err := os.Open(\"tests/kdbx4/tmp.kdbx\")\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to open keepass file: %s\", err)\n\t}\n\tdefer tmpfile.Close()\n\n\t// Decode the new database\n\tdb = NewDatabase()\n\tdb.Credentials = NewPasswordCredentials(\"abcdefg12345678\")\n\terr = NewDecoder(tmpfile).Decode(db)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to decode temporary file: %s\", err)\n\t}\n\n\t// Unlock entries\n\terr = db.UnlockProtectedEntries()\n\tif err != nil {\n\t\tt.Fatalf(\"Problem unlocking entries. %s\", err)\n\t}\n\n\t// Test password matching\n\tpw := db.Content.Root.Groups[0].Groups[0].Entries[0].GetPassword()\n\tif pw != \"Password\" {\n\t\tt.Fatalf(\n\t\t\t\"Failed to decode password: should be 'Password' not '%s'\",\n\t\t\tpw,\n\t\t)\n\t}\n\n\t// Test new value matching\n\turl := db.Content.Root.Groups[0].Groups[0].Entries[0].GetContent(\"URL\")\n\tif url != \"http://github.com\" {\n\t\tt.Fatalf(\n\t\t\t\"Failed to decode url: should be 'http://github.com' not '%s'\",\n\t\t\turl,\n\t\t)\n\t}\n}", "func TestInvalidSignatureVerify(t *testing.T) {\n\tfor _, tt := range fileTests {\n\t\tcapset, err := NewCapSet()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tm, err := NewMutableFile(capset, \"/tmp\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t_, err = m.Write(tt.contents)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer os.Remove(path.Join(m.storageDir, m.filename))\n\n\t\tok, err := m.Verify()\n\t\tif !ok || err != nil {\n\t\t\tt.Errorf(\"could not verify correct signature, %s\", err)\n\t\t}\n\n\t\thandle, err := os.OpenFile(path.Join(m.storageDir, m.filename),\n\t\t\tos.O_RDWR, 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not open file: %s\", err)\n\t\t}\n\t\tfileInfo, _ := handle.Stat()\n\t\tgarbage := []byte{0xBA, 0xAD, 0xC0, 0xDE}\n\t\t_, err = handle.WriteAt(garbage, fileInfo.Size()-4)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\thandle.Close()\n\n\t\tok, err = m.Verify()\n\t\tif ok || err == nil {\n\t\t\tt.Fatal(\"verified bad signature!\")\n\t\t}\n\t}\n}", "func bytesToRecover(chunkFetchOffset, chunkFetchLength, chunkSize uint64, rs modules.ErasureCoder) uint64 {\n\t// If partialDecoding is not available we downloaded the whole sector and\n\t// recovered the whole chunk.\n\tif !rs.SupportsPartialEncoding() {\n\t\treturn chunkSize\n\t}\n\t// Else we need to calculate how much data we need to recover.\n\trecoveredSegmentSize := uint64(rs.MinPieces() * crypto.SegmentSize)\n\t_, numSegments := segmentsForRecovery(chunkFetchOffset, chunkFetchLength, rs)\n\treturn numSegments * recoveredSegmentSize\n\n}", "func (cp *Compactor) Compact(ctx context.Context, opts *brtypes.CompactOptions) (*brtypes.Snapshot, error) {\n\tcp.logger.Info(\"Start compacting\")\n\n\t// Deepcopy restoration options ro to avoid any mutation of the passing object\n\tcompactorRestoreOptions := opts.RestoreOptions.DeepCopy()\n\n\t// If no base snapshot is found, abort compaction as there would be nothing to compact\n\tif compactorRestoreOptions.BaseSnapshot == nil {\n\t\tcp.logger.Error(\"No base snapshot found. Nothing is available for compaction\")\n\t\treturn nil, fmt.Errorf(\"no base snapshot found. Nothing is available for compaction\")\n\t}\n\n\tcp.logger.Infof(\"Creating temporary etcd directory %s for restoration.\", compactorRestoreOptions.Config.DataDir)\n\terr := os.MkdirAll(compactorRestoreOptions.Config.DataDir, 0700)\n\tif err != nil {\n\t\tcp.logger.Errorf(\"Unable to create temporary etcd directory for compaction: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\tdefer func() {\n\t\tif err := os.RemoveAll(compactorRestoreOptions.Config.DataDir); err != nil {\n\t\t\tcp.logger.Errorf(\"Failed to remove temporary etcd directory %s: %v\", compactorRestoreOptions.Config.DataDir, err)\n\t\t}\n\t}()\n\n\t// Then restore from the snapshots\n\tr := restorer.NewRestorer(cp.store, cp.logger)\n\tembeddedEtcd, err := r.Restore(*compactorRestoreOptions, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to restore snapshots during compaction: %v\", err)\n\t}\n\n\tcp.logger.Info(\"Restoration for compaction is done.\")\n\t// There is a possibility that restore operation may not start an embedded ETCD.\n\tif embeddedEtcd == nil {\n\t\tembeddedEtcd, err = miscellaneous.StartEmbeddedEtcd(cp.logger, compactorRestoreOptions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tdefer func() {\n\t\tembeddedEtcd.Server.Stop()\n\t\tembeddedEtcd.Close()\n\t}()\n\n\tep := []string{embeddedEtcd.Clients[0].Addr().String()}\n\n\t// Then compact ETCD\n\n\t// Build Client\n\tclientFactory := etcdutil.NewClientFactory(compactorRestoreOptions.NewClientFactory, brtypes.EtcdConnectionConfig{\n\t\tMaxCallSendMsgSize: compactorRestoreOptions.Config.MaxCallSendMsgSize,\n\t\tEndpoints: ep,\n\t\tInsecureTransport: true,\n\t})\n\tclientKV, err := clientFactory.NewKV()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build etcd KV client\")\n\t}\n\tdefer clientKV.Close()\n\n\tclientMaintenance, err := clientFactory.NewMaintenance()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build etcd maintenance client\")\n\t}\n\tdefer clientMaintenance.Close()\n\n\trevCheckCtx, cancel := context.WithTimeout(ctx, etcdDialTimeout)\n\tgetResponse, err := clientKV.Get(revCheckCtx, \"foo\")\n\tcancel()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to connect to etcd KV client: %v\", err)\n\t}\n\tetcdRevision := getResponse.Header.GetRevision()\n\n\t// Compact\n\t// Please refer below issue for why physical compaction was necessary\n\t// https://github.com/gardener/etcd-backup-restore/issues/451\n\tif _, err := clientKV.Compact(ctx, etcdRevision, clientv3.WithCompactPhysical()); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to compact: %v\", err)\n\t}\n\n\t// Then defrag ETCD\n\tif opts.NeedDefragmentation {\n\t\tclient, err := clientFactory.NewCluster()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build etcd cluster client\")\n\t\t}\n\t\tdefer client.Close()\n\n\t\terr = etcdutil.DefragmentData(ctx, clientMaintenance, client, ep, opts.DefragTimeout.Duration, cp.logger)\n\t\tif err != nil {\n\t\t\tcp.logger.Errorf(\"failed to defragment: %v\", err)\n\t\t}\n\t}\n\n\t// Then take snapshot of ETCD\n\tsnapshotReqCtx, cancel := context.WithTimeout(ctx, opts.SnapshotTimeout.Duration)\n\tdefer cancel()\n\n\t// Determine suffix of compacted snapshot that will be result of this compaction\n\tsuffix := compactorRestoreOptions.BaseSnapshot.CompressionSuffix\n\tif len(compactorRestoreOptions.DeltaSnapList) > 0 {\n\t\tsuffix = compactorRestoreOptions.DeltaSnapList[compactorRestoreOptions.DeltaSnapList.Len()-1].CompressionSuffix\n\t}\n\n\tisCompressed, compressionPolicy, err := compressor.IsSnapshotCompressed(suffix)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to determine if snapshot is compressed: %v\", compactorRestoreOptions.BaseSnapshot.CompressionSuffix)\n\t}\n\n\tisFinal := compactorRestoreOptions.BaseSnapshot.IsFinal\n\n\tcc := &compressor.CompressionConfig{Enabled: isCompressed, CompressionPolicy: compressionPolicy}\n\tsnapshot, err := etcdutil.TakeAndSaveFullSnapshot(snapshotReqCtx, clientMaintenance, cp.store, etcdRevision, cc, suffix, isFinal, cp.logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Update snapshot lease only if lease update flag is enabled\n\tif opts.EnabledLeaseRenewal {\n\t\t// Update revisions in holder identity of full snapshot lease.\n\t\tctx, cancel := context.WithTimeout(ctx, brtypes.LeaseUpdateTimeoutDuration)\n\t\tif err := heartbeat.FullSnapshotCaseLeaseUpdate(ctx, cp.logger, snapshot, cp.k8sClientset, opts.FullSnapshotLeaseName, opts.DeltaSnapshotLeaseName); err != nil {\n\t\t\tcp.logger.Warnf(\"Snapshot lease update failed : %v\", err)\n\t\t}\n\t\tcancel()\n\t}\n\n\treturn snapshot, nil\n}", "func (mgr *DataCheckMgr) doRecover() {\n\n\tnow := time.Now().Unix()\n\tblog.Info(\"data checker: doRecover begin.... now(%d)\", now)\n\tdefer func() {\n\t\tnow = time.Now().Unix()\n\t\tblog.Info(\"data checker: doRecover end.... now(%d)\", now)\n\t}()\n\n\trunAses, err := mgr.store.ListRunAs()\n\tif err != nil {\n\t\tblog.Error(\"data checker: fail to list runAses, err:%s\", err.Error())\n\t\treturn\n\t}\n\n\tfor _, runAs := range runAses {\n\t\tappIDs, err := mgr.store.ListApplicationNodes(runAs)\n\t\tif err != nil {\n\t\t\tblog.Error(\"data checker: fail to list %s, err:%s\", runAs, err.Error())\n\t\t\tcontinue\n\t\t}\n\t\tif nil == appIDs {\n\t\t\tblog.Warn(\"data checker: no application nodes under runAs:%s\", runAs)\n\t\t\tcontinue\n\t\t}\n\t\tfor _, appID := range appIDs {\n\t\t\tblog.Info(\"data checker: to recover application:%s.%s \", runAs, appID)\n\t\t\tmgr.recoverTaskgroup(runAs, appID)\n\t\t}\n\t}\n\n\treturn\n}", "func (e Des3CbcSha1Kd) VerifyIntegrity(protocolKey, ct, pt []byte, usage uint32) bool {\n\treturn rfc3961.VerifyIntegrity(protocolKey, ct, pt, usage, e)\n}", "func VerifyFile(reader io.Reader, logger *log.Logger) (err error) {\n\trrZone, _, err := readAndParseZone(reader, false)\n\tif err != nil {\n\t\treturn\n\t}\n\trrSets := rrZone.CreateRRSet(true)\n\n\trrSigTuples := make(map[string]*RRSigTuple)\n\n\tvar pzsk, pksk *dns.DNSKEY\n\n\t// Pairing each RRSet with its RRSig\n\tfor _, set := range rrSets {\n\t\tif len(set) > 0 {\n\t\t\tif set[0].Header().Rrtype == dns.TypeDNSKEY {\n\t\t\t\tkey1 := set[0].(*dns.DNSKEY)\n\t\t\t\tkey2 := set[1].(*dns.DNSKEY)\n\t\t\t\tif key1.Flags == 256 {\n\t\t\t\t\tpzsk = key1\n\t\t\t\t\tpksk = key2\n\t\t\t\t} else if key1.Flags == 257 {\n\t\t\t\t\tpzsk = key2\n\t\t\t\t\tpksk = key1\n\t\t\t\t}\n\t\t\t}\n\t\t\tfirstRR := set[0]\n\t\t\tvar setHash string\n\t\t\tif firstRR.Header().Rrtype == dns.TypeRRSIG {\n\t\t\t\tfor _, preSig := range set {\n\t\t\t\t\tsig := preSig.(*dns.RRSIG)\n\t\t\t\t\tsetHash = fmt.Sprintf(\"%s#%s#%s\", sig.Header().Name, dns.Class(sig.Header().Class), dns.Type(sig.TypeCovered))\n\t\t\t\t\ttuple, ok := rrSigTuples[setHash]\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\ttuple = &RRSigTuple{}\n\t\t\t\t\t\trrSigTuples[setHash] = tuple\n\t\t\t\t\t}\n\t\t\t\t\ttuple.RRSig = sig\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tsetHash = fmt.Sprintf(\"%s#%s#%s\", firstRR.Header().Name, dns.Class(firstRR.Header().Class), dns.Type(firstRR.Header().Rrtype))\n\t\t\t\ttuple, ok := rrSigTuples[setHash]\n\t\t\t\tif !ok {\n\t\t\t\t\ttuple = &RRSigTuple{}\n\t\t\t\t\trrSigTuples[setHash] = tuple\n\t\t\t\t}\n\t\t\t\ttuple.RRSet = set\n\t\t\t}\n\t\t}\n\t}\n\n\tif pzsk == nil || pksk == nil {\n\t\terr = fmt.Errorf(\"couldn't find dnskeys\")\n\t\treturn err\n\t}\n\n\t// Checking each RRset RRSignature.\n\tfor setName, tuple := range rrSigTuples {\n\t\tsig := tuple.RRSig\n\t\tset := tuple.RRSet\n\t\tif len(set) == 0 {\n\t\t\terr = fmt.Errorf(\"the RRSet %s has no elements\", setName)\n\t\t\treturn\n\t\t}\n\t\tif sig == nil {\n\t\t\terr = fmt.Errorf(\"the RRSet %s does not have a Signature\", setName)\n\t\t}\n\t\tif set == nil {\n\t\t\terr = fmt.Errorf(\"the Signature %s does not have a RRSet\", setName)\n\t\t}\n\t\texpDate := time.Unix(int64(sig.Expiration), 0)\n\t\tif expDate.Before(time.Now()) {\n\t\t\terr = fmt.Errorf(\n\t\t\t\t\"the Signature for RRSet %s has already expired. Expiration date: %s\",\n\t\t\t\tsetName,\n\t\t\t\texpDate.Format(\"2006-01-02 15:04:05\"),\n\t\t\t)\n\t\t\tlogger.Printf(\"%s\\n\", err)\n\t\t\treturn\n\t\t}\n\t\tif set[0].Header().Rrtype == dns.TypeDNSKEY {\n\t\t\terr = sig.Verify(pksk, set)\n\t\t} else {\n\t\t\terr = sig.Verify(pzsk, set)\n\t\t}\n\t\tif err != nil {\n\t\t\tlogger.Printf(\"[Error] (%s) %s \\n\", err, setName)\n\t\t} else {\n\t\t\tlogger.Printf(\"[ OK ] %s\\n\", setName)\n\t\t}\n\t}\n\treturn\n}", "func panicRecover(input *models.RunningInput) {\n\tif err := recover(); err != nil {\n\t\ttrace := make([]byte, 2048)\n\t\truntime.Stack(trace, true)\n\t\tlog.Printf(\"E! FATAL: [%s] panicked: %s, Stack:\\n%s\",\n\t\t\tinput.LogName(), err, trace)\n\t\tlog.Println(\"E! PLEASE REPORT THIS PANIC ON GITHUB with \" +\n\t\t\t\"stack trace, configuration, and OS information: \" +\n\t\t\t\"https://github.com/influxdata/telegraf/issues/new/choose\")\n\t}\n}", "func RecoverKey(constr *chow.Construction) []byte {\n\tround1, round2 := round{\n\t\tconstruction: constr,\n\t\tround: 1,\n\t}, round{\n\t\tconstruction: constr,\n\t\tround: 2,\n\t}\n\n\t// Decomposition Phase\n\tconstr1 := aspn.DecomposeSPN(round1, cspn.SAS)\n\tconstr2 := aspn.DecomposeSPN(round2, cspn.SAS)\n\n\tvar (\n\t\tleading, middle, trailing sboxLayer\n\t\tleft, right = affineLayer(constr1[1].(encoding.BlockAffine)), affineLayer(constr2[1].(encoding.BlockAffine))\n\t)\n\n\tfor pos := 0; pos < 16; pos++ {\n\t\tleading[pos] = constr1[0].(encoding.ConcatenatedBlock)[pos]\n\t\tmiddle[pos] = encoding.ComposedBytes{\n\t\t\tconstr1[2].(encoding.ConcatenatedBlock)[pos],\n\t\t\tconstr2[0].(encoding.ConcatenatedBlock)[common.ShiftRows(pos)],\n\t\t}\n\t\ttrailing[pos] = constr2[2].(encoding.ConcatenatedBlock)[pos]\n\t}\n\n\t// Disambiguation Phase\n\t// Disambiguate the affine layer.\n\tlin, lout := left.clean()\n\trin, rout := right.clean()\n\n\tleading.rightCompose(lin, common.NoShift)\n\tmiddle.leftCompose(lout, common.NoShift).rightCompose(rin, common.ShiftRows)\n\ttrailing.leftCompose(rout, common.NoShift)\n\n\t// The SPN decomposition naturally leaves the affine layers without a constant part.\n\t// We would push it into the S-boxes here if that wasn't the case.\n\n\t// Move the constant off of the input and output of the S-boxes.\n\tmcin, mcout := middle.cleanConstant()\n\tmcin, mcout = left.Decode(mcin), right.Encode(mcout)\n\n\tleading.rightCompose(encoding.DecomposeConcatenatedBlock(encoding.BlockAdditive(mcin)), common.NoShift)\n\ttrailing.leftCompose(encoding.DecomposeConcatenatedBlock(encoding.BlockAdditive(mcout)), common.NoShift)\n\n\t// Move the multiplication off of the input and output of the middle S-boxes.\n\tmlin, mlout := middle.cleanLinear()\n\n\tleading.rightCompose(mlin, common.NoShift)\n\ttrailing.leftCompose(mlout, common.NoShift)\n\n\t// fmt.Println(encoding.ProbablyEquivalentBlocks(\n\t// \tencoding.ComposedBlocks{aspn.Encoding{round1}, ShiftRows{}, aspn.Encoding{round2}},\n\t// \tencoding.ComposedBlocks{leading, left, middle, ShiftRows{}, right, trailing},\n\t// ))\n\t// Output: true\n\n\t// Extract the key from the leading S-boxes.\n\tkey := [16]byte{}\n\n\tfor pos := 0; pos < 16; pos++ {\n\t\tfor guess := 0; guess < 256; guess++ {\n\t\t\tcand := encoding.ComposedBytes{\n\t\t\t\tleading[pos], encoding.ByteAdditive(guess), encoding.InverseByte{sbox{}},\n\t\t\t}\n\n\t\t\tif isAS(cand) {\n\t\t\t\tkey[pos] = byte(guess)\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\tkey = left.Encode(key)\n\n\treturn backOneRound(backOneRound(key[:], 2), 1)\n}", "func tcRecoverFP(n *ir.CallExpr) ir.Node {\n\tif len(n.Args) != 1 {\n\t\tbase.FatalfAt(n.Pos(), \"wrong number of arguments: %v\", n)\n\t}\n\n\tn.Args[0] = Expr(n.Args[0])\n\tif !n.Args[0].Type().IsPtrShaped() {\n\t\tbase.FatalfAt(n.Pos(), \"%L is not pointer shaped\", n.Args[0])\n\t}\n\n\tn.SetType(types.Types[types.TINTER])\n\treturn n\n}", "func (signedFlavor *SignedFlavor) Verify(publicKey *rsa.PublicKey) error {\n\n\tif len(signedFlavor.Signature) == 0 {\n\t\treturn errors.New(\"Could not verify the signed flavor: The signed flavor that does not have a signature\")\n\t}\n\n\tsignatureBytes, err := base64.StdEncoding.DecodeString(signedFlavor.Signature)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not verify the signed flavor: An error occurred attempting to decode the signed flavor's signature\")\n\t}\n\n\tflavorDigest, err := signedFlavor.Flavor.getFlavorDigest()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not verify the signed flavor: An error occurred collecting the flavor digest\")\n\t}\n\n\terr = rsa.VerifyPKCS1v15(publicKey, crypto.SHA384, flavorDigest, signatureBytes)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Could not verify the signed flavor: PKCS1 verification failed\")\n\t}\n\n\treturn nil\n}", "func dcrm_sign(msgprex string,txhash string,save string,dcrmpkx *big.Int,dcrmpky *big.Int,cointype string,ch chan interface{}) string {\n\n if strings.EqualFold(cointype,\"EOS\") == true {\n\t\n\tvar eosstr string\n\tfor k,v := range LdbPubKeyData {\n\t key := string(k)\n\t value := string(v)\n\t if strings.EqualFold(key,string([]byte(\"eossettings\"))) {\n\t\teosstr = value\n\t\tbreak\n\t }\n\t}\n\t///////\n\tif eosstr == \"\" {\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:get eos setting data from db fail\",Err:fmt.Errorf(\"get save date fail.\")}\n\t ch <- res\n\t return \"\"\n\t}\n\n\t// Retrieve eospubkey\n\teosstrs := strings.Split(string(eosstr),\":\")\n\tfmt.Println(\"======== get eos settings,eosstr = %s ========\",eosstr)\n\tif len(eosstrs) != 5 {\n\t var ret2 Err\n\t ret2.Info = \"get eos settings error: \"+string(eosstr)\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:eos setting data error\",Err:ret2}\n\t ch <- res\n\t return \"\"\n\t}\n\tpubhex := eosstrs[3]\n\tdcrmpks, _ := hex.DecodeString(pubhex)\n\tdcrmpkx2,dcrmpky2 := secp256k1.S256().Unmarshal(dcrmpks[:])\n\t//dcrmaddr := pubhex\n\tfmt.Println(\"======== dcrm_sign eos,pkx = %+v,pky = %+v,==========\",dcrmpkx2,dcrmpky2)\n\ttxhashs := []rune(txhash)\n\tif string(txhashs[0:2]) == \"0x\" {\n\t txhash = string(txhashs[2:])\n\t}\n\n\tw,err := FindWorker(msgprex)\n\tif w == nil || err != nil {\n\t logs.Debug(\"===========get worker fail.=============\")\n\t res := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:no find worker\",Err:GetRetErr(ErrNoFindWorker)}\n\t ch <- res\n\t return \"\"\n\t}\n\tid := w.id\n\n\tvar ch1 = make(chan interface{}, 1)\n\tvar flag = false\n\tvar ret string\n\tvar tip string\n\tvar bak_sig string\n\t//25-->1\n\tfor i := 0; i < 1; i++ {\n\t\tbak_sig = Sign_ec2(msgprex,save,txhash,cointype,dcrmpkx2,dcrmpky2,ch1,id)\n\t\tret,tip,_ = GetChannelValue(ch_t,ch1)\n\t\t//if ret != \"\" && eos.IsCanonical([]byte(ret)) == true \n\t\tif ret == \"\" {\n\t\t\tw := workers[id]\n\t\t\tw.Clear2()\n\t\t\tcontinue\n\t\t}\n\t\tb, _ := hex.DecodeString(ret)\n\t\tif eos.IsCanonical(b) == true {\n\t\t\tflag = true\n\t\t\tbreak\n\t\t}\n\t\tw := workers[id]\n\t\tw.Clear2()\n\t}\n\tif flag == false {\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:eos dcrm sign fail\",Err:GetRetErr(ErrDcrmSigFail)}\n\t\tch <- res\n\t\treturn \"\"\n\t}\n\n\tres := RpcDcrmRes{Ret:ret,Tip:tip,Err:nil}\n\tch <- res\n\treturn bak_sig\n }\n \n /////////////\n txhashs := []rune(txhash)\n if string(txhashs[0:2]) == \"0x\" {\n\ttxhash = string(txhashs[2:])\n }\n\n w,err := FindWorker(msgprex)\n if w == nil || err != nil {\n\tfmt.Println(\"===========get worker fail.=============\")\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:no find worker\",Err:fmt.Errorf(\"no find worker.\")}\n\tch <- res\n\treturn \"\"\n }\n id := w.id\n\n GetEnodesInfo(w.groupid) \n \n if int32(Enode_cnts) != int32(NodeCnt) {\n\tfmt.Println(\"============the net group is not ready.please try again.================\")\n\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:the group is not ready\",Err:fmt.Errorf(\"group not ready.\")}\n\tch <- res\n\treturn \"\"\n }\n\n fmt.Println(\"===================!!!Start!!!====================\")\n\n ///////\n if strings.EqualFold(cointype,\"EVT1\") == true {\n\tlogs.Debug(\"======== dcrm_sign ready to call Sign_ec2\",\"msgprex\",msgprex,\"save\",save,\"txhash\",txhash,\"cointype\",cointype,\"pkx\",dcrmpkx,\"pky\",dcrmpky,\"id\",id)\n\tlogs.Debug(\"!!! token type is EVT1 !!!\")\n\tvar ch1 = make(chan interface{}, 1)\n\tvar flag = false\n\tvar ret string\n\tvar tip string\n\tvar cherr error\n\tvar bak_sig string\n\t//25-->1\n\tfor i := 0; i < 1; i++ {\n\t\tbak_sig = Sign_ec2(msgprex,save,txhash,cointype,dcrmpkx,dcrmpky,ch1,id)\n\t\tret, tip,cherr = GetChannelValue(ch_t,ch1)\n\t\tif cherr != nil {\n\t\t\tlogs.Debug(\"======== dcrm_sign evt\",\"cherr\",cherr)\n\t\t\ttime.Sleep(time.Duration(1)*time.Second) //1000 == 1s\n\t\t\tw := workers[id]\n\t\t\tw.Clear2()\n\t\t\tcontinue\n\t\t}\n\t\tlogs.Debug(\"======== dcrm_sign evt\",\"signature\",ret,\"\",\"========\")\n\t\t//if ret != \"\" && eos.IsCanonical([]byte(ret)) == true \n\t\tif ret == \"\" {\n\t\t\tw := workers[id]\n\t\t\tw.Clear2()\n\t\t\tcontinue\n\t\t}\n\t\tb, _ := hex.DecodeString(ret)\n\t\tif eos.IsCanonical(b) == true {\n\t\t\tfmt.Printf(\"\\nret is a canonical signature\\n\")\n\t\t\tflag = true\n\t\t\tbreak\n\t\t}\n\t\tw := workers[id]\n\t\tw.Clear2()\n\t}\n\tlogs.Debug(\"======== dcrm_sign evt\",\"got rsv flag\",flag,\"ret\",ret,\"\",\"========\")\n\tif flag == false {\n\t\tres := RpcDcrmRes{Ret:\"\",Tip:\"dcrm back-end internal error:dcrm sign fail\",Err:GetRetErr(ErrDcrmSigFail)}\n\t\tch <- res\n\t\treturn \"\"\n\t}\n\t//ch <- ret\n\tres := RpcDcrmRes{Ret:ret,Tip:tip,Err:cherr}\n\tch <- res\n\treturn bak_sig\n } else {\n\tbak_sig := Sign_ec2(msgprex,save,txhash,cointype,dcrmpkx,dcrmpky,ch,id)\n\treturn bak_sig\n }\n\n return \"\"\n}", "func Test_VerifySigFromTass(t *testing.T) {\n\trequire := require.New(t)\n\n\t//c := &sm2.Driver{}\n\n\txBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000FD4241057FEC6CBEEC501F7E1763751B8F6DFCFB910FB634FBB76A16639EF172\")\n\tyBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000001C6DA89F9C1A5EE9B6108E5A2A5FE336962630A34DBA1AF428451E1CE63BB3CF\")\n\tx := new(big.Int).SetBytes(xBytes)\n\ty := new(big.Int).SetBytes(yBytes)\n\n\tpublicKey := &gmsm_sm2.PublicKey{\n\t\tX: x,\n\t\tY: y,\n\t}\n\tvar pubSM2 sm2.PubKeySM2\n\tcopy(pubSM2[:], gmsm_sm2.Compress(publicKey))\n\n\trBytes := common.FromHex(\"00000000000000000000000000000000000000000000000000000000000000003AA29337E7149047FB8AE83F30AA00125E23173C88F284ADDED2E5B59ACAA5B9\")\n\tsBytes := common.FromHex(\"0000000000000000000000000000000000000000000000000000000000000000E2E9338109D74269578216039FD4D1C764E7F6F142CBB2E3035E7E49D375D330\")\n\tr := new(big.Int).SetBytes(rBytes)\n\ts := new(big.Int).SetBytes(sBytes)\n\n\tsignature := sm2.SignatureSM2(sm2.Serialize(r, s))\n\n\tmsg := []byte(\"112233445566112233445566112233445566112233445566\")\n\tok := pubSM2.VerifyBytes(msg, signature)\n\trequire.Equal(true, ok)\n}", "func recoverEthSig(R, S, Vb *big.Int, sigHash ethcmn.Hash) (ethcmn.Address, error) {\n\tif Vb.BitLen() > 8 {\n\t\treturn ethcmn.Address{}, errors.New(\"invalid signature\")\n\t}\n\n\tV := byte(Vb.Uint64() - 27)\n\tif !ethcrypto.ValidateSignatureValues(V, R, S, true) {\n\t\treturn ethcmn.Address{}, errors.New(\"invalid signature\")\n\t}\n\n\t// encode the signature in uncompressed format\n\tr, s := R.Bytes(), S.Bytes()\n\tsig := make([]byte, 65)\n\n\tcopy(sig[32-len(r):32], r)\n\tcopy(sig[64-len(s):64], s)\n\tsig[64] = V\n\n\t// recover the public key from the signature\n\tpub, err := ethcrypto.Ecrecover(sigHash[:], sig)\n\tif err != nil {\n\t\treturn ethcmn.Address{}, err\n\t}\n\n\tif len(pub) == 0 || pub[0] != 4 {\n\t\treturn ethcmn.Address{}, errors.New(\"invalid public key\")\n\t}\n\n\tvar addr ethcmn.Address\n\tcopy(addr[:], ethcrypto.Keccak256(pub[1:])[12:])\n\n\treturn addr, nil\n}", "func checkDecode(input string, curve CurveID) (result []byte, err error) {\n\tdecoded := base58.Decode(input)\n\tif len(decoded) < 5 {\n\t\treturn nil, fmt.Errorf(\"invalid format\")\n\t}\n\tvar cksum [4]byte\n\tcopy(cksum[:], decoded[len(decoded)-4:])\n\t///// WARN: ok the ripemd160checksum should include the prefix in CERTAIN situations,\n\t// like when we imported the PubKey without a prefix ?! tied to the string representation\n\t// or something ? weird.. checksum shouldn't change based on the string reprsentation.\n\tif bytes.Compare(ripemd160checksum(decoded[:len(decoded)-4], curve), cksum[:]) != 0 {\n\t\treturn nil, fmt.Errorf(\"invalid checksum\")\n\t}\n\t// perhaps bitcoin has a leading net ID / version, but EOS doesn't\n\tpayload := decoded[:len(decoded)-4]\n\tresult = append(result, payload...)\n\treturn\n}", "func Verify(node map[int64][]byte, filename string,identity string, readbitlen int64,ch string) string {\n\tfmt.Println(\"Start validation\")\n\tt1:=time.Now()\n\n\n\tvar leafnodenum int64\n\tvar nodenum int64\n\tfilesize := GetFileSize(filename)\n\tif (filesize * 8 / readbitlen) > 0 {\n\t\tleafnodenum = (filesize*8/readbitlen + 1)\n\t} else {\n\t\tleafnodenum = (filesize * 8 / readbitlen)\n\t}\n\tfmt.Println(\"leafnodenum is \", leafnodenum)\n\tnodenum = Calcnodenumber(leafnodenum)\n\tfmt.Println(\"nodenum is \", nodenum)\n\n\trootnodevalue, ok := node [ nodenum-1 ]\n\tif (ok) {\n\t\tfmt.Println(\"rootnodevalue is \", rootnodevalue)\n\t} else {\n\t\tfmt.Println(\"rootnodevalue not exist\")\n\t\tvar result = \"Root node does not exist, validation failed\"\n\t\treturn result\n\t}\n\tvar rootnodestring string = biu.ToBinaryString(rootnodevalue)\n\n\trootnodestring = strings.Replace(rootnodestring, \"[\", \"\", -1)\n\n\trootnodestring = strings.Replace(rootnodestring, \"]\", \"\", -1)\n\n\trootnodestring = strings.Replace(rootnodestring, \" \", \"\", -1)\n\t//fmt.Println(\"rootnodestring is \", rootnodestring)\n\n\tvar bittosting string = biu.ToBinaryString(leafnodenum)\n\n\tbittosting = strings.Replace(bittosting, \"[\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \"]\", \"\", -1)\n\tbittosting = strings.Replace(bittosting, \" \", \"\", -1)\n\tvar stringlen = len(bittosting)\n\t//fmt.Println(\"leafnodenum is \", bittosting)\n\t//fmt.Println(\"stringlen is \", stringlen)\n\tvar stringiter int = 0\n\tvar zerolen int = 0\n\tfor stringiter = 0; stringiter < stringlen; stringiter++ {\n\t\tif '0' != bittosting[stringiter] {\n\t\t\t//zerolen = stringiter + 1\n\t\t\tzerolen = stringiter\n\t\t\tbreak\n\t\t}\n\t}\n\tvar eachlen uintptr = ((unsafe.Sizeof(leafnodenum) * 8) - uintptr(zerolen))\n\t//fmt.Println(\"eachlen is \", eachlen)\n\n\tvar nodeposition []int64\n\n\tvar chunkarray []string = ChunkString(rootnodestring, int(eachlen))\n\t//fmt.Println(\"chunkarray is \", chunkarray)\n\tvar bititer int = 0\n\tfor bititer = 0; bititer < len(chunkarray); bititer++ {\n\t\tvar tmpint int64 = 0\n\t\tvar partiter int = 0\n\t\tfor partiter = 0; partiter < len(chunkarray[bititer]); partiter++ {\n\t\t\ttmpint = (tmpint << 1)\n\t\t\tif '1' == chunkarray[bititer][partiter] {\n\t\t\t\ttmpint = (tmpint) ^ 1\n\t\t\t}\n\t\t\tif tmpint >= leafnodenum {\n\t\t\t\ttmpint = tmpint % leafnodenum\n\t\t\t}\n\n\t\t}\n\t\tnodeposition = append(nodeposition, tmpint)\n\t}\n\t//fmt.Println(\"nodeposition is \", nodeposition)\n\tnodeposition = RemoveRepeatedElement(nodeposition)\n\tfmt.Println(\"Leaf node to be verified is \", nodeposition)\n\n\n\t//1. Verify that the head value of the leaf node is consistent with the head value of the file stored locally\n\n\tvar headiter int\n\tfmt.Println(\"len(nodeposition) is \", len(nodeposition))\n\n\t//fmt.Println(\"verifyfile is \", verifyfile)\n\tfor headiter = 0; headiter < len(nodeposition); headiter++ {\n\n\t\t//var nodenumber int64\n\t\t//nodenumber = nodeposition[headiter]\n\t\t//fmt.Println(nodenumber,\"验证与本地文件是否相同的节点 \", nodeposition[headiter])\n\t\t//fmt.Println(\"node[nodeposition[headiter]] is \", node[nodeposition[headiter]])\n\t\tvar verifyfile []byte\n\t\tverifyfile,_ = ReadBlock(filename,readbitlen,readbitlen*nodeposition[headiter])\n\t\t//fmt.Println(\"verifyfile is \", verifyfile)\n\t\tif(verifyfile != nil){\n\t\t\t//fmt.Println(\"verifyfile is \", verifyfile)\n\t\t}else {\n\t\t\tfmt.Println(\"verifyfile is nil\")\n\t\t\treturn \"fail\"\n\t\t}\n\t\tif(node[nodeposition[headiter]] != nil){\n\t\t\t//fmt.Println(\"node[nodeposition[headiter]] is \", node[nodeposition[headiter]])\n\t\t}else {\n\t\t\treturn \"fail\"\n\t\t}\n\t\tret, _ := bitcompare(verifyfile, node[nodeposition[headiter]], readbitlen)\n\t\tif(ret){\n\n\t\t\t//fmt.Println(\"与本地文件相同节点:\", nodeposition[headiter])\n\t\t}else {\n\t\t\tfmt.Println(\"Verification failed node:\",nodeposition[headiter])\n\t\t\treturn \"The node is incorrect and the verification is unsuccessful\"\n\t\t}\n\t}\n\tfmt.Println(\"1.The head value of the node is the same as that of the local file\")\n\n\n\n\t//2,Verify whether hash(id||previoushash||nonce) is consistent with head||tail\n\n\tvar nodeiter int\n\t//var nodevalue []byte\n\t//var previousnode []byte\n\tfor nodeiter = 0; nodeiter < len(nodeposition); nodeiter++{\n\n\t\tnodevalue, ok := node [ nodeposition[nodeiter] ]\n\t\tif (ok) {\n\t\t\t//fmt.Println(\"nodevalue is \", nodevalue)\n\t\t} else {\n\t\t\tfmt.Println(\"not exist node:\",nodeposition[nodeiter])\n\t\t\tvar result = \"Node does not exist, validation failed\"\n\t\t\treturn result\n\t\t}\n\t\tif(nodeposition[nodeiter] ==0){\n\t\t\tvar trys string\n\t\t\tvar noucevalue int64\n\t\t\ttrys += identity\n\n\t\t\tnoucevalue = calnoucevalue(nodevalue)\n\t\t\t//identity||nouce\n\t\t\ttrys += strconv.FormatInt(noucevalue, 10)\n\t\t\t//计算hash\n\t\t\tcalc_hash := GetSHA256HashCode([]byte(trys))\n\n\t\t\tvar comparebyte []byte\n\t\t\tcomparebyte, _ = hex.DecodeString(calc_hash)\n\t\t\tret, _ := bitcompare(nodevalue, comparebyte, 32*8)\n\t\t\tif ret {\n\t\t\t\t//fmt.Println(\"nodevalue is \", nodevalue)\n\t\t\t\t//fmt.Println(\"comparebyte is \", comparebyte)\n\t\t\t\t//fmt.Println(\"Verification success node \", nodeposition[nodeiter])\n\n\t\t\t}else{\n\t\t\t\tfmt.Println(\"Verification failed node:\",nodeposition[nodeiter])\n\t\t\t\tvar result = \"The node is incorrect and the verification is unsuccessful\"\n\t\t\t\treturn result\n\t\t\t}\n\t\t}else{\n\t\t\t//fmt.Println(\"previousnode is \", nodeposition[nodeiter]-1)\n\t\t\tpreviousnode, ok := node [ nodeposition[nodeiter]-1 ]\n\t\t\tif (ok) {\n\t\t\t\t//fmt.Println(\"previousnode is \", nodeposition[nodeiter]-1)\n\t\t\t\t//fmt.Println(\"previousnodevalue is \", previousnode)\n\t\t\t\tvar trys string\n\t\t\t\tvar previoushash string\n\t\t\t\tvar noucevalue int64\n\t\t\t\tvar previousnodehead []byte\n\t\t\t\tpreviousnodehead = make([]byte,32)\n\t\t\t\tcopy(previousnodehead,previousnode)\n\t\t\t\t//fmt.Println(\"previousnodehead is \", previousnodehead)\n\t\t\t\ttrys += identity\n\t\t\t\tprevioushash = hex.EncodeToString(previousnodehead)\n\t\t\t\ttrys += previoushash\n\t\t\t\tnoucevalue = calnoucevalue(nodevalue)\n\t\t\t\t//identity||previouse||nonce\n\t\t\t\ttrys += strconv.FormatInt(noucevalue, 10)\n\t\t\t\t//计算hash\n\t\t\t\tcalc_hash := GetSHA256HashCode([]byte(trys))\n\n\t\t\t\tvar comparebyte []byte\n\t\t\t\tcomparebyte, _ = hex.DecodeString(calc_hash)\n\t\t\t\t//fmt.Println(\"comparebyte is \", comparebyte)\n\t\t\t\tret, _ := bitcompare(nodevalue, comparebyte, 32)\n\t\t\t\tif ret {\n\t\t\t\t\t//fmt.Println(\"nodevalue is \", nodevalue)\n\t\t\t\t\t//fmt.Println(\"comparebyte is \", comparebyte)\n\n\n\t\t\t\t}else{\n\t\t\t\t\tfmt.Println(\"previousnode:\",nodeposition[nodeiter])\n\t\t\t\t\tvar result = \"The node is incorrect and the verification is unsuccessful\"\n\t\t\t\t\treturn result\n\t\t\t\t}\n\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"not exist previousnode:\",nodeposition[nodeiter])\n\t\t\t\tvar result = \"The node is incorrect and the verification is unsuccessful\"\n\t\t\t\treturn result\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(\"2.hash(id||previoushash||nonce) head||tail is same\")\n\n\n\n\tvar rownum []int64\n\tvar nSize int64\n\tvar allnodenum int64 = 0\n\tvar key []byte = []byte(ch)\n\tfor nSize = leafnodenum; nSize > 1; nSize = (nSize + 1) / 2 {\n\t\tallnodenum = nSize + allnodenum\n\t\trownum = append(rownum, allnodenum)\n\t}\n\trownum = append(rownum,allnodenum+1)\n\tfmt.Println(\"Layers of Merkel tree:\",len(rownum))\n\n\tvar nodenumiter int64 = 0\n\tfor nodenumiter = 0; nodenumiter < int64(len(nodeposition)); nodenumiter++ {\n\n\t\tvar nodepath []int64\n\t\tnodepath = append(nodepath, nodeposition[nodenumiter])\n\t\tvar i int\n\t\tvar childnode int64\n\t\tvar nodenumber int64 = nodeposition[nodenumiter]\n\t\tvar nodevalue []byte\n\t\tfor i=1; i<len(rownum);i++{\n\t\t\tif(i == 1){\n\t\t\t\tchildnode = nodeposition[nodenumiter]\n\t\t\t}else{\n\t\t\t\tchildnode = childnode/2\n\t\t\t}\n\n\t\t\tvar verifynodevalue []byte\n\t\t\tif(i == 1){\n\t\t\t\tif Oddornot(childnode) {\n\t\t\t\t\tleftnodevalue, ok := node[nodenumber-1]\n\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t}\n\t\t\t\t\trightnodevalue, ok := node[nodenumber]\n\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t}\n\n\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\n\t\t\t\t} else{\n\t\t\t\t\tif(nodenumber == rownum[0]-1){\n\t\t\t\t\t\tleftnodevalue, ok := node[nodenumber]\n\t\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\trightnodevalue:= node[nodenumber]\n\t\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleftnodevalue, ok := node[nodenumber]\n\t\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\trightnodevalue, ok := node[nodenumber+1]\n\t\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}else{\n\t\t\t\tif Oddornot(childnode) {\n\t\t\t\t\tleftnodevalue, ok := node[nodenumber-1]\n\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t}\n\t\t\t\t\trightnodevalue := nodevalue\n\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\t\t\t\t} else{\n\t\t\t\t\tif(nodenumber == rownum[i-1]-1){\n\t\t\t\t\t\tleftnodevalue := nodevalue;\n\t\t\t\t\t\trightnodevalue := nodevalue\n\t\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\t\t\t\t\t}else{\n\t\t\t\t\t\tleftnodevalue := nodevalue;\n\t\t\t\t\t\trightnodevalue, ok := node[nodenumber+1]\n\t\t\t\t\t\tif (!ok) {\n\t\t\t\t\t\t\treturn \"The node does not exist\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\tverifynodevalue = CalMerkleNodeValue(leftnodevalue, rightnodevalue, key)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t\tnodevalue = verifynodevalue\n\t\t\tif(i == len(rownum)-1) {\n\t\t\t\t//Calculate to root node\n\t\t\t\t//fmt.Println(\"root node:\",node[rownum[i]-1])\n\t\t\t\t//fmt.Println(\"nodevalue\",nodevalue)\n\t\t\t\tret, _ := bitcompare(nodevalue, node[rownum[i]-1], 32*8)\n\t\t\t\tif (ret) {\n\t\t\t\t} else {\n\t\t\t\t\treturn \"Verification failed, wrong path\"\n\t\t\t\t}\n\t\t\t}\n\t\t\t//j represents the number of the node in the layer\n\t\t\tvar j int64\n\t\t\tj = childnode / 2\n\t\t\t//nodenumber is the number of the node in the Merkel tree\n\t\t\tnodenumber = rownum[i-1]+j\n\t\t\tnodepath = append(nodepath, nodenumber)\n\t\t}\n\t}\n\tfmt.Println(\"3.Node path validation successful\")\n\n\telapsed := time.Since(t1)\n\tfmt.Println(\"verification consumption time =\", elapsed)\n\tvar result = \"verify success\"\n\treturn result\n}", "func (v *visitor) isRecover(call *ast.CallExpr) bool {\n\tif fun, ok := call.Fun.(*ast.Ident); ok {\n\t\tif _, ok := v.typesInfo.Uses[fun].(*types.Builtin); ok {\n\t\t\treturn fun.Name == \"recover\"\n\t\t}\n\t}\n\treturn false\n}", "func FuzzVerify(data []byte) int {\n\tvar i Input\n\tif err := i.UnmarshalBinary(data); err != nil {\n\t\treturn -1\n\t}\n\n\tv := ECVRFP256SHA256TAI()\n\tsk := NewKey(v.Params().ec, i.SK[:])\n\t_, err := v.Verify(sk.Public(), i.PI[:], i.Alpha)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn 1\n}", "func (i *ITwoFactorService) RecoverAuthenticatorCommit() (*geyser.Request, error) {\n\tsm, err := i.Interface.Methods.Get(schema.MethodKey{\n\t\tName: \"RecoverAuthenticatorCommit\",\n\t\tVersion: 1,\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := geyser.NewRequest(i.Interface, sm)\n\n\treturn req, nil\n}", "func (gWal *GenericWAL) Recover() error {\n entryCh := make(chan *Entry)\n quitCh := make(chan struct{})\n defer close(quitCh)\n go func() {\n if err := gWal.wal.StartRecovery(entryCh, quitCh); err != nil {\n glog.Errorf(\"could not recover state from local wal :: %v\", err)\n entryCh <- nil\n }\n }()\n\n count := 0\n for entry := range entryCh {\n if entry == nil {\n glog.Errorf(\"wal recovery channel is closed unexpectedly\")\n return fmt.Errorf(\"wal error\")\n }\n count++\n\n switch entry.Type {\n case CTypeDone:\n glog.Infof(\"wal recovery is complete because last record is read\")\n close(entryCh)\n\n case CTypeData:\n gWal.updateRecoveryMap(false /* checkpoint */, int64(entry.LSN),\n entry.Data)\n glog.V(1).Infof(\"recovered a delta record with lsn %v\", entry.LSN)\n\n case CTypeCheckpoint:\n gWal.updateRecoveryMap(true /* checkpoint */, -1, entry.Data)\n glog.V(1).Infof(\"recovered a checkpoint record with lsn %v\", entry.LSN)\n\n case CTypeError:\n glog.Errorf(\"wal recovery encountered an unrecoverable error\")\n return fmt.Errorf(\"wal error\")\n\n default:\n glog.Errorf(\"wal recovery received an unknown or invalid record\")\n return fmt.Errorf(\"wal error\")\n }\n }\n\n return nil\n}", "func RecoverPubkey(msg []byte, sig []byte) []byte {\n\tif len(sig) != 65 {\n\t\tlog.Panic()\n\t}\n\n\tvar recid int = int(sig[64])\n\n\tpubkey, ret := secp.RecoverPublicKey(\n\t\tsig[0:64],\n\t\tmsg,\n\t\trecid)\n\n\tif ret != 1 {\n\t\tlog.Printf(\"RecoverPubkey: code %s\", ret)\n\t\treturn nil\n\t}\n\t//var pubkey2 []byte = pubkey1.Bytes() //compressed\n\n\tif pubkey == nil {\n\t\tlog.Panic(\"ERROR: impossible, pubkey nil and ret ==1\")\n\t}\n\tif len(pubkey) != 33 {\n\t\tlog.Panic(\"pubkey length wrong\")\n\t}\n\n\treturn pubkey\n\t//nonce1.SetBytes(nonce_seed)\n\n}", "func RetrieveFile(w http.ResponseWriter, r *http.Request) {\n\t//log\n\tnow, userIP := globalPkg.SetLogObj(r)\n\tlogobj := logpkg.LogStruct{\"_\", now, userIP, \"macAdress\", \"RetrieveFile\", \"file\", \"_\", \"_\", \"_\", 0}\n\n\tvar obj RetrieveBody\n\tdecoder := json.NewDecoder(r.Body)\n\tdecoder.DisallowUnknownFields()\n\terr := decoder.Decode(&obj)\n\tif err != nil {\n\t\tglobalPkg.SendError(w, \"please enter your correct request\")\n\t\tglobalPkg.WriteLog(logobj, \"please enter your correct request\", \"failed\")\n\t\treturn\n\t}\n\t// check for pk\n\tacc := account.GetAccountByAccountPubicKey(obj.Publickey)\n\tif acc.AccountPublicKey != obj.Publickey {\n\t\tglobalPkg.SendError(w, \"error in public key\")\n\t\tglobalPkg.WriteLog(logobj, \"error in public key\", \"failed\")\n\t\treturn\n\t}\n\t// check for pwd\n\tif acc.AccountPassword != obj.Password {\n\t\tglobalPkg.SendError(w, \"error in password\")\n\t\tglobalPkg.WriteLog(logobj, \"error in password\", \"failed\")\n\t\treturn\n\t}\n\t// TODO check time\n\t// Validate Signture\n\tvalidSig := false\n\tpk := account.FindpkByAddress(acc.AccountPublicKey).Publickey\n\tif pk != \"\" {\n\t\tpublickey := cryptogrpghy.ParsePEMtoRSApublicKey(pk)\n\t\t// signatureData := obj.FileID + obj.Publickey + obj.Password +\n\t\t// \tobj.Time\n\t\tsignatureData := obj.Publickey + obj.Password + obj.FileID\n\n\t\tvalidSig = cryptogrpghy.VerifyPKCS1v15(obj.Signture, signatureData, *publickey)\n\t\t// validSig = true\n\t} else {\n\t\tvalidSig = false\n\t}\n\tif !validSig {\n\t\tglobalPkg.SendError(w, \"you are not allowed to download\")\n\t\tglobalPkg.WriteLog(logobj, \"you are not allowed to download\", \"failed\")\n\t\treturn\n\t}\n\t// check is user own this file ?\n\tfiles := acc.Filelist\n\tfound := false\n\tvar selectedFile accountdb.FileList\n\tfor _, file := range files {\n\t\tif file.Fileid == obj.FileID {\n\t\t\tfound = true\n\t\t\tselectedFile = file\n\t\t\tbreak\n\t\t}\n\t}\n\t// check if this file share to this account== who take share file can download it\n\tsharefiles := filestorage.FindSharedfileByAccountIndex(acc.AccountIndex)\n\tif len(sharefiles.OwnerSharefile) != 0 {\n\t\tfor _, sharefileobj := range sharefiles.OwnerSharefile {\n\t\t\tif containsfileid(sharefileobj.Fileid, obj.FileID) {\n\t\t\t\tfound = true\n\t\t\t\taccuntObj := account.GetAccountByAccountPubicKey(sharefileobj.OwnerPublicKey)\n\t\t\t\tfor _, filelistObj := range accuntObj.Filelist {\n\t\t\t\t\tif filelistObj.Fileid == obj.FileID {\n\t\t\t\t\t\tselectedFile = filelistObj\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\t// fmt.Println(\"selectedFile.FileName \", selectedFile.FileName)\n\tif !found {\n\t\tglobalPkg.SendError(w, \"You don't have this file or file shared to you\")\n\t\tglobalPkg.WriteLog(logobj, \"You don't have this file or file shared to you\", \"failed\")\n\t\treturn\n\t}\n\n\t// collect file and save it in a temp file\n\tdecryptIndexBlock1 := cryptogrpghy.KeyDecrypt(globalpkg.EncryptAccount, selectedFile.Blockindex)\n\tfmt.Println(\" *********** block index \", decryptIndexBlock1)\n\tblkObj := block.GetBlockInfoByID(decryptIndexBlock1)\n\tvar fStrct filestorage.FileStruct\n\tfor _, tx := range blkObj.BlockTransactions {\n\t\tfStrct = tx.Filestruct\n\t\tif fStrct.Fileid == selectedFile.Fileid {\n\t\t\tfStrct = tx.Filestruct\n\t\t\tbreak\n\t\t}\n\t}\n\t// check active validators\n\tvar actives []validator.ValidatorStruct\n\tvalidatorLst := validator.GetAllValidators()\n\tfor _, valdtr := range validatorLst {\n\t\tif valdtr.ValidatorActive {\n\t\t\tactives = append(actives, valdtr)\n\t\t}\n\t}\n\tvar chnkObj filestorage.Chunkdb\n\tnewPath := filepath.Join(uploadPath, fStrct.Fileid+fStrct.FileType)\n\tfile, er := os.OpenFile(newPath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0777)\n\tif er != nil {\n\t\tfmt.Println(\"error in open file \", err)\n\t\tglobalPkg.SendError(w, \"server is down !\")\n\t\tglobalPkg.WriteLog(logobj, \"can not oprn file \", \"failed\")\n\t\treturn\n\t}\n\tdefer file.Close()\n\tnotvalidchnkdata := false\n\tcountnotvalidchnkdata := 0\n\tvar res broadcastTcp.FileBroadcastResponse\n\tvar chunkcount int = 0\n\tfor key, value := range fStrct.Mapping {\n\t\tfor _, chunkDta := range value {\n\t\t\t// time.Sleep(time.Millisecond * 10)\n\t\t\tindofvalidator := contains(actives, chunkDta.ValidatorIP)\n\t\t\tif indofvalidator != -1 {\n\t\t\t\tvalidatorObj2 := actives[indofvalidator]\n\t\t\t\tchnkObj.Chunkid = key\n\t\t\t\tchnkObj.Chunkhash = chunkDta.Chunkhash\n\t\t\t\t// _, _, res := broadcastTcp.SendObject(chnkObj, actives[i].ValidatorPublicKey, \"getchunkdata\", \"file\", actives[i].ValidatorSoketIP)\n\t\t\t\tif validatorObj2.ValidatorPublicKey == validator.CurrentValidator.ValidatorPublicKey {\n\t\t\t\t\t_, _, res = broadcastTcp.SendObject(chnkObj, validator.CurrentValidator.ValidatorPublicKey, \"getchunkdata\", \"file\", validator.CurrentValidator.ValidatorSoketIP)\n\n\t\t\t\t} else {\n\t\t\t\t\t_, _, res = broadcastTcp.SendObject(chnkObj, validatorObj2.ValidatorPublicKey, \"getchunkdata\", \"file\", validatorObj2.ValidatorSoketIP)\n\t\t\t\t}\n\t\t\t\tif !res.Valid {\n\t\t\t\t\tfmt.Println(\"server is down\")\n\t\t\t\t\tnotvalidchnkdata = true\n\t\t\t\t\tcontinue\n\t\t\t\t} else {\n\t\t\t\t\treshashchunk := globalPkg.GetHash(res.ChunkData)\n\t\t\t\t\tif reshashchunk != chnkObj.Chunkhash {\n\t\t\t\t\t\tfmt.Println(\"chunk data is lost .\")\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else {\n\t\t\t\t\t\tnotvalidchnkdata = false\n\n\t\t\t\t\t\t_, err := file.Write(res.ChunkData)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfmt.Println(\"error in write chunk to file : \", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t\tchunkcount++\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t} // end else\n\t\t\t\tif notvalidchnkdata { // currupted\n\t\t\t\t\tcountnotvalidchnkdata++\n\t\t\t\t\tfmt.Println(\"Count of not valid chunk data : \", countnotvalidchnkdata)\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\tfmt.Println(\"written chunk \", chunkcount)\n\tfile0, er2 := ioutil.ReadFile(newPath)\n\tif er2 != nil {\n\t\tfmt.Println(\"error in reading file !!!\")\n\t}\n\tcollectedhashfile := globalPkg.GetHash(file0)\n\tfmt.Println(\"Collected File Hash \", collectedhashfile)\n\tfmt.Println(\"Original File Hash \", fStrct.FileHash2)\n\n\t// if collectedhashfile != fStrct.FileHash {\n\t// \tif countnotvalidchnkdata > 0 {\n\t// \t\tfmt.Println(\"error in getting chunk data !!!\")\n\t// \t}\n\t// \tglobalPkg.SendError(w, \"server is down !\")\n\t// \tglobalPkg.WriteLog(logobj, \"collected file hash not equall\", \"failed\")\n\t// \treturn\n\t// }\n\n\t// read file as bytes\n\tfile2, er2 := os.Open(newPath)\n\tif er2 != nil {\n\t\tfmt.Println(\"error in reading file !!!\")\n\t}\n\n\tfileinfoCollected, _ := file2.Stat()\n\tfmt.Println(\"File Size \", fStrct.FileSize)\n\tfmt.Println(\"Collected File Size \", fileinfoCollected.Size())\n\t// if fStrct.FileSize != fileinfoCollected.Size() {\n\t// \tglobalPkg.SendError(w, \"file is corrupted\")\n\t// \tglobalPkg.WriteLog(logobj, \"file is corrupted size file is different\", \"failed\")\n\t// \treturn\n\t// }\n\t// ip := strings.Split(validator.CurrentValidator.ValidatorIP, \":\")\n\t// fmt.Println(\"length of string : \", len(ip))\n\t// strip := ip[0] + \"s\"\n\t// httpsip := strip + \":\" + ip[1] + \":\" + ip[2]\n\t// // u, err := url.Parse(validator.CurrentValidator.ValidatorIP)\n\t// u, err := url.Parse(httpsip)\n\t// fmt.Println(\"=================== link \", u, \"========path ==== \", validator.CurrentValidator.ValidatorIP)\n\t// if err != nil {\n\t// \tfmt.Println(err)\n\t// }\n\t// u, err := url.Parse(\"https://us-demoinochain.inovatian.com\")\n\tu, err := url.Parse(globalPkg.GlobalObj.Downloadfileip)\n\n\tu.Path = path.Join(u.Path, \"files\", fStrct.Fileid+fStrct.FileType)\n\tlink := u.String()\n\tglobalPkg.SendResponseMessage(w, link)\n\tglobalPkg.WriteLog(logobj, \"File downloaded successfully\", \"failed\")\n\n}", "func (p *BlsCosi) checkIntegrity() error {\n\tif p.Msg == nil {\n\t\treturn fmt.Errorf(\"no proposal msg specified\")\n\t}\n\tif p.CreateProtocol == nil {\n\t\treturn fmt.Errorf(\"no create protocol function specified\")\n\t}\n\tif p.verificationFn == nil {\n\t\treturn fmt.Errorf(\"verification function cannot be nil\")\n\t}\n\tif p.subProtocolName == \"\" {\n\t\treturn fmt.Errorf(\"sub-protocol name cannot be empty\")\n\t}\n\tif p.Timeout < 500*time.Microsecond {\n\t\treturn fmt.Errorf(\"unrealistic timeout\")\n\t}\n\tif p.Threshold > p.Tree().Size() {\n\t\treturn fmt.Errorf(\"threshold (%d) bigger than number of nodes (%d)\", p.Threshold, p.Tree().Size())\n\t}\n\tif p.Threshold < 1 {\n\t\treturn fmt.Errorf(\"threshold of %d smaller than one node\", p.Threshold)\n\t}\n\n\treturn nil\n}", "func setupSignature(t *testing.T) (stop func(), clients []*exec.Cmd, contractPath, contractFilePath string) {\n\t// Cleanup\n\teraseDatabase()\n\n\t// Start the platform\n\tworkingDir, err := ioutil.TempDir(\"\", \"dfss_\")\n\tassert.Equal(t, nil, err)\n\t_, _, _, stop, ca, err := startPlatform(workingDir)\n\tassert.Equal(t, nil, err)\n\n\ttime.Sleep(2 * time.Second)\n\n\t// Register clients\n\tclient1, err := createClient(workingDir, ca, 9091)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client1, \"[email protected]\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient2, err := createClient(workingDir, ca, 9092)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client2, \"[email protected]\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\tclient3, err := createClient(workingDir, ca, 9093)\n\tassert.Equal(t, nil, err)\n\terr = registerAndAuth(client3, \"[email protected]\", \"password\", \"\", true, true)\n\tassert.Equal(t, nil, err)\n\n\t// Create contract\n\tclient1 = newClient(client1)\n\tsetLastArg(client1, \"new\", true)\n\tcontractFilePath = filepath.Join(\"testdata\", \"contract.txt\")\n\tclient1.Stdin = strings.NewReader(\n\t\t\"password\\n\" +\n\t\t\tcontractFilePath + \"\\n\" +\n\t\t\t\"\\n\" +\n\t\t\t\"[email protected]\\n\" +\n\t\t\t\"[email protected]\\n\" +\n\t\t\t\"[email protected]\\n\" +\n\t\t\t\"\\n\",\n\t)\n\terr = checkStderr(t, client1, \"\")\n\tassert.Equal(t, nil, err)\n\n\t// Get contract file\n\tcontractEntity := getContract(\"contract.txt\", 0)\n\tcontractData, err := contract.GetJSON(contractEntity)\n\tassert.Equal(t, nil, err)\n\tcontractPath = filepath.Join(workingDir, \"c.dfss\")\n\terr = ioutil.WriteFile(contractPath, contractData, os.ModePerm)\n\tassert.Equal(t, nil, err)\n\n\t// Test with wrong file, should abort\n\twrongFileClient := newClient(client1)\n\tsetLastArg(wrongFileClient, \"sign\", true)\n\tsetLastArg(wrongFileClient, contractPath, false)\n\twrongFileClient.Stdin = strings.NewReader(\"wrongfile.txt\\npassword\\nyes\\n\")\n\t_, err = wrongFileClient.Output()\n\tassert.NotNil(t, err)\n\n\tclients = make([]*exec.Cmd, 3)\n\tclients[0] = newClient(client1)\n\tclients[1] = newClient(client2)\n\tclients[2] = newClient(client3)\n\treturn\n}", "func RecoverAll() {\n\tdoRecover(recover(), true)\n}", "func parseRecover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\tpanic(e)\n\t\t}\n\t\t*errp = e.(error)\n\t}\n\treturn\n}", "func (uv *UtxoVM) verifySignatures(tx *pb.Transaction, digestHash []byte) (bool, map[string]bool, error) {\n\t// XuperSign is not empty, use XuperSign verify\n\tif tx.GetXuperSign() != nil {\n\t\treturn uv.verifyXuperSign(tx, digestHash)\n\t}\n\n\t// Not XuperSign(multisig/rignsign etc.), use old signature process\n\tverifiedAddr := make(map[string]bool)\n\tif len(tx.InitiatorSigns) < 1 || len(tx.AuthRequire) != len(tx.AuthRequireSigns) {\n\t\treturn false, nil, errors.New(\"invalid signature param\")\n\t}\n\n\t// verify initiator\n\takType := acl.IsAccount(tx.Initiator)\n\tif akType == 0 {\n\t\t// check initiator address signature\n\t\tok, err := pm.IdentifyAK(tx.Initiator, tx.InitiatorSigns[0], digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[tx.Initiator] = true\n\t} else if akType == 1 {\n\t\tinitiatorAddr := make([]string, 0)\n\t\t// check initiator account signatures\n\t\tfor _, sign := range tx.InitiatorSigns {\n\t\t\tak, err := uv.cryptoClient.GetEcdsaPublicKeyFromJSON([]byte(sign.PublicKey))\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\taddr, err := uv.cryptoClient.GetAddressFromPublicKey(ak)\n\t\t\tif err != nil {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn false, nil, err\n\t\t\t}\n\t\t\tok, err := pm.IdentifyAK(addr, sign, digestHash)\n\t\t\tif !ok {\n\t\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", tx.Initiator, \"error\", err)\n\t\t\t\treturn ok, nil, err\n\t\t\t}\n\t\t\tverifiedAddr[addr] = true\n\t\t\tinitiatorAddr = append(initiatorAddr, tx.Initiator+\"/\"+addr)\n\t\t}\n\t\tok, err := pm.IdentifyAccount(tx.Initiator, initiatorAddr, uv.aclMgr)\n\t\tif !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures initiator permission check failed\",\n\t\t\t\t\"account\", tx.Initiator, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t} else {\n\t\tuv.xlog.Warn(\"verifySignatures failed, invalid address\", \"address\", tx.Initiator)\n\t\treturn false, nil, ErrInvalidSignature\n\t}\n\n\t// verify authRequire\n\tfor idx, authReq := range tx.AuthRequire {\n\t\tsplitRes := strings.Split(authReq, \"/\")\n\t\taddr := splitRes[len(splitRes)-1]\n\t\tsignInfo := tx.AuthRequireSigns[idx]\n\t\tif _, has := verifiedAddr[addr]; has {\n\t\t\tcontinue\n\t\t}\n\t\tok, err := pm.IdentifyAK(addr, signInfo, digestHash)\n\t\tif err != nil || !ok {\n\t\t\tuv.xlog.Warn(\"verifySignatures failed\", \"address\", addr, \"error\", err)\n\t\t\treturn false, nil, err\n\t\t}\n\t\tverifiedAddr[addr] = true\n\t}\n\treturn true, verifiedAddr, nil\n}", "func compactSigCheck(t *testing.T, sig []byte) {\n\tt.Helper()\n\tb := int(sig[32])\n\tif b < 0 {\n\t\tt.Errorf(\"highest bit is negative: %d\", b)\n\t}\n\tif ((b >> 7) == 1) != ((b & 0x80) == 0x80) {\n\t\tt.Errorf(\"highest bit: %d bit >> 7: %d\", b, b>>7)\n\t}\n\tif (b & 0x80) == 0x80 {\n\t\tt.Errorf(\"highest bit: %d bit & 0x80: %d\", b, b&0x80)\n\t}\n}", "func Recover(cb func()) (err error) {\n\tdefer func() {\n\t\tif e := recover(); e != nil {\n\t\t\terr = errors.E(\"panic %v: %v\", e, string(debug.Stack()))\n\t\t}\n\t}()\n\tcb()\n\treturn nil\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) Digest(opts *bind.CallOpts) ([32]byte, error) {\n\tvar (\n\t\tret0 = new([32]byte)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"digest\")\n\treturn *ret0, err\n}", "func (keyDB *KeyDB) ShouldRecover(lastAvailableBlock uint64) (bool, uint64, error) {\n\tsavepoint, err := keyDB.GetLastSavepoint()\n\tif err != nil {\n\t\treturn false, 0, err\n\t}\n\tif savepoint == nil {\n\t\treturn true, 0, nil\n\t}\n\treturn savepoint.BlockNum != lastAvailableBlock, savepoint.BlockNum + 1, nil\n}", "func readMasterDigest() (defaultUser string, protection string, masterDigest *[]byte, err error) {\n\tdir, err := filepath.Abs(filepath.Dir(os.Args[0]))\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\tvar content *[]byte = new([]byte)\n\tdefer clearByteSlice(content)\n\t*content, err = ioutil.ReadFile(dir + \"/\" + masterDigestFilename)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\n\t// Reading the file step by step instead of with bytes.Split() to avoid using more memory than necessary for security purposes\n\tvar i int\n\ti = bytes.Index(*content, []byte(\"Default user: \"))\n\tif i < 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"'Default user: ' not found in secret digest file\")\n\t}\n\tif i > 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"'Default user: ' must be the start of the secret digest file\")\n\t}\n\tclearAndTrim(content, i+len([]byte(\"Default user: \")))\n\ti = bytes.Index(*content, []byte(\"\\n\"))\n\tif i < 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"New line not found after 'Default user: ' in secret digest file\")\n\t}\n\tdefaultUser = string((*content)[:i])\n\tclearAndTrim(content, i+len([]byte(\"\\n\")))\n\ti = bytes.Index(*content, []byte(\"Protection: \"))\n\tif i < 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"'Protection: ' not found in secret digest file\")\n\t}\n\tclearAndTrim(content, i+len([]byte(\"Protection: \")))\n\ti = bytes.Index(*content, []byte(\"\\n\"))\n\tif i < 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"New line not found after 'Protection: ' in secret digest file\")\n\t}\n\tprotection = string((*content)[:i])\n\tclearAndTrim(content, i+len([]byte(\"\\n\")))\n\ti = bytes.Index(*content, []byte(\"Secret Digest: \"))\n\tif i < 0 {\n\t\treturn \"\", \"\", nil, errors.New(\"'Secret Digest: ' not found in secret digest file\")\n\t}\n\tclearAndTrim(content, i+len([]byte(\"Secret Digest: \")))\n\tmasterDigest = new([]byte)\n\t*masterDigest, err = base64.StdEncoding.DecodeString(string(*content))\n\tclearByteSlice(content)\n\tif err != nil {\n\t\treturn \"\", \"\", nil, err\n\t}\n\treturn defaultUser, protection, masterDigest, nil\n}", "func Test_Secp256_06b(t *testing.T) {\n\tpubkey1, seckey := GenerateKeyPair()\n\tmsg := RandByte(32)\n\tsig := Sign(msg, seckey)\n\n\tfail_count := 0\n\tfor i := 0; i < TESTS; i++ {\n\t\tmsg = RandByte(32)\n\t\tpubkey2 := RecoverPubkey(msg, sig)\n\t\tif bytes.Equal(pubkey1, pubkey2) == true {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif pubkey2 != nil && VerifySignature(msg, sig, pubkey2) != 1 {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif VerifySignature(msg, sig, pubkey1) == 1 {\n\t\t\tt.Fail()\n\t\t}\n\t}\n\tif fail_count != 0 {\n\t\tfmt.Printf(\"ERROR: Accepted signature for %v of %v random messages\\n\", fail_count, TESTS)\n\t}\n}", "func Test_Secp256_06b(t *testing.T) {\n\tpubkey1, seckey := GenerateKeyPair()\n\tmsg := RandByte(32)\n\tsig := Sign(msg, seckey)\n\n\tfail_count := 0\n\tfor i := 0; i < TESTS; i++ {\n\t\tmsg = RandByte(32)\n\t\tpubkey2 := RecoverPubkey(msg, sig)\n\t\tif bytes.Equal(pubkey1, pubkey2) == true {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif pubkey2 != nil && VerifySignature(msg, sig, pubkey2) != 1 {\n\t\t\tt.Fail()\n\t\t}\n\n\t\tif VerifySignature(msg, sig, pubkey1) == 1 {\n\t\t\tt.Fail()\n\t\t}\n\t}\n\tif fail_count != 0 {\n\t\tfmt.Printf(\"ERROR: Accepted signature for %v of %v random messages\\n\", fail_count, TESTS)\n\t}\n}", "func finishedSum(md5, sha1, label, masterSecret []byte) []byte {\n\tseed := make([]byte, len(md5)+len(sha1));\n\tbytes.Copy(seed, md5);\n\tbytes.Copy(seed[len(md5):len(seed)], sha1);\n\tout := make([]byte, finishedVerifyLength);\n\tpRF11(out, masterSecret, label, seed);\n\treturn out;\n}", "func BaseDER(path string) string {\n dat, _ := ioutil.ReadFile(path)\n block, _ := pem.Decode(dat)\n if block == nil {\n return \"No Key Found.\"\n } // end if.\n\n pubout := base64.StdEncoding.EncodeToString(block.Bytes)\n return pubout\n\n}", "func (_BondedECDSAKeep *BondedECDSAKeepCaller) CheckSignatureFraud(opts *bind.CallOpts, _v uint8, _r [32]byte, _s [32]byte, _signedDigest [32]byte, _preimage []byte) (bool, error) {\n\tvar (\n\t\tret0 = new(bool)\n\t)\n\tout := ret0\n\terr := _BondedECDSAKeep.contract.Call(opts, out, \"checkSignatureFraud\", _v, _r, _s, _signedDigest, _preimage)\n\treturn *ret0, err\n}", "func Recover() arpc.HandlerFunc {\n\treturn func(ctx *arpc.Context) {\n\t\tdefer util.Recover()\n\t\tctx.Next()\n\t}\n}", "func (c OffChainCrossNodeSimplePaymentReconciliationBill) VerifySignature() error {\n\n\treturn c.ChannelChainTransferData.CheckMustAddressAndSigns()\n}", "func recovery() {\n\n\tif r := recover(); r != nil {fmt.Println(\"some error has occured_______________________________________________\",r)}\n}", "func strictSignatureCheck(pk PublicKey, signature ByteSlice) error {\n\tswitch pk.Algorithm {\n\tcase SignatureAlgoEd25519:\n\t\tif len(pk.Key) != crypto.PublicKeySize {\n\t\t\treturn errors.New(\"invalid public key size in transaction\")\n\t\t}\n\t\tif len(signature) != crypto.SignatureSize {\n\t\t\treturn errors.New(\"invalid signature size in transaction\")\n\t\t}\n\t\treturn nil\n\tdefault:\n\t\treturn errors.New(\"unrecognized public key type in transaction\")\n\t}\n}", "func TestSignVerifyHash(t *testing.T) {\n\tt.Parallel()\n\t// Create some random data.\n\tdata := fastrand.Bytes(100)\n\t// Generate a keypair.\n\tsk, pk := GenerateED25519KeyPair()\n\t// Hash the data.\n\thash := blake2b.Sum256(data)\n\t// Sign the data.\n\tsig := signHash(hash, sk)\n\t// Verify signature\n\tif !verifyHash(hash, pk, sig) {\n\t\tt.Fatal(\"signature wasn't verified\")\n\t}\n}", "func Recover(db *datastore.CachedDB, latest types.LayerID, beacon system.BeaconGetter, opts ...Opt) (*Tortoise, error) {\n\ttrtl, err := New(opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlayer, err := ballots.LatestLayer(db)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load latest known layer: %w\", err)\n\t}\n\n\tmalicious, err := identities.GetMalicious(db)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"recover malicious %w\", err)\n\t}\n\tfor _, id := range malicious {\n\t\ttrtl.OnMalfeasance(id)\n\t}\n\n\tif types.GetEffectiveGenesis() != types.FirstEffectiveGenesis() {\n\t\t// need to load the golden atxs after a checkpoint recovery\n\t\tif err := recoverEpoch(types.GetEffectiveGenesis().Add(1).GetEpoch(), trtl, db, beacon); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tepoch, err := atxs.LatestEpoch(db)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load latest epoch: %w\", err)\n\t}\n\tepoch++ // recoverEpoch expects target epoch, rather than publish\n\tif layer.GetEpoch() != epoch {\n\t\tfor eid := layer.GetEpoch(); eid <= epoch; eid++ {\n\t\t\tif err := recoverEpoch(eid, trtl, db, beacon); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\tfor lid := types.GetEffectiveGenesis().Add(1); !lid.After(layer); lid = lid.Add(1) {\n\t\tif err := RecoverLayer(context.Background(), trtl, db, beacon, lid, types.MinLayer(layer, latest)); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load tortoise state at layer %d: %w\", lid, err)\n\t\t}\n\t}\n\treturn trtl, nil\n}", "func d(digest types.Digest) []byte {\n\tif len(digest) != 2*md5.Size {\n\t\tpanic(\"digest wrong length \" + string(digest))\n\t}\n\tb, err := hex.DecodeString(string(digest))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func d(digest types.Digest) []byte {\n\tif len(digest) != 2*md5.Size {\n\t\tpanic(\"digest wrong length \" + string(digest))\n\t}\n\tb, err := hex.DecodeString(string(digest))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func getCryptoParams(db *sql.DB, ignore_version bool) (iv, key []byte) {\n var id, version, signature, sync_uuid string\n var hash, info []byte\n const VERSION = \"5\"\n const SIGNATURE = \"WalletxDb\"\n\n row := db.QueryRow(\"SELECT * FROM Identity\")\n err := row.Scan(&id, &version, &signature, &sync_uuid, &hash, &info)\n check(err)\n\n if debug {\n fmt.Fprintf(os.Stderr,\n \"Id: %v, version: %v, signature: %v, sync uuid %v, hash bytes: %d, info bytes: %d\\n\",\n id, version, signature, sync_uuid, len(hash), len(info))\n fmt.Println()\n }\n\n if (version != VERSION || signature != SIGNATURE) && !ignore_version {\n fmt.Fprintf(os.Stderr,\n \"Database version is '%s' and signature is '%s'\\n\",\n version, signature)\n fmt.Fprintf(os.Stderr,\n \"The program is designed for version '%s' and signature '%s'\\n\",\n VERSION, SIGNATURE)\n fmt.Fprintf(os.Stderr,\n \"To execute in spite of the difference, please use '-ignore'\\n\")\n os.Exit(1)\n }\n\n iv = info[16:32]\n salt := info[32:48]\n key = generateKey(hash, salt)\n\n return\n}", "func (m *ManagedDeviceItemRequestBuilder) RecoverPasscode()(*ib6fe4058a826f6d827fec2a61b53730458811701046b26ceb4044feeb7ddf7d1.RecoverPasscodeRequestBuilder) {\n return ib6fe4058a826f6d827fec2a61b53730458811701046b26ceb4044feeb7ddf7d1.NewRecoverPasscodeRequestBuilderInternal(m.pathParameters, m.requestAdapter);\n}", "func consumeSigVerificationGas(\n\tmeter sdk.GasMeter, sig []byte, pubkey crypto.PubKey, params Params,\n) sdk.Result {\n\n\tpubkeyType := strings.ToLower(fmt.Sprintf(\"%T\", pubkey))\n\n\tswitch {\n\tcase strings.Contains(pubkeyType, \"ed25519\"):\n\t\tmeter.ConsumeGas(params.SigVerifyCostED25519, \"ante verify: ed25519\")\n\t\treturn sdk.ErrInvalidPubKey(\"ED25519 public keys are unsupported\").Result()\n\n\tcase strings.Contains(pubkeyType, \"secp256k1\"):\n\t\tmeter.ConsumeGas(params.SigVerifyCostSecp256k1, \"ante verify: secp256k1\")\n\t\treturn sdk.Result{}\n\n\tcase strings.Contains(pubkeyType, \"multisigthreshold\"):\n\t\tvar multisignature multisig.Multisignature\n\t\tcodec.Cdc.MustUnmarshalBinaryBare(sig, &multisignature)\n\n\t\tmultisigPubKey := pubkey.(multisig.PubKeyMultisigThreshold)\n\t\tconsumeMultisignatureVerificationGas(meter, multisignature, multisigPubKey, params)\n\t\treturn sdk.Result{}\n\n\tdefault:\n\t\treturn sdk.ErrInvalidPubKey(fmt.Sprintf(\"unrecognized public key type: %s\", pubkeyType)).Result()\n\t}\n}", "func SignCompact(key *PrivateKey, hash []byte, isCompressedKey bool) ([]byte, error) {\n\tsig := key.Sign(hash)\n\n\tcurve := S256()\n\t// bitcoind checks the bit length of R and S here. The ecdsa signature\n\t// algorithm returns R and S mod N therefore they will be the bitsize of\n\t// the curve, and thus correctly sized.\n\tfor i := 0; i < (curve.H+1)*2; i++ {\n\t\tpk, err := recoverKeyFromSignature(sig, hash, i, true)\n\t\tif err == nil && pk.X.Cmp(key.X) == 0 && pk.Y.Cmp(key.Y) == 0 {\n\t\t\tresult := make([]byte, 1, 2*curve.byteSize+1)\n\t\t\tresult[0] = 27 + byte(i)\n\t\t\tif isCompressedKey {\n\t\t\t\tresult[0] += 4\n\t\t\t}\n\t\t\t// Not sure this needs rounding but safer to do so.\n\t\t\tcurvelen := (curve.BitSize + 7) / 8\n\n\t\t\t// Pad R and S to curvelen if needed.\n\t\t\tbytelen := (sig.R.BitLen() + 7) / 8\n\t\t\tif bytelen < curvelen {\n\t\t\t\tresult = append(result,\n\t\t\t\t\tmake([]byte, curvelen-bytelen)...)\n\t\t\t}\n\t\t\tresult = append(result, sig.R.Bytes()...)\n\n\t\t\tbytelen = (sig.S.BitLen() + 7) / 8\n\t\t\tif bytelen < curvelen {\n\t\t\t\tresult = append(result,\n\t\t\t\t\tmake([]byte, curvelen-bytelen)...)\n\t\t\t}\n\t\t\tresult = append(result, sig.S.Bytes()...)\n\n\t\t\treturn result, nil\n\t\t}\n\t}\n\n\treturn nil, errors.New(\"no valid solution for pubkey found\")\n}", "func Sign(name string, message string, password string)([]byte, []byte, error){\n\n\tvar manager cryptostore.Manager\n\trootDir := os.Getenv(\"BASECLIHOME\")\n\tfmt.Println(\"rootdir\"+rootDir)\n\tkeyDir := filepath.Join(rootDir, KeySubdir)\n\n\tsignEssue.Message = []byte(message)\n\t// TODO: smarter loading??? with language and fallback?\n\tcodec := keys.MustLoadCodec(\"english\")\n\tmanager = cryptostore.New(\n\t\tcryptostore.SecretBox,\n\t\tfilestorage.New(keyDir),\n\t\tcodec,\n\t)\n\tvar sign keys.Signable\n\tfmt.Println(&sign)\n\tsign = &signEssue\n\tfmt.Println(sign)\n\terr := manager.Sign(name, password, sign)\n\tif err != nil{\n\t\treturn \tnil, nil, err\n\t}else {\n\t\treturn signEssue.Publikey.Bytes()[1:], signEssue.Sig.Bytes()[1:], nil\n\t}\n}", "func (j *jws) Compact(key interface{}) ([]byte, error) {\n\tif len(j.sb) < 1 {\n\t\treturn nil, ErrNotEnoughMethods\n\t}\n\n\tif err := j.sign(key); err != nil {\n\t\treturn nil, err\n\t}\n\n\tsig, err := j.sb[0].Signature.Base64()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn format(\n\t\tj.sb[0].Protected,\n\t\tj.plcache,\n\t\tsig,\n\t), nil\n}", "func TestCheckSignatureEncoding(t *testing.T) {\n\tt.Parallel()\n\n\ttests := []struct {\n\t\tname string\n\t\tsig []byte\n\t\tisValid bool\n\t}{\n\t\t{\n\t\t\tname: \"valid signature\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: true,\n\t\t},\n\t\t{\n\t\t\tname: \"empty.\",\n\t\t\tsig: nil,\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad magic\",\n\t\t\tsig: decodeHex(\"314402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad 1st int marker magic\",\n\t\t\tsig: decodeHex(\"304403204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"bad 2nd int marker\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41032018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"short len\",\n\t\t\tsig: decodeHex(\"304302204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long len\",\n\t\t\tsig: decodeHex(\"304502204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long X\",\n\t\t\tsig: decodeHex(\"304402424e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"long Y\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022118152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"short Y\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41021918152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"trailing crap\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d0901\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"X == N \",\n\t\t\tsig: decodeHex(\"30440220fffffffffffffffffffffffffffff\" +\n\t\t\t\t\"ffebaaedce6af48a03bbfd25e8cd0364141022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"X == N \",\n\t\t\tsig: decodeHex(\"30440220fffffffffffffffffffffffffffff\" +\n\t\t\t\t\"ffebaaedce6af48a03bbfd25e8cd0364142022018152\" +\n\t\t\t\t\"2ec8eca07de4860a4acdd12909d831cc56cbbac46220\" +\n\t\t\t\t\"82221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Y == N\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410220fffff\" +\n\t\t\t\t\"ffffffffffffffffffffffffffebaaedce6af48a03bb\" +\n\t\t\t\t\"fd25e8cd0364141\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Y > N\",\n\t\t\tsig: decodeHex(\"304402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410220fffff\" +\n\t\t\t\t\"ffffffffffffffffffffffffffebaaedce6af48a03bb\" +\n\t\t\t\t\"fd25e8cd0364142\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"0 len X\",\n\t\t\tsig: decodeHex(\"302402000220181522ec8eca07de4860a4acd\" +\n\t\t\t\t\"d12909d831cc56cbbac4622082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"0 len Y\",\n\t\t\tsig: decodeHex(\"302402204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd410200\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"extra R padding\",\n\t\t\tsig: decodeHex(\"30450221004e45e16932b8af514961a1d3a1a\" +\n\t\t\t\t\"25fdf3f4f7732e9d624c6c61548ab5fb8cd410220181\" +\n\t\t\t\t\"522ec8eca07de4860a4acdd12909d831cc56cbbac462\" +\n\t\t\t\t\"2082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t\t{\n\t\t\tname: \"extra S padding\",\n\t\t\tsig: decodeHex(\"304502204e45e16932b8af514961a1d3a1a25\" +\n\t\t\t\t\"fdf3f4f7732e9d624c6c61548ab5fb8cd41022100181\" +\n\t\t\t\t\"522ec8eca07de4860a4acdd12909d831cc56cbbac462\" +\n\t\t\t\t\"2082221a8768d1d09\"),\n\t\t\tisValid: false,\n\t\t},\n\t}\n\n\t// flags := ScriptVerifyStrictEncoding\n\tflags := StandardVerifyFlags\n\tfor _, test := range tests {\n\t\terr := TstCheckSignatureEncoding(test.sig, flags)\n\t\tif err != nil && test.isValid {\n\t\t\tt.Errorf(\"checkSignatureEncoding test '%s' failed \"+\n\t\t\t\t\"when it should have succeeded: %v\", test.name,\n\t\t\t\terr)\n\t\t} else if err == nil && !test.isValid {\n\t\t\tt.Errorf(\"checkSignatureEncooding test '%s' succeeded \"+\n\t\t\t\t\"when it should have failed\", test.name)\n\t\t}\n\t}\n}", "func (r *rpcClient) Recover(ctx context.Context) error {\n\tctx, span := r.startSpanFromContext(ctx, \"sb.rpcClient.Recover\")\n\tdefer span.End()\n\n\t_ = r.Close()\n\treturn r.ensureConn(ctx)\n}", "func TestInvalidSignatureRead(t *testing.T) {\n\tfor _, tt := range fileTests {\n\t\tcapset, err := NewCapSet()\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tm, err := NewMutableFile(capset, \"/tmp\")\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\t_, err = m.Write(tt.contents)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer os.Remove(path.Join(m.storageDir, m.filename))\n\n\t\thandle, err := os.OpenFile(path.Join(m.storageDir, m.filename),\n\t\t\tos.O_RDWR, 0)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"could not open file: %s\", err)\n\t\t}\n\t\tfileInfo, _ := handle.Stat()\n\t\tgarbage := []byte{0xBA, 0xAD, 0xC0, 0xDE}\n\t\t_, err = handle.WriteAt(garbage, fileInfo.Size()-4)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\thandle.Close()\n\n\t\t_, err = ioutil.ReadAll(m)\n\t\tif err != rsa.ErrVerification {\n\t\t\tt.Fatal(\"read the corrupt file anyway\")\n\t\t}\n\t}\n}", "func (s *EdX25519PublicKey) Verify(b []byte) ([]byte, error) {\n\tif l := len(b); l < sign.Overhead {\n\t\treturn nil, errors.Errorf(\"not enough data for signature\")\n\t}\n\t_, ok := sign.Open(nil, b, s.publicKey)\n\tif !ok {\n\t\treturn nil, errors.Errorf(\"verify failed\")\n\t}\n\treturn b[sign.Overhead:], nil\n}" ]
[ "0.55068606", "0.5347167", "0.5318669", "0.5005839", "0.49518755", "0.49437165", "0.49308798", "0.49030274", "0.48570257", "0.48034772", "0.47937787", "0.47539333", "0.47513276", "0.47443518", "0.47344515", "0.4721497", "0.47032088", "0.4700939", "0.46931618", "0.4690987", "0.46634352", "0.46604353", "0.46514326", "0.46356413", "0.46355778", "0.45776367", "0.45531738", "0.45407537", "0.45393017", "0.4516118", "0.45079073", "0.45027256", "0.44675353", "0.44630358", "0.445276", "0.44512096", "0.4425275", "0.4420632", "0.4418978", "0.43967718", "0.4386546", "0.43861383", "0.43830606", "0.43727866", "0.43706852", "0.43617532", "0.43593952", "0.43342638", "0.4324576", "0.43205994", "0.4318245", "0.43166432", "0.43166405", "0.43097162", "0.4304376", "0.43017155", "0.42875385", "0.42812407", "0.42798564", "0.427552", "0.4274582", "0.42616138", "0.42558146", "0.42358768", "0.42289263", "0.42263618", "0.42255044", "0.4220061", "0.42198202", "0.42188624", "0.42167404", "0.42034936", "0.42029274", "0.4198132", "0.41939843", "0.4190247", "0.4188789", "0.41884562", "0.41884562", "0.41860223", "0.41857222", "0.41793323", "0.4174157", "0.4171264", "0.417114", "0.41708305", "0.41685474", "0.4167975", "0.4153338", "0.4153338", "0.4152206", "0.41512835", "0.4137426", "0.41342622", "0.41291937", "0.41270795", "0.41238248", "0.41195175", "0.41191414", "0.4116388" ]
0.57710606
0
String returns a string representation
func (p ParsedPanic) String() string { return fmt.Sprintf("%v\n%v", p.Reason, p.Content) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (s Library) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"UserID: \" + reform.Inspect(s.UserID, true)\n\tres[2] = \"VolumeID: \" + reform.Inspect(s.VolumeID, true)\n\tres[3] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[4] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (s CreateCanaryOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateAlgorithmOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Info) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func String() string {\n\toutput := output{\n\t\tRerun: Rerun,\n\t\tVariables: Variables,\n\t\tItems: Items,\n\t}\n\tvar err error\n\tvar b []byte\n\tif Indent == \"\" {\n\t\tb, err = json.Marshal(output)\n\t} else {\n\t\tb, err = json.MarshalIndent(output, \"\", Indent)\n\t}\n\tif err != nil {\n\t\tmessageErr := Errorf(\"Error in parser. Please report this output to https://github.com/drgrib/alfred/issues: %v\", err)\n\t\tpanic(messageErr)\n\t}\n\ts := string(b)\n\treturn s\n}", "func (enc *simpleEncoding) String() string {\n\treturn \"simpleEncoding(\" + enc.baseName + \")\"\n}", "func (s ReEncryptOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateQuickConnectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String() string {\n\treturn fmt.Sprintf(\n\t\t\"AppVersion = %s\\n\"+\n\t\t\t\"VCSRef = %s\\n\"+\n\t\t\t\"BuildVersion = %s\\n\"+\n\t\t\t\"BuildDate = %s\",\n\t\tAppVersion, VCSRef, BuildVersion, Date,\n\t)\n}", "func (s CreateFHIRDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateSafetyRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r Rooms) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (r *Registry) String() string {\n\tout := make([]string, 0, len(r.nameToObject))\n\tfor name, object := range r.nameToObject {\n\t\tout = append(out, fmt.Sprintf(\"* %s:\\n%s\", name, object.serialization))\n\t}\n\treturn strings.Join(out, \"\\n\\n\")\n}", "func (s CreateDatabaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProgramOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i NotMachine) String() string { return toString(i) }", "func (r SendAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s CreateHITTypeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r ReceiveAll) String() string {\n\tJSON, err := json.Marshal(r)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\treturn string(JSON)\n}", "func (s CreateUseCaseOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (e ExternalCfps) String() string {\n\tje, _ := json.Marshal(e)\n\treturn string(je)\n}", "func String() string {\n\treturn fmt.Sprintf(`Version: \"%s\", BuildTime: \"%s\", Commit: \"%s\" `, Version, BuildTime, Commit)\n}", "func (s CreateProjectVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateEntityOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func String(v interface{}) string {\n\treturn StringWithOptions(v, nil)\n}", "func (r Resiliency) String() string {\n\tb, _ := json.Marshal(r)\n\treturn string(b)\n}", "func (z Zamowienium) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateSolutionVersionOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSceneOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateThingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p polynomial) String() (str string) {\n\tfor _, m := range p.monomials {\n\t\tstr = str + \" \" + m.String() + \" +\"\n\t}\n\tstr = strings.TrimRight(str, \"+\")\n\treturn \"f(x) = \" + strings.TrimSpace(str)\n}", "func (s ExportProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateLanguageModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (clp CLP) String() string {\n\treturn fmt.Sprintf(\"%v%v%v%v\", clp.Creator, clp.Ticker, clp.Name, clp.ReserveRatio)\n}", "func (c CourseCode) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Botversionsummary) String() string {\n \n \n \n \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (r RoomOccupancies) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (c cargo) String() string {\n\treturn fmt.Sprintf(\"<ID: %d, %d x %d, %d area>\", c.item.id, c.item.l, c.item.w, c.area)\n}", "func String() string {\n\treturn StringWithSize(IntInRange(1, 8))\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateProjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateDataLakeOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (x XID) String() string {\n\tdst := make([]byte, 20)\n\tx.encode(dst)\n\treturn b2s(dst)\n}", "func (s StartPipelineReprocessingOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o QtreeCreateResponse) String() string {\n\treturn ToString(reflect.ValueOf(o))\n}", "func (s CreateDatastoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i Info) String() string {\n\ts, _ := i.toJSON()\n\treturn s\n}", "func (p person) String() string {\n\treturn fmt.Sprintf(\"Object %s: %d\", p.Name, p.Age)\n}", "func (o *Addshifttraderequest) String() string {\n \n \n \n \n o.AcceptableIntervals = []string{\"\"} \n\n j, _ := json.Marshal(o)\n str, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n return str\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r RoomOccupancy) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (t Test1s) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (z *Perplex) String() string {\n\ta := make([]string, 5)\n\ta[0] = \"(\"\n\ta[1] = fmt.Sprintf(\"%v\", &z.l)\n\tif z.r.Sign() == -1 {\n\t\ta[2] = fmt.Sprintf(\"%v\", &z.r)\n\t} else {\n\t\ta[2] = fmt.Sprintf(\"+%v\", &z.r)\n\t}\n\ta[3] = \"s\"\n\ta[4] = \")\"\n\treturn strings.Join(a, \"\")\n}", "func (s ResolveRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (g *Generic) String() string {\n\tparamStr := make([]string, len(g.Params))\n\tfor i, pr := range g.Params {\n\t\tparamStr[i] = pr.String()\n\t}\n\n\treturn fmt.Sprintf(\"{Header: %s, Params: %s}\",\n\t\tg.Header.String(),\n\t\tparamStr,\n\t)\n}", "func (s CreateModelCardOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s ResolutionTechniques) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotLocaleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateTrialComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (ak *Ak47) String() string {\n\treturn fmt.Sprintf(\"%s\\nOrigin: %s\", ak.Gun.String(), ak.Origin)\n}", "func (s CreateWaveOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (bits Bits) String() string", "func (p *Parms) String() string {\n\tout, _ := json.MarshalIndent(p, \"\", \"\\t\")\n\treturn string(out)\n}", "func (z Zamowienia) String() string {\n\tjz, _ := json.Marshal(z)\n\treturn string(jz)\n}", "func (s CreateComponentOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (a agent) String() string {\n\treturn fmt.Sprintf(\"[id=%v, name=%v, processVersion=%v, bundleVersion=%v, features=%v, zones=%v]\",\n\t\ta.id, a.name, a.processVersion, a.bundleVersion, a.features, a.zones)\n}", "func (g GetObjectOutput) String() string {\n\treturn helper.Prettify(g)\n}", "func (r Room) String() string {\n\tjr, _ := json.Marshal(r)\n\treturn string(jr)\n}", "func (t Terms) String() string {\n\tjt, _ := json.Marshal(t)\n\treturn string(jt)\n}", "func (s CreateAddressBookOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s RestoreFromRecoveryPointOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *Directrouting) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (s CreateContextOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateBotOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *RUT) String() string {\n\treturn r.Format(DefaultFormatter)\n}", "func (o *Digitalcondition) String() string {\n\tj, _ := json.Marshal(o)\n\tstr, _ := strconv.Unquote(strings.Replace(strconv.Quote(string(j)), `\\\\u`, `\\u`, -1))\n\n\treturn str\n}", "func (c CourseCodes) String() string {\n\tjc, _ := json.Marshal(c)\n\treturn string(jc)\n}", "func (book *Book) String() string {\n\treturn \tfmt.Sprintf(\"id=%d, subject=%v, title=%v, author=%v\\n\",book.id,book.subject,book.title,book.author)\n}", "func (s VerbatimString) ToString() (string, error) { return _verbatimString(s).ToString() }", "func (pp *Pubrec) String() string {\n\treturn fmt.Sprintf(\"<Pubrec ID=%d>\", pp.ID)\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetObjectOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *InterRecord) String() string {\n\tbuf := r.Bytes()\n\tdefer ffjson.Pool(buf)\n\n\treturn string(buf)\n}", "func (s *S) String() string {\n\treturn fmt.Sprintf(\"%s\", s) // Sprintf will call s.String()\n}", "func (s Sign) Str() string { return string(s[:]) }", "func (s DeleteRoomOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (d Decomposition) String() string {\n\treturn d.string(\"*\", \"(\", \")\")\n}", "func (s Template) String() string {\n\tres := make([]string, 12)\n\tres[0] = \"ID: \" + reform.Inspect(s.ID, true)\n\tres[1] = \"Title: \" + reform.Inspect(s.Title, true)\n\tres[2] = \"Description: \" + reform.Inspect(s.Description, true)\n\tres[3] = \"Type: \" + reform.Inspect(s.Type, true)\n\tres[4] = \"Note: \" + reform.Inspect(s.Note, true)\n\tres[5] = \"CoachID: \" + reform.Inspect(s.CoachID, true)\n\tres[6] = \"PlaceID: \" + reform.Inspect(s.PlaceID, true)\n\tres[7] = \"Weekday: \" + reform.Inspect(s.Weekday, true)\n\tres[8] = \"StartTime: \" + reform.Inspect(s.StartTime, true)\n\tres[9] = \"Duration: \" + reform.Inspect(s.Duration, true)\n\tres[10] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[11] = \"UpdatedAt: \" + reform.Inspect(s.UpdatedAt, true)\n\treturn strings.Join(res, \", \")\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateModelOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateActivationOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (i *Info) String() string {\n\tb, _ := json.Marshal(i)\n\treturn string(b)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s CreateResolverRuleOutput) String() string {\n\treturn awsutil.Prettify(s)\n}" ]
[ "0.72166216", "0.71055776", "0.705432", "0.705432", "0.70538026", "0.70451146", "0.70315385", "0.7019821", "0.6979171", "0.6975708", "0.6974538", "0.69690806", "0.69501877", "0.69498706", "0.69424176", "0.6922216", "0.6922148", "0.6921232", "0.6911624", "0.6908449", "0.69030976", "0.6901329", "0.6896361", "0.68959886", "0.6892253", "0.6888957", "0.6881654", "0.68719095", "0.6856193", "0.6852305", "0.68507004", "0.6839842", "0.682436", "0.6822008", "0.6821564", "0.6821493", "0.68207127", "0.6819531", "0.68187046", "0.68187046", "0.68165386", "0.6815109", "0.6813832", "0.6812856", "0.681273", "0.681273", "0.681273", "0.681273", "0.68126476", "0.6811522", "0.68065345", "0.68025315", "0.68004614", "0.67968994", "0.6795854", "0.67955387", "0.67936414", "0.6793047", "0.67922467", "0.6789337", "0.6787697", "0.67864114", "0.6786077", "0.67841417", "0.6783809", "0.67834973", "0.6783016", "0.6782864", "0.6779483", "0.67760843", "0.67747", "0.6773722", "0.6773611", "0.6773334", "0.6771014", "0.6768808", "0.6767695", "0.67671585", "0.67660934", "0.67646235", "0.6762231", "0.67613786", "0.6756281", "0.6755205", "0.6753454", "0.6753429", "0.6750668", "0.6750341", "0.67487997", "0.674828", "0.6746306", "0.6745622", "0.6743595", "0.6742438", "0.6741923", "0.6741531", "0.6741531", "0.6740601", "0.6740297", "0.674017", "0.674017" ]
0.0
-1
ParsePanic parses a panic output
func ParsePanic(panicContent string) *ParsedPanic { reason := "" prefix := "panic: " j := len(prefix) if len(panicContent) >= j && panicContent[0:j] == prefix { lines := strings.Split(panicContent, "\n") if len(lines) > 0 { reason = lines[0][j:] } } ret := ParsedPanic{} ret.Content = panicContent ret.Reason = reason return &ret }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Parse(bytes []byte) (result interface{}, err error) {\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tif parseErr, ok := r.(error); ok {\n\t\t\t\terr = parseErr\n\t\t\t} else {\n\t\t\t\terr = fmt.Errorf(\"unexpected panic: %v\", r)\n\t\t\t}\n\t\t}\n\t}()\n\treturn parsePanicUnsafe(bytes)\n}", "func ParseFatal(cfg *Configurator, tgt interface{}) {\n\tif cfg == nil {\n\t\tcfg = &Configurator{}\n\t}\n\n\tcfg.ParseFatal(tgt)\n}", "func (p ParsedPanic) String() string {\n\treturn fmt.Sprintf(\"%v\\n%v\", p.Reason, p.Content)\n}", "func (p *parser) recover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\t// Print the stack trace but do not inhibit the running application.\n\t\t\tbuf := make([]byte, 64<<10)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\n\t\t\tfmt.Fprintf(os.Stderr, \"parser panic: %v\\n%s\", e, buf)\n\t\t\t*errp = errUnexpected\n\t\t} else {\n\t\t\t*errp = e.(error)\n\t\t}\n\t}\n\tp.lex.close()\n}", "func (cfg *Configurator) ParseFatal(tgt interface{}) {\n\terr := cfg.Parse(tgt)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"Cannot load configuration file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n}", "func parseRecover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\tpanic(e)\n\t\t}\n\t\t*errp = e.(error)\n\t}\n\treturn\n}", "func TestConfig_ParsePanic(t *testing.T) {\n\tci.Parallel(t)\n\n\tc, err := ParseConfigFile(\"./testdata/obj-len-one.hcl\")\n\tif err != nil {\n\t\tt.Fatalf(\"parse error: %s\\n\", err)\n\t}\n\n\td, err := ParseConfigFile(\"./testdata/obj-len-one.json\")\n\tif err != nil {\n\t\tt.Fatalf(\"parse error: %s\\n\", err)\n\t}\n\n\trequire.EqualValues(t, c, d)\n}", "func (a *syslogServers) Parse(input string) error {\n\ta.data = nil\n\ta.stdout = false\n\tfor _, syslogLine := range strings.Split(input, \"\\n\") {\n\t\tif syslogLine == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\t// strip spaces\n\t\tsyslogLine = strings.Join(strings.Fields(syslogLine), \"\")\n\t\t// parse log params\n\t\tlogParams := make(map[string]string)\n\t\tfor _, param := range strings.Split(syslogLine, \",\") {\n\t\t\tif param == \"\" {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tparts := strings.Split(param, \":\")\n\t\t\t// param should be key: value\n\t\t\tif len(parts) == 2 {\n\t\t\t\tlogParams[parts[0]] = parts[1]\n\t\t\t} else {\n\t\t\t\tlogger.Errorf(\"incorrect syslog param: '%s' in '%s'\", param, syslogLine)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// populate annotation data\n\t\tlogData := new(types.Log)\n\t\tif address, ok := logParams[\"address\"]; !ok {\n\t\t\tlogger.Errorf(\"incorrect syslog Line: no address param in '%s'\", syslogLine)\n\t\t\tcontinue\n\t\t} else {\n\t\t\tlogData.Address = address\n\t\t}\n\t\tfor k, v := range logParams {\n\t\t\tswitch strings.ToLower(k) {\n\t\t\tcase \"address\":\n\t\t\t\tif v == \"stdout\" {\n\t\t\t\t\ta.stdout = true\n\t\t\t\t}\n\t\t\tcase \"port\":\n\t\t\t\tif logParams[\"address\"] != \"stdout\" {\n\t\t\t\t\tlogData.Address += \":\" + v\n\t\t\t\t}\n\t\t\tcase \"length\":\n\t\t\t\tif length, errConv := strconv.Atoi(v); errConv == nil {\n\t\t\t\t\tlogData.Length = int64(length)\n\t\t\t\t}\n\t\t\tcase \"format\":\n\t\t\t\tlogData.Format = v\n\t\t\tcase \"facility\":\n\t\t\t\tlogData.Facility = v\n\t\t\tcase \"level\":\n\t\t\t\tlogData.Level = v\n\t\t\tcase \"minlevel\":\n\t\t\t\tlogData.Level = v\n\t\t\tdefault:\n\t\t\t\tlogger.Errorf(\"unkown syslog param: '%s' in '%s' \", k, syslogLine)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\ta.data = append(a.data, logData)\n\t}\n\tif len(a.data) == 0 {\n\t\treturn errors.New(\"could not parse syslog-server annotation\")\n\t}\n\treturn nil\n}", "func panicRecover(input *models.RunningInput) {\n\tif err := recover(); err != nil {\n\t\ttrace := make([]byte, 2048)\n\t\truntime.Stack(trace, true)\n\t\tlog.Printf(\"E! FATAL: [%s] panicked: %s, Stack:\\n%s\",\n\t\t\tinput.LogName(), err, trace)\n\t\tlog.Println(\"E! PLEASE REPORT THIS PANIC ON GITHUB with \" +\n\t\t\t\"stack trace, configuration, and OS information: \" +\n\t\t\t\"https://github.com/influxdata/telegraf/issues/new/choose\")\n\t}\n}", "func (s *scanner) Fatal(args ...interface{}) {\n\ts.T.Fatalf(\"%s: %s\", s.pos(), fmt.Sprint(args...))\n}", "func isPanicLine(text string) bool {\n\treturn regexPanic.MatchString(text)\n}", "func tcPanic(n *ir.UnaryExpr) ir.Node {\n\tn.X = Expr(n.X)\n\tn.X = AssignConv(n.X, types.Types[types.TINTER], \"argument to panic\")\n\tif n.X.Type() == nil {\n\t\tn.SetType(nil)\n\t\treturn n\n\t}\n\treturn n\n}", "func hackParse(file string) (map[string]interface{}, error) {\n\tcv2 := make(map[string]interface{})\n\n\taliasRegexp, err := regexp.Compile(`\\s*(.+?)\\s+AS\\s+(.+?)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\ttagsRegexp, err := regexp.Compile(`\\s*(.+?)\\s*:\\s*\\[(.+?)\\]\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\trangeRegexp, err := regexp.Compile(`(\\d+)-(\\d+)`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\tsectionRegexp, err := regexp.Compile(`\\s*\\\\\\\\\\s*(.+?)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\tdottedDateLineRegexp, err := regexp.Compile(`\\s*(.+?)\\.(.+?)\\s*:\\s*(\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\tdateLineRegexp, err := regexp.Compile(`\\s*(.+?)\\s*:\\s*(\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\tdottedRegexp, err := regexp.Compile(`\\s*(.+?)\\.(.+?)\\s*:\\s*(.+)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\totherRegexp, err := regexp.Compile(`\\s*(.+?)\\s*:\\s*(.+)\\s*\\n`)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\n\tb, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn cv2, err\n\t}\n\ts := string(b)\n\tinComment := false\n\tinEscape := false\n\tinString := false\n\tpendingString := \"\"\n\tpendingComment := \"\"\n\tpendingUnknown := \"\"\n\tpendingEscape := \"\"\n\tcurrentSection := \"\"\n\tlastString := \"\"\n\tlastEscape := \"\"\n\tfor index, runeValue := range s {\n\t\tif runeValue == '/' && s[index+1] == '*' {\n\t\t\tinComment = true\n\t\t\tlog.Println(\"inComment: \", inComment)\n\t\t}\n\t\t// TODO: will break if index+1>len\n\t\tif runeValue == '*' && s[index+1] == '/' && inComment {\n\t\t\tinComment = false\n\t\t\tlog.Println(\"inComment: \", inComment)\n\t\t\t//log.Println(\"comment: \", pendingComment)\n\t\t\tpendingComment = \"\"\n\t\t}\n\t\tif inComment {\n\t\t\tpendingComment += string(runeValue)\n\t\t\tcontinue\n\t\t}\n\n\t\tif runeValue == '\\\\' && s[index+1] == '{' && !inEscape {\n\t\t\tinEscape = true\n\t\t\tlog.Println(\"inEscape: \", inEscape)\n\t\t}\n\t\t// TODO: will break if index+1>len\n\t\tif runeValue == '}' && inEscape {\n\t\t\tinEscape = false\n\t\t\tlog.Println(\"inEscape: \", inEscape)\n\t\t\tlastEscape = pendingEscape[2:]\n\t\t\tlog.Println(\"escape: \", lastEscape)\n\t\t\tpendingEscape = \"\"\n\t\t}\n\t\tif inEscape {\n\t\t\tpendingEscape += string(runeValue)\n\t\t\tcontinue\n\t\t}\n\n\t\tif runeValue == '\"' {\n\t\t\tif inString {\n\t\t\t\tinString = false\n\t\t\t\t// TODO: will break on 0 length strings\n\t\t\t\tlastString = pendingString[1:]\n\t\t\t\tlog.Println(\"lastString:\", lastString)\n\t\t\t\tpendingString = \"\"\n\t\t\t} else {\n\t\t\t\tinString = true\n\t\t\t}\n\t\t\tlog.Println(\"inString:\", inString)\n\t\t}\n\n\t\tif inString {\n\t\t\tpendingString += string(runeValue)\n\t\t} else if inEscape {\n\t\t\tpendingEscape += string(runeValue)\n\t\t} else {\n\t\t\tpendingUnknown += string(runeValue)\n\t\t}\n\n\t\tfoundSection := sectionRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundSection) > 0 {\n\t\t\tcurrentSection = strings.Trim(foundSection[0][1], \"\\n \")\n\t\t\tlog.Printf(\"foundSection %s\", currentSection)\n\t\t\tif _, ok := cv2[currentSection]; !ok {\n\t\t\t\tcv2[currentSection] = make(map[string]interface{})\n\t\t\t}\n\t\t\tpendingUnknown = \"\"\n\t\t}\n\n\t\tif currentSection == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\tfoundAs := aliasRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundAs) > 0 {\n\t\t\tvalue := strings.Replace(strings.Trim(foundAs[0][2], \" \"), `\"`, lastString, 1)\n\t\t\tvalue = strings.Replace(value, `}`, `\\{`+lastEscape+`}`, 1)\n\t\t\tlog.Printf(\"foundAs %s AS %s\", foundAs[0][1], value)\n\t\t\tpendingUnknown = \"\"\n\n\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\tif _, ok := ref[\"cv2_aliases\"]; !ok {\n\t\t\t\tref[\"cv2_aliases\"] = make(map[string]string)\n\t\t\t}\n\n\t\t\tref2 := ref[\"cv2_aliases\"].(map[string]string)\n\t\t\tref2[foundAs[0][1]] = value\n\t\t}\n\n\t\tfoundTag := tagsRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundTag) > 0 {\n\t\t\tvalue := strings.Replace(strings.Trim(foundTag[0][2], \" \"), `\"`, lastString, 1)\n\t\t\tvalue = strings.Replace(value, `}`, `\\{`+lastEscape+`}`, 1)\n\t\t\tlog.Printf(\"foundTag %s AS %s\", foundTag[0][1], value)\n\t\t\tpendingUnknown = \"\"\n\t\t\tfoundRange := rangeRegexp.FindAllStringSubmatch(value, -1)\n\t\t\tif len(foundRange) > 0 {\n\t\t\t\tlog.Printf(\"foundRange %s to %s\", foundRange[0][1], foundRange[0][2])\n\n\t\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\t\tif _, ok := ref[\"cv2_ranges\"]; !ok {\n\t\t\t\t\tref[\"cv2_ranges\"] = make(map[string]string)\n\t\t\t\t}\n\n\t\t\t\tref2 := ref[\"cv2_ranges\"].(map[string]string)\n\t\t\t\tref2[foundTag[0][1]] = value\n\n\t\t\t} else {\n\t\t\t\t// TODO: make this robust\n\t\t\t\tvalue = strings.Replace(value, \" ,\", \",\", -1)\n\t\t\t\tvalue = strings.Replace(value, \", \", \",\", -1)\n\t\t\t\tenums := strings.Split(value, \",\")\n\t\t\t\tlog.Println(\"Enums are \")\n\t\t\t\tfor _, enum := range enums {\n\t\t\t\t\tlog.Println(\"\\t\", strings.Trim(enum, \" \"))\n\t\t\t\t}\n\n\t\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\t\tif _, ok := ref[\"cv2_enums\"]; !ok {\n\t\t\t\t\tref[\"cv2_enums\"] = make(map[string][]string)\n\t\t\t\t}\n\n\t\t\t\tref2 := ref[\"cv2_enums\"].(map[string][]string)\n\t\t\t\tref2[foundTag[0][1]] = enums\n\t\t\t}\n\t\t}\n\n\t\tfoundDottedDateLine := dottedDateLineRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundDottedDateLine) > 0 {\n\t\t\tt, err := time.Parse(\"02.01.2006\", foundDottedDateLine[0][3])\n\t\t\tif err != nil {\n\t\t\t\treturn cv2, err\n\t\t\t}\n\t\t\tlog.Printf(\"foundDottedDateLine %s.%s %s\", foundDottedDateLine[0][1], foundDottedDateLine[0][2], t.Format(\"01/02/2006\"))\n\t\t\tpendingUnknown = \"\"\n\n\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\tif _, ok := ref[\"cv2_values\"]; !ok {\n\t\t\t\tref[\"cv2_values\"] = make(map[string]interface{})\n\t\t\t}\n\n\t\t\tref2 := ref[\"cv2_values\"].(map[string]interface{})\n\t\t\tif _, ok := ref2[foundDottedDateLine[0][1]]; !ok {\n\t\t\t\tref2[foundDottedDateLine[0][1]] = make(map[string]string)\n\t\t\t}\n\n\t\t\tref3 := ref2[foundDottedDateLine[0][1]].(map[string]string)\n\t\t\tref3[foundDottedDateLine[0][2]] = t.Format(\"01/02/2006\")\n\t\t}\n\n\t\tfoundDateLine := dateLineRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundDateLine) > 0 {\n\t\t\tt, err := time.Parse(\"02.01.2006\", foundDateLine[0][2])\n\t\t\tif err != nil {\n\t\t\t\treturn cv2, err\n\t\t\t}\n\t\t\tlog.Printf(\"foundDateLine %s %s\", foundDateLine[0][1], t.Format(\"01/02/2006\"))\n\t\t\tpendingUnknown = \"\"\n\n\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\tif _, ok := ref[\"cv2_values\"]; !ok {\n\t\t\t\tref[\"cv2_values\"] = make(map[string]string)\n\t\t\t}\n\n\t\t\tref2 := ref[\"cv2_values\"].(map[string]string)\n\t\t\tref2[foundDateLine[0][1]] = t.Format(\"01/02/2006\")\n\t\t}\n\n\t\tfoundDotted := dottedRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundDotted) > 0 {\n\t\t\tvalue := strings.Replace(strings.Trim(foundDotted[0][3], \" \"), `\"`, lastString, 1)\n\t\t\tvalue = strings.Replace(value, `}`, `\\{`+lastEscape+`}`, 1)\n\t\t\tlog.Printf(\"foundDotted %s.%s: %s\", foundDotted[0][1], foundDotted[0][2], value)\n\t\t\tpendingUnknown = \"\"\n\n\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\tif _, ok := ref[\"cv2_values\"]; !ok {\n\t\t\t\tref[\"cv2_values\"] = make(map[string]interface{})\n\t\t\t}\n\n\t\t\tref2 := ref[\"cv2_values\"].(map[string]interface{})\n\t\t\tif _, ok := ref2[foundDotted[0][1]]; !ok {\n\t\t\t\tref2[foundDotted[0][1]] = make(map[string]string)\n\t\t\t}\n\n\t\t\tref3 := ref2[foundDotted[0][1]].(map[string]string)\n\t\t\tref3[foundDotted[0][2]] = value\n\t\t}\n\n\t\tfoundOther := otherRegexp.FindAllStringSubmatch(pendingUnknown, -1)\n\t\tif len(foundOther) > 0 {\n\t\t\tvalue := strings.Replace(strings.Trim(foundOther[0][2], \" \"), `\"`, lastString, 1)\n\t\t\tvalue = strings.Replace(value, `}`, `\\{`+lastEscape+`}`, 1)\n\t\t\tlog.Printf(\"foundOther %s: %s\", foundOther[0][1], value)\n\t\t\tpendingUnknown = \"\"\n\n\t\t\tref := cv2[currentSection].(map[string]interface{})\n\t\t\tif _, ok := ref[\"cv2_values\"]; !ok {\n\t\t\t\tref[\"cv2_values\"] = make(map[string]string)\n\t\t\t}\n\n\t\t\tref2 := ref[\"cv2_values\"].(map[string]string)\n\t\t\tref2[foundOther[0][1]] = value\n\t\t\tlog.Printf(\"%s %s %s\\n\", currentSection, foundOther[0][1], value)\n\t\t}\n\t\t//log.Println(\"pendingUnknown\", pendingUnknown)\n\t}\n\n\treturn cv2, nil\n}", "func errorUnrecognized(p *Parser, text string, next statefn) statefn {\n\tp.logger.Printf(\"unrecognized: %s\\n\", text)\n\treturn next\n}", "func handlePanic(resp http.ResponseWriter, status int) {\n\tif p := recover(); p != nil {\n\n\t\tmessageFmt := \"Unhandled panic: %s\"\n\t\tvar err error\n\n\t\tswitch p.(type) {\n\t\tcase nil:\n\t\t\t// normal case, just ignore.\n\t\tcase string:\n\t\t\tmessageFmt = p.(string)\n\t\t\terr = errors.New(messageFmt)\n\t\tcase error:\n\t\t\terr = p.(error)\n\t\tdefault:\n\t\t\terr = errors.New(fmt.Sprint(p))\n\t\t}\n\n\t\tif err != nil {\n\t\t\treportError(err, messageFmt, resp, status)\n\t\t}\n\t}\n}", "func (c *icmpCollector) Parse(ostype string, output string) (Icmp, error) {\n\t// if ostype != rpc.IOSXE && ostype != rpc.NXOS && ostype != rpc.IOS {\n\t// \treturn nil, errors.New(\"'show interface' is not implemented for \" + ostype)\n\t// }\n\n\ttargetRegexp := regexp.MustCompile(`^\\s*--- (.*) ping statistics ---.*$`) // target\n\tpacketLossRegexp := regexp.MustCompile(`^\\s*(?:(?:\\d+) packets transmitted, (?:\\d+) received, )?((?:[1-9][\\d]*|0)(?:\\.\\d+)?)% packet loss.*$`) // packet loss rate\n\trttRegexp := regexp.MustCompile(`^\\s*(?:rtt|round-trip)? min/avg/max(?:/mdev)? = ((?:[1-9][\\d]*|0)(?:\\.[\\d]+)?)/((?:[1-9][\\d]*|0)(?:\\.[\\d]+)?)/((?:[1-9][\\d]*|0)(?:\\.[\\d]+)?)(?:/.*)? ms.*$`)\n\n\tcurrent := Icmp{}\n\tlines := strings.Split(output, \"\\n\")\n\tfor _, line := range lines {\n\t\tif matches := targetRegexp.FindStringSubmatch(line); matches != nil {\n\t\t\tcurrent = Icmp{\n\t\t\t\tTarget: matches[1],\n\t\t\t}\n\t\t}\n\t\tif current == (Icmp{}) {\n\t\t\tcontinue\n\t\t}\n\t\tif matches := packetLossRegexp.FindStringSubmatch(line); matches != nil {\n\t\t\tcurrent.PacketLoss = util.Str2float64(matches[1])\n\t\t\tif current.PacketLoss == 100 {\n\t\t\t\tcurrent.PingStatus = \"down\"\n\t\t\t} else {\n\t\t\t\tcurrent.PingStatus = \"up\"\n\t\t\t}\n\t\t}\n\t\tif matches := rttRegexp.FindStringSubmatch(line); matches != nil {\n\t\t\tcurrent.RttMin = util.Str2float64(matches[1])\n\t\t\tcurrent.RttAvg = util.Str2float64(matches[2])\n\t\t\tcurrent.RttMax = util.Str2float64(matches[3])\n\t\t}\n\n\t}\n\treturn current, nil\n}", "func ParseDie(notation string) (d Die, err error) {\n\tmatches := dieRegex.FindStringSubmatch(notation)\n\n\tif len(matches) != 2 {\n\t\terr = fmt.Errorf(\"parsing %q: invalid syntax\", notation)\n\t} else {\n\t\tvar n int\n\t\tn, err = strconv.Atoi(matches[1])\n\n\t\tif n < 2 {\n\t\t\terr = TooFewSidesError(n)\n\t\t}\n\n\t\td = Die(n)\n\t}\n\n\treturn\n}", "func HandlePanic(name string, err *error) {\n\tif r := recover(); r != nil {\n\n\t\tlog.RootLogger().Warnf(\"%s: PANIC Occurred : %v\\n\", name, r)\n\n\t\t// todo: useful for debugging\n\t\tlog.RootLogger().Debugf(\"StackTrace: %s\", debug.Stack())\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}\n}", "func recoverPanic(w http.ResponseWriter, panicSrc string) {\n\tif r := recover(); r != nil {\n\t\tgenericMsg := fmt.Sprintf(panicMessageTmpl, panicSrc)\n\t\tfmt.Fprintf(os.Stderr, fmt.Sprintf(\"%s\\npanic message: %v\\nstack trace: %s\", genericMsg, r, debug.Stack()))\n\t\tif w != nil {\n\t\t\twriteHTTPErrorResponse(w, http.StatusInternalServerError, crashStatus, genericMsg)\n\t\t}\n\t}\n}", "func (tm *TabletManager) HandleRPCPanic(ctx context.Context, name string, args, reply any, verbose bool, err *error) {\n\t// panic handling\n\tif x := recover(); x != nil {\n\t\tlog.Errorf(\"TabletManager.%v(%v) on %v panic: %v\\n%s\", name, args, topoproto.TabletAliasString(tm.tabletAlias), x, tb.Stack(4))\n\t\t*err = fmt.Errorf(\"caught panic during %v: %v\", name, x)\n\t\treturn\n\t}\n\n\t// quick check for fast path\n\tif !verbose && *err == nil {\n\t\treturn\n\t}\n\n\t// we gotta log something, get the source\n\tfrom := \"\"\n\tci, ok := callinfo.FromContext(ctx)\n\tif ok {\n\t\tfrom = ci.Text()\n\t}\n\n\tif *err != nil {\n\t\t// error case\n\t\tlog.Warningf(\"TabletManager.%v(%v)(on %v from %v) error: %v\", name, args, topoproto.TabletAliasString(tm.tabletAlias), from, (*err).Error())\n\t\t*err = vterrors.Wrapf(*err, \"TabletManager.%v on %v error: %v\", name, topoproto.TabletAliasString(tm.tabletAlias), (*err).Error())\n\t} else {\n\t\t// success case\n\t\tlog.Infof(\"TabletManager.%v(%v)(on %v from %v): %#v\", name, args, topoproto.TabletAliasString(tm.tabletAlias), from, reply)\n\t}\n}", "func parseError(m mxj.Map) string {\n\terrMsg, err := m.ValueForPathString(\"Envelope.Body.Fault.faultstring\")\n\tif err != nil {\n\t\treturn m.StringIndentNoTypeInfo(0)\n\t}\n\n\treturn errMsg\n}", "func HandleErrPANIC(err error, text string) {\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %v at %v\", err, text)\n\t\tpanic(err)\n\t}\n}", "func (c *Controller) HandlePanic(v interface{}) {\n status := http.StatusInternalServerError\n switch e := v.(type) {\n case *perror.Error:\n status = e.Status()\n c.Json(EmptyObject, status, e.Message())\n default:\n c.Json(EmptyObject, status)\n }\n\n c.Context().Error(\"%s, trace[%s]\", util.ToString(v), util.PanicTrace(TraceMaxDepth, false))\n}", "func errFromPanic(p interface{}) error {\n\tif err, ok := p.(error); ok {\n\t\treturn err\n\t}\n\treturn fmt.Errorf(\"panic: %v\", p)\n}", "func errFromPanic(p interface{}) error {\n\tif err, ok := p.(error); ok {\n\t\treturn err\n\t}\n\treturn fmt.Errorf(\"panic: %v\", p)\n}", "func (ev *evaluator) recover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\t// Print the stack trace but do not inhibit the running application.\n\t\t\tbuf := make([]byte, 64<<10)\n\t\t\tbuf = buf[:runtime.Stack(buf, false)]\n\n\t\t\tlog.Errorf(\"parser panic: %v\\n%s\", e, buf)\n\t\t\t*errp = fmt.Errorf(\"unexpected error\")\n\t\t} else {\n\t\t\t*errp = e.(error)\n\t\t}\n\t}\n}", "func TestPanic(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic as expected\")\n\t\t}\n\t}()\n\n\tr, w, _ := os.Pipe()\n\tSetOutputs(Output{\n\t\tName: \"test\",\n\t\tWriter: w,\n\t\tLevels: level.Default,\n\t})\n\n\tPanic(\"Test fatal\")\n\toutC := make(chan string)\n\tgo ioCopy(r, outC)\n\tw.Close()\n\tout := <-outC\n\n\texpected := \"Test fatal\"\n\tn := level.Labels[level.Panic]\n\tif !strings.Contains(out, expected) || !strings.Contains(out, n) {\n\t\tt.Errorf(\"Result `%s` doesn't contains `%s` and `%s`\",\n\t\t\tout, expected, n)\n\t}\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t} else if err != nil && *err != nil {\n\t\tfmt.Printf(\"%s : ERROR : %v\\n\", functionName, *err)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\t}\n}", "func handlePanic() {\n\tif r := recover(); r != nil {\n\t\tlog.Printf(\"panic recovered: %s \\n %s\", r, debug.Stack())\n\t}\n}", "func TestPanicf(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic as expected\")\n\t\t}\n\t}()\n\n\tr, w, _ := os.Pipe()\n\tSetOutputs(Output{\n\t\tName: \"test\",\n\t\tWriter: w,\n\t\tLevels: level.Default,\n\t})\n\n\tPanicf(\"Test fatal %s\", \"formatted\")\n\toutC := make(chan string)\n\tgo ioCopy(r, outC)\n\tw.Close()\n\tout := <-outC\n\n\texpected := \"Test fatal formatted\"\n\tn := level.Labels[level.Panic]\n\tif !strings.Contains(out, expected) || !strings.Contains(out, n) {\n\t\tt.Errorf(\"Result `%s` doesn't contains `%s` and `%s`\",\n\t\t\tout, expected, n)\n\t}\n}", "func DumpPanicTrace(kb int) {\n\ts := []byte(\"/src/runtime/panic.go\")\n\te := []byte(\"\\ngoroutine \")\n\tline := []byte(\"\\n\")\n\tstack := make([]byte, kb<<10) // 4KB\n\tlength := runtime.Stack(stack, true)\n\tstart := bytes.Index(stack, s)\n\tstack = stack[start:length]\n\tstart = bytes.Index(stack, line) + 1\n\tstack = stack[start:]\n\tend := bytes.LastIndex(stack, line)\n\tif end != -1 {\n\t\tstack = stack[:end]\n\t}\n\tend = bytes.Index(stack, e)\n\tif end != -1 {\n\t\tstack = stack[:end]\n\t}\n\t_, _ = os.Stdout.Write(bytes.TrimRight(stack, \"\\n\"))\n}", "func (s *BasePCREListener) ExitParse(ctx *ParseContext) {}", "func (p Packet) Panic(v ...interface{}) {\n\tp = p.setOptionalData(v)\n\tp.setDefaultTag(\"panic\")\n\tgo (wrapper.Packet(p)).Panic()\n}", "func catchPanic(err *error, functionName string) {\n\tif r := recover(); r != nil {\n\t\tfmt.Printf(\"%s : PANIC Defered : %v\\n\", functionName, r)\n\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\tfmt.Printf(\"%s : Stack Trace : %s\", functionName, string(buf))\n\n\t\tif err != nil {\n\t\t\t*err = fmt.Errorf(\"%v\", r)\n\t\t}\n\t}\n}", "func TestParsingBadPacketDropLog(t *testing.T) {\n\tchannel := make(chan PacketDrop)\n\t// testing bad log without source IP\n\tcurTime := time.Now().Format(PacketDropLogTimeLayout)\n\ttestLog1 := fmt.Sprintf(\"%s %s %s %s\", curTime, testHostname, testLogPrefix, testDstIP)\n\terr := parse(testLogPrefix, testLog1, channel)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error, but got error nil!\")\n\t}\n\t// testing bad log without destination IP\n\ttestLog2 := fmt.Sprintf(\"%s %s %s %s\", curTime, testHostname, testLogPrefix, testSrcIP)\n\terr = parse(testLogPrefix, testLog2, channel)\n\tif err == nil {\n\t\tt.Fatalf(\"Expected error, but got error nil!\")\n\t}\n}", "func (p *LogParser) Parse(address string, b []byte) {\n\t//p.Result = map[string]interface{}{}\n\tp.Raw = b\n\tvar r Parser\n\n\tif format := p.formatByAddress[address]; format != nil {\n\t\tr = format()\n\t} else {\n\t\tr = CreateParser(p.fmt)\n\t}\n\tp.Result, err = r.Parse(b)\n\tif err != nil {\n\t\tp.Result = map[string]interface{}{\n\t\t\t\"priority\": 0,\n\t\t\t\"facility\": 0,\n\t\t\t\"severity\": 0,\n\t\t\t\"version\": NO_VERSION,\n\t\t\t\"timestamp\": time.Now(),\n\t\t\t\"message\": string(b),\n\t\t}\n\t}\n}", "func parseLogEntry(line []byte, statePerPod map[string]*PodState) *DetectedEntry {\n\tfor probe, regex := range regexMap {\n\t\tif regex.Match(line) {\n\t\t\tmatchResult := regex.FindSubmatch(line)\n\t\t\tif matchResult != nil {\n\t\t\t\tts, err := time.Parse(kubeletLogTimeFormat, currentYear+\" \"+string(matchResult[1]))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(\"Error: can not parse log timestamp in kubelet.log\")\n\t\t\t\t}\n\t\t\t\tswitch probe {\n\t\t\t\t// 'container starts' reported by PLEG event.\n\t\t\t\tcase probeContainerStartPLEG:\n\t\t\t\t\t{\n\t\t\t\t\t\tpod := string(matchResult[2])\n\t\t\t\t\t\tif _, ok := statePerPod[pod]; !ok {\n\t\t\t\t\t\t\tstatePerPod[pod] = &PodState{ContainerNrPLEG: 1}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstatePerPod[pod].ContainerNrPLEG++\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// In our test the pod contains an infra container and test container.\n\t\t\t\t\t\tswitch statePerPod[pod].ContainerNrPLEG {\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tprobe = probeInfraContainerPLEG\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tprobe = probeTestContainerPLEG\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t// 'container starts' detected by PLEG reported in Kublet SyncPod.\n\t\t\t\tcase probeContainerStartPLEGSync:\n\t\t\t\t\t{\n\t\t\t\t\t\tpod := string(matchResult[2])\n\t\t\t\t\t\tif _, ok := statePerPod[pod]; !ok {\n\t\t\t\t\t\t\tstatePerPod[pod] = &PodState{ContainerNrPLEGSync: 1}\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tstatePerPod[pod].ContainerNrPLEGSync++\n\t\t\t\t\t\t}\n\t\t\t\t\t\t// In our test the pod contains an infra container and test container.\n\t\t\t\t\t\tswitch statePerPod[pod].ContainerNrPLEGSync {\n\t\t\t\t\t\tcase 1:\n\t\t\t\t\t\t\tprobe = probeInfraContainerPLEGSync\n\t\t\t\t\t\tcase 2:\n\t\t\t\t\t\t\tprobe = probeTestContainerPLEGSync\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t// 'pod running' reported by Kubelet status manager.\n\t\t\t\tcase probeStatusUpdate:\n\t\t\t\t\t{\n\t\t\t\t\t\t// We only trace the first status update event.\n\t\t\t\t\t\tpod := string(matchResult[2])\n\t\t\t\t\t\tif _, ok := statePerPod[pod]; !ok {\n\t\t\t\t\t\t\tstatePerPod[pod] = &PodState{}\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif statePerPod[pod].StatusUpdated {\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t\tstatePerPod[pod].StatusUpdated = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn &DetectedEntry{Probe: probe, Timestamp: ts}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}", "func HandlePanic(c lars.Context, trace []byte) {\n\n\t// redirect to or directly render friendly error page\n}", "func TestNginxTimeParse(t *testing.T) {\n\tp := &Parser{\n\t\tPatterns: []string{\"%{NGINX_LOG}\"},\n\t}\n\tassert.NoError(t, p.compile())\n\n\tm, err := p.parse(`192.168.45.53 - - [05/Apr/2017:17:25:06 +0800] \"POST /v2/repos/kodo_z0_app_pfdstg/data HTTP/1.1\" 200 497 2 \"-\" \"Go 1.1 package http\" \"-\" 192.168.160.1:80 pipeline.qiniu.io KBkAAD7W6-UfdrIU 0.139`)\n\tassert.NoError(t, err)\n\trequire.NotNil(t, m)\n\tassert.Equal(t, \"2017-04-05T17:25:06+08:00\", m[\"ts\"])\n}", "func tryPanic() {\n\tpanic(\"panik ga?! panik ga?! ya panik lah masa ngga!\")\n}", "func Panic(v ...interface{}) {\n s := sout(v...)\n Std.Output(LevelPanic, CallDepth, s)\n panic(s)\n}", "func (_IStaking *IStakingFilterer) ParseUnregistered(log types.Log) (*IStakingUnregistered, error) {\n\tevent := new(IStakingUnregistered)\n\tif err := _IStaking.contract.UnpackLog(event, \"Unregistered\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func (p *parser) recover(errp *error) {\n\te := recover()\n\tif e != nil {\n\t\tif _, ok := e.(runtime.Error); ok {\n\t\t\tpanic(e)\n\t\t}\n\t\tif p != nil {\n\t\t\tp.stopParse()\n\t\t}\n\t\t*errp = e.(error)\n\t}\n\treturn\n}", "func (pe *PanicError) String() string {\n\treturn fmt.Sprintf(\"%v\\r\\n%s\", pe.Panic, pe.Stack)\n}", "func (e HandlerPanicError) Format(s fmt.State, verb rune) {\n\tswitch verb {\n\tcase 's':\n\t\t_, _ = io.WriteString(s, e.Error())\n\tcase 'v':\n\t\t_, _ = io.WriteString(s, e.Error())\n\t\tfor _, f := range e.stack {\n\t\t\t_, _ = io.WriteString(s, \"\\n\")\n\t\t\tif s.Flag('+') {\n\t\t\t\t_, _ = fmt.Fprintf(s, \"%s\\n\\t\", f.Function)\n\t\t\t}\n\t\t\t_, _ = fmt.Fprintf(s, \"%s:%d\", f.File, f.Line)\n\t\t}\n\t}\n}", "func logpanic(msg, gold string) {\n\tpanic(fmt.Sprintf(\"Malformed log format string. %s.\\n%s\", msg, gold))\n}", "func (s *errDeal) Panic(a ...interface{}) {\n\ts.once.Do(s.initPath)\n\n\tnow := time.Now() //获取当前时间\n\tpid := os.Getpid() //获取进程ID\n\ttimeStr := now.Format(\"2006-01-02\") //设定时间格式\n\tfname := fmt.Sprintf(\"%s/panic_%s-%x.log\", s._path, timeStr, pid) //保存错误信息文件名:程序名-进程ID-当前时间(年月日时分秒)\n\tfmt.Println(\"panic to file \", fname)\n\n\tf, err := os.OpenFile(fname, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0666)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\n\tf.WriteString(\"=========================\" + now.Format(\"2006-01-02 15:04:05 ========================= \\r\\n\"))\n\tf.WriteString(getStr(a...)) //输出堆栈信息\n\tf.WriteString(\"=========================end=========================\")\n}", "func (h *HSTIMParser) ParsePatient(msg []byte) (HSTIMPatient, error) {\n\tpatient := HSTIMPatient{}\n\tpatient.SequenceNumber = 1\n\n\t// Verify the first character is `P`, which indicates it's a patient record\n\t// Probably redundant\n\tif msg[0] != 'P' {\n\t\treturn patient, &ParseError{fmt.Sprintf(\"Not a patient record\")}\n\t}\n\n\tmsgStr := removeTrailingValues(msg)\n\n\tsplits := strings.Split(msgStr[2:], \"|\")\n\tif len(splits) != 25 {\n\t\treturn patient, &ParseError{fmt.Sprintf(\"Expected 25 fields, got %d\", len(splits))}\n\t}\n\n\tif splits[0] != \"1\" {\n\t\treturn patient, &ParseError{\"Sequence number should always be 1\"}\n\t}\n\n\tpatient.PatientID = splits[1]\n\tpatient.Location = splits[24]\n\n\treturn patient, nil\n}", "func (_Registry *RegistryFilterer) ParseOperatorContractPanicButtonUpdated(log types.Log) (*RegistryOperatorContractPanicButtonUpdated, error) {\n\tevent := new(RegistryOperatorContractPanicButtonUpdated)\n\tif err := _Registry.contract.UnpackLog(event, \"OperatorContractPanicButtonUpdated\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func ParseMessage_KLog(boot_ts time.Time, data string) (syslog5424.Message,error) {\n\tlog.SetFlags(log.Ltime | log.Lshortfile)\n\n\tpart\t:= FieldsFuncN(data, 4, get_klog_tokenizer())\n\n\tif (len(part) < 4){\n\t\tlog.Println(data)\n\t\tfor pi := range part {\n\t\t\tlog.Println(part[pi])\n\t\t}\n\t}\n\n\tswitch len(part) {\n\n\tcase 2:\n\t\tprio, err := strconv.Atoi(part[0])\n\t\tif err != nil {\n\t\t\treturn syslog5424.EmptyMessage(),errors.New(\"Wrong Priority :\"+string(part[0]))\n\t\t}\n\n\t\treturn\tsyslog5424.CreateMessage(\"-\", syslog5424.Priority(prio), part[2]),nil\n\n\tcase 3:\n\t\t// (kern) 0 * 8 + 6 (info)\n\t\treturn\tsyslog5424.CreateMessage(\"-\", syslog5424.Priority(6), part[2]).Delta(boot_ts, part[0], part[1]),nil\n\n\tcase 4:\n\t\tprio, err := strconv.Atoi(part[0])\n\t\tif err != nil {\n\t\t\treturn syslog5424.EmptyMessage(),errors.New(\"Wrong Priority :\"+string(part[0]))\n\t\t}\n\t\treturn\tsyslog5424.CreateMessage(\"-\", syslog5424.Priority(prio), part[3]).Delta(boot_ts, part[1], part[2]),nil\n\n\tdefault:\n\t\t// (kern) 0 * 8 + 6 (info)\n\t\treturn\tsyslog5424.CreateMessage(\"-\", syslog5424.Priority(6), data),nil\n\t}\n}", "func (p *parser) parseEvent(pkgs []*usagepb.PackageInfo, timestamp int64, event, details, pid string) (string, error) {\n\t// Reset the saved event state if we've moved on to a new event type.\n\tif p.lastEventType != event {\n\t\tp.printPartial()\n\t\tp.lastEventType = event\n\t}\n\n\tswitch event {\n\tcase \"DEBUG\":\n\t\tif details == nativeCrashStart {\n\t\t\tp.partialEvent.Start = timestamp\n\t\t\treturn \"\", nil\n\t\t}\n\t\tvar err error\n\t\tstartMs := p.partialEvent.Start\n\t\tif m, result := historianutils.SubexpNames(nativeCrashProcessRE, details); m && startMs != 0 {\n\t\t\tvar uid string\n\t\t\tuid, err = procToUID(result[\"process\"], pkgs)\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: \"Native crash\",\n\t\t\t\tStart: startMs, // Use the last seen native crash start time.\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: fmt.Sprintf(\"%s: %s\", result[\"process\"], result[\"thread\"]),\n\t\t\t\tOpt: uid,\n\t\t\t})\n\t\t\tp.partialEvent = csv.Entry{} // Clear it here in case we encounter another line that matches the regexp in this crash event.\n\t\t}\n\t\treturn \"\", err\n\tcase \"StrictMode\":\n\t\t// Match the start of a policy violation event.\n\t\tif strings.HasPrefix(details, strictModePre) {\n\t\t\t// Possible we have a stored existing policy violation event. Print it out if it exists.\n\t\t\tp.printPartial()\n\t\t\t// Save the event, but don't print it out yet in case we find the process name in\n\t\t\t// the stack trace.\n\t\t\tp.partialEvent = csv.Entry{\n\t\t\t\tDesc: \"StrictMode policy violation\",\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: strings.TrimSpace(strings.TrimPrefix(details, strictModePre)),\n\t\t\t}\n\t\t\treturn \"\", nil\n\t\t}\n\t\tif p.partialEvent.Start != 0 && strings.HasPrefix(details, \"at\") {\n\t\t\t// Probably part of the stack trace if it starts with \"at\".\n\t\t\t// e.g. \"at com.android.app.AppSettings.newInstance(AppSettings.java:11418)\"\n\t\t\tpkg, err := packageutils.GuessPackage(details, \"\", pkgs)\n\t\t\t// StrictMode violations will be reported by the \"android\" package,\n\t\t\t// but this would be useless to display so we wait until we find a\n\t\t\t// meaningful package name.\n\t\t\tif pkg == nil || err != nil || pkg.GetPkgName() == \"android\" {\n\t\t\t\t// Don't bother returning the error as we're not sure what line the real package is on.\n\t\t\t\treturn \"\", nil\n\t\t\t}\n\t\t\tp.partialEvent.Opt = strconv.Itoa(int(pkg.GetUid()))\n\t\t\tp.printPartial()\n\t\t\treturn \"\", nil\n\t\t}\n\t\t// Not part of a stack trace. Print out any existing StrictMode event.\n\t\tp.printPartial()\n\t\treturn \"\", nil\n\tcase \"dumpstate\":\n\t\tif strings.Contains(details, \"begin\") {\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: \"Logcat misc\",\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"string\",\n\t\t\t\tValue: \"bug report collection triggered\",\n\t\t\t})\n\t\t\treturn \"\", nil\n\t\t}\n\tcase \"BluetoothAdapter\":\n\t\tif strings.Contains(details, \"startLeScan()\") {\n\t\t\tappName, uid := p.pidInfo(pid)\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: \"Bluetooth Scan\",\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: fmt.Sprintf(\"%s (PID: %s)\", appName, pid),\n\t\t\t\tOpt: uid,\n\t\t\t})\n\t\t}\n\t\treturn \"\", nil\n\tcase \"AndroidRuntime\":\n\t\tif m, result := historianutils.SubexpNames(crashStartRE, details); m {\n\t\t\t// Don't print out a crash event until we have the process details of what crashed.\n\t\t\tp.partialEvent.Value = result[\"source\"]\n\t\t\treturn \"\", nil\n\t\t}\n\t\tif m, result := historianutils.SubexpNames(crashProcessRE, details); m && p.partialEvent.Value != \"\" {\n\t\t\tuid, err := procToUID(result[\"process\"], pkgs)\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: crashes,\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: fmt.Sprintf(\"%s: %s\", result[\"process\"], p.partialEvent.Value),\n\t\t\t\tOpt: uid,\n\t\t\t})\n\t\t\tp.partialEvent = csv.Entry{}\n\t\t\treturn \"\", err\n\t\t}\n\tcase \"art\":\n\t\tif m, result := historianutils.SubexpNames(gcPauseRE, details); m {\n\t\t\tt := \"\"\n\t\t\tswitch result[\"type\"] {\n\t\t\tcase \"Background partial\":\n\t\t\t\tt = \"Background (partial)\"\n\t\t\tcase \"Background sticky\":\n\t\t\t\tt = \"Background (sticky)\"\n\t\t\tcase \"Explicit\":\n\t\t\t\tt = \"Foreground\"\n\t\t\tdefault:\n\t\t\t\treturn \"\", fmt.Errorf(\"got unknown GC Pause type: %s\", result[\"type\"])\n\t\t\t}\n\t\t\tdur, err := time.ParseDuration(result[\"pausedDur\"])\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: fmt.Sprintf(\"GC Pause - %s\", t),\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: strconv.FormatInt(dur.Nanoseconds(), 10),\n\t\t\t})\n\t\t\treturn \"\", nil\n\t\t}\n\tcase \"Choreographer\":\n\t\tif m, result := historianutils.SubexpNames(choreographerRE, details); m {\n\t\t\t_, uid := p.pidInfo(pid)\n\t\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\t\tDesc: \"Choreographer (skipped frames)\",\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: result[\"numFrames\"],\n\t\t\t\tOpt: uid,\n\t\t\t})\n\t\t\treturn \"\", nil\n\t\t}\n\n\t// Format of Activity Manager details is defined at frameworks/base/services/core/java/com/android/server/am/EventLogTags.logtags.\n\tcase amWTFEvent:\n\t\tif strings.HasPrefix(details, \"[\") { // Encountered start of am_wtf event.\n\t\t\t// Possible we have a stored existing am_wtf event. Print it out if it exists.\n\t\t\tp.printPartial()\n\t\t\t// Sometimes the event is multi-line, so save the event for printing later.\n\t\t\tp.partialEvent = csv.Entry{\n\t\t\t\tDesc: event,\n\t\t\t\tStart: timestamp,\n\t\t\t\tType: \"service\",\n\t\t\t\tValue: strings.Trim(details, \"[]\"),\n\t\t\t}\n\t\t\treturn \"\", nil\n\t\t} else if p.partialEvent.Desc != amWTFEvent { // No saved am_wtf event, and it's not the start of an am_wtf event.\n\t\t\treturn \"\", fmt.Errorf(\"am_wtf event with non expected format: %s\", amWTFEvent)\n\t\t}\n\t\tp.partialEvent.Value += \"\\n\" + strings.Trim(details, \"]\") // Continuation of existing event.\n\t\treturn \"\", nil\n\n\tcase lowMemoryEvent:\n\t\tdetails = strings.Trim(details, \"[]\")\n\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\tDesc: \"AM Low Memory\",\n\t\t\tStart: timestamp,\n\t\t\tType: \"service\",\n\t\t\tValue: details, // The value is the number of processes.\n\t\t})\n\t\treturn \"\", nil\n\tcase anrEvent:\n\t\tdetails = strings.Trim(details, \"[]\")\n\t\treturn p.parseANR(pkgs, timestamp, details)\n\tcase procStartEvent, procDiedEvent:\n\t\tdetails = strings.Trim(details, \"[]\")\n\t\treturn p.parseProc(timestamp, details, event)\n\tcase \"dvm_lock_sample\":\n\t\tdetails = strings.Trim(details, \"[]\")\n\t\tparts := strings.Split(details, \",\")\n\t\twarning, err := verifyLen(\"dvm_lock_sample\", parts, 9)\n\t\tif err != nil {\n\t\t\treturn warning, err\n\t\t}\n\t\tuid, err := procToUID(parts[0], pkgs)\n\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\tDesc: \"Long dvm_lock_sample\", // Filtering on duration is done on JS side.\n\t\t\tStart: timestamp,\n\t\t\tType: \"service\",\n\t\t\tValue: details,\n\t\t\tOpt: uid,\n\t\t})\n\t\treturn warning, err\n\tdefault:\n\t\tdetails = strings.Trim(details, \"[]\")\n\t\tp.csvState.PrintInstantEvent(csv.Entry{\n\t\t\tDesc: event,\n\t\t\tStart: timestamp,\n\t\t\tType: \"service\",\n\t\t\tValue: details,\n\t\t})\n\t}\n\treturn \"\", nil\n}", "func (c *Controller) HandlePanic(v interface{}, debug bool) {\n\tstatus := http.StatusInternalServerError\n\n\tswitch e := v.(type) {\n\tcase *perror.Error:\n\t\tstatus = e.Status()\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tc.Json(EmptyObject, status, e.Message())\n\t\t\t\tc.Context().Error(\"%s, trace[%s]\", util.ToString(err), util.PanicTrace(TraceMaxDepth, false, debug))\n\t\t\t}\n\t\t}()\n\n\t\tApp().Router().ErrorController(c.Context(), status).(iface.IErrorController).Error(status, e.Message())\n\tdefault:\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tc.Json(EmptyObject, status)\n\t\t\t\tc.Context().Error(\"%s, trace[%s]\", util.ToString(err), util.PanicTrace(TraceMaxDepth, false, debug))\n\t\t\t}\n\t\t}()\n\n\t\tApp().Router().ErrorController(c.Context(), status).(iface.IErrorController).Error(status, \"\")\n\t}\n\n\tif status != http.StatusOK {\n\t\tc.Context().Error(\"%s, trace[%s]\", util.ToString(v), util.PanicTrace(TraceMaxDepth, false, debug))\n\t}\n}", "func LogPanic(context string, module string, info string) {\n log.Panic().\n Str(\"Context\", context).\n Str(\"Module\", module).\n Msg(info)\n}", "func (_Registry *RegistryFilterer) ParseDefaultPanicButtonUpdated(log types.Log) (*RegistryDefaultPanicButtonUpdated, error) {\n\tevent := new(RegistryDefaultPanicButtonUpdated)\n\tif err := _Registry.contract.UnpackLog(event, \"DefaultPanicButtonUpdated\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func TestPanicSafety(t *testing.T) {\n\tpredeclared := starlark.StringDict{\n\t\t\"panic\": starlark.NewBuiltin(\"panic\", func(thread *starlark.Thread, b *starlark.Builtin, args starlark.Tuple, kwargs []starlark.Tuple) (starlark.Value, error) {\n\t\t\tpanic(args[0])\n\t\t}),\n\t\t\"list\": starlark.NewList([]starlark.Value{starlark.MakeInt(0)}),\n\t}\n\n\t// This program is executed twice, using the same Thread,\n\t// and panics both times, with values 1 and 2, while\n\t// main is on the stack and a for-loop is active.\n\t//\n\t// It mutates list, a predeclared variable.\n\t// This operation would fail if the previous\n\t// for-loop failed to close its iterator during the panic.\n\t//\n\t// It also calls main a second time without recursion enabled.\n\t// This operation would fail if the previous\n\t// call failed to pop main from the stack during the panic.\n\tconst src = `\nlist[0] += 1\n\ndef main():\n for x in list:\n panic(x)\n\nmain()\n`\n\tthread := new(starlark.Thread)\n\tfor _, i := range []int{1, 2} {\n\t\t// Use a func to limit the scope of recover.\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif got := fmt.Sprint(recover()); got != fmt.Sprint(i) {\n\t\t\t\t\tt.Fatalf(\"recover: got %v, want %v\", got, i)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tv, err := starlark.ExecFile(thread, \"panic.star\", src, predeclared)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"ExecFile returned error %q, expected panic\", err)\n\t\t\t} else {\n\t\t\t\tt.Fatalf(\"ExecFile returned %v, expected panic\", v)\n\t\t\t}\n\t\t}()\n\t}\n}", "func (c *CloudFormationTemplate) ParseOutput(descOut *cloudformation.DescribeStacksOutput, cloudFormationValues map[string]string) {\n\tstack := descOut.Stacks[0]\n\tfor _, cfOutput := range stack.Outputs {\n\t\ttrimKey := strings.TrimSpace(*cfOutput.OutputKey)\n\t\ttrimVal := strings.TrimSpace(*cfOutput.OutputValue)\n\t\tcloudFormationValues[trimKey] = trimVal\n\t}\n\tc.Output = cloudFormationValues\n}", "func main() {\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Error:\", err)\n\t}\n\n\tif err := testPanic(); err != nil {\n\t\tfmt.Println(\"Test Panic:\", err)\n\t}\n}", "func (_Cakevault *CakevaultFilterer) ParseUnpause(log types.Log) (*CakevaultUnpause, error) {\n\tevent := new(CakevaultUnpause)\n\tif err := _Cakevault.contract.UnpackLog(event, \"Unpause\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func (_Cakevault *CakevaultFilterer) ParseUnpaused(log types.Log) (*CakevaultUnpaused, error) {\n\tevent := new(CakevaultUnpaused)\n\tif err := _Cakevault.contract.UnpackLog(event, \"Unpaused\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func slicePanic() {\n\tn := []int{1, 2, 3}\n\tfmt.Println(n[4])\n\tfmt.Println(\"Executia in slice s-a terminat cu succes\")\n}", "func CatchPanic(errRef *error) {\n\tr := recover()\n\tif r == nil {\n\t\treturn\n\t}\n\terr, ok := r.(error)\n\tif ok {\n\t\t*errRef = errors.New(fmt.Sprintf(\"panic: %v\", err))\n\t\treturn\n\t}\n\t*errRef = errors.New(fmt.Sprintf(\"%v\", r))\n}", "func TestParse(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\tp *Process\n\t\tout string\n\t\terr string\n\t}{\n\t\t{\n\t\t\tname: \"no status file\",\n\t\t\tp: &Process{\n\t\t\t\tstat: \"1 (systemd) S 0 1 1 0 -1 4194560 45535 23809816 88 2870 76 378 35944 9972 20 0 1 0 2 230821888 2325 18446744073709551615 1 1 0 0 0 0 671173123 4096 1260 0 0 0 17 2 0 0 69 0 0 0 0 0 0 0 0 0 0\",\n\t\t\t},\n\t\t\terr: \"no Uid string in \",\n\t\t},\n\t\t{\n\t\t\tname: \"Valid output\",\n\t\t\tout: \"PID TTY TIME CMD \\n1 ? 00:00:04 systemd \\n\",\n\t\t\tp: &Process{\n\t\t\t\tstat: \"1 (systemd) S 0 1 1 0 -1 4194560 45535 23809816 88 2870 76 378 35944 9972 20 0 1 0 2 230821888 2325 18446744073709551615 1 1 0 0 0 0 671173123 4096 1260 0 0 0 17 2 0 0 69 0 0 0 0 0 0 0 0 0 0\",\n\t\t\t\tstatus: `Name:\tsystemd\nUmask:\t0000\nState:\tS (sleeping)\nTgid:\t1\nNgid:\t0\nPid:\t1\nPPid:\t0\nTracerPid:\t0\nUid:\t0\t0\t0\t0\nGid:\t0\t0\t0\t0\nFDSize:\t128\nGroups:\nNStgid:\t1\nNSpid:\t1\nNSpgid:\t1\nNSsid:\t1\nVmPeak:\t 290768 kB\nVmSize:\t 225412 kB\nVmLck:\t 0 kB\nVmPin:\t 0 kB\nVmHWM:\t 9308 kB\nVmRSS:\t 9300 kB\nRssAnon:\t 2524 kB\nRssFile:\t 6776 kB\nRssShmem:\t 0 kB\nVmData:\t 18696 kB\nVmStk:\t 132 kB\nVmExe:\t 1336 kB\nVmLib:\t 10008 kB\nVmPTE:\t 204 kB\nVmSwap:\t 0 kB\nHugetlbPages:\t 0 kB\nCoreDumping:\t0\nThreads:\t1\nSigQ:\t0/31573\nSigPnd:\t0000000000000000\nShdPnd:\t0000000000000000\nSigBlk:\t7be3c0fe28014a03\nSigIgn:\t0000000000001000\nSigCgt:\t00000001800004ec\nCapInh:\t0000000000000000\nCapPrm:\t0000003fffffffff\nCapEff:\t0000003fffffffff\nCapBnd:\t0000003fffffffff\nCapAmb:\t0000000000000000\nNoNewPrivs:\t0\nSeccomp:\t0\nSpeculation_Store_Bypass:\tthread vulnerable\nCpus_allowed:\tffffffff,ffffffff,ffffffff,ffffffff\nCpus_allowed_list:\t0-127\nMems_allowed:\t00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001\nMems_allowed_list:\t0\nvoluntary_ctxt_switches:\t10168\nnonvoluntary_ctxt_switches:\t3746\n`,\n\t\t\t},\n\t\t\terr: \"\",\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif err := tt.p.Parse(); err != nil {\n\t\t\t\tif err.Error() != tt.err {\n\t\t\t\t\tt.Errorf(\"Parse() = %q, want: %q\", err, tt.err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n}", "func defaultPanicHandler() {\n\tdefer defaultNotifier.dontPanic()\n\n\terr := panicwrap.BasicMonitor(func(output string) {\n\t\ttoNotify, err := errors.ParsePanic(output)\n\n\t\tif err != nil {\n\t\t\tdefaultNotifier.Config.log(\"bugsnag.handleUncaughtPanic: %v\", err)\n\t\t}\n\t\tNotify(toNotify, SeverityError, Configuration{Synchronous: true})\n\t})\n\n\tif err != nil {\n\t\tdefaultNotifier.Config.log(\"bugsnag.handleUncaughtPanic: %v\", err)\n\t}\n}", "func CatchPanic(err *error, goRoutine string, functionName string) {\n\tif r := recover(); r != nil {\n\t\t// Capture the stack trace\n\t\tbuf := make([]byte, 10000)\n\t\truntime.Stack(buf, false)\n\n\t\terr2 := fmt.Errorf(\"PANIC Defered [%v] : Stack Trace : %v\", r, string(buf))\n\t\ttracelog.Alert(\"Unhandled Exception\", goRoutine, functionName, err2.Error())\n\n\t\tif err != nil {\n\t\t\t*err = err2\n\t\t}\n\t}\n}", "func (_KeepRegistry *KeepRegistryFilterer) ParseOperatorContractPanicButtonUpdated(log types.Log) (*KeepRegistryOperatorContractPanicButtonUpdated, error) {\n\tevent := new(KeepRegistryOperatorContractPanicButtonUpdated)\n\tif err := _KeepRegistry.contract.UnpackLog(event, \"OperatorContractPanicButtonUpdated\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (_ERC20Pausable *ERC20PausableFilterer) ParseUnpaused(log types.Log) (*ERC20PausableUnpaused, error) {\n\tevent := new(ERC20PausableUnpaused)\n\tif err := _ERC20Pausable.contract.UnpackLog(event, \"Unpaused\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func testPanic() (err error) {\n\tdefer catchPanic(&err, \"TestPanic\")\n\tfmt.Printf(\"\\nTestPanic: Start Test\\n\")\n\n\terr = mimicError(\"1\")\n\n\tpanic(\"Mimic Panic\")\n}", "func DPanicf(template string, args ...interface{}) {\n\terrorLogger.DPanicf(template, args...)\n}", "func Panic2Response(c *gin.Context, err error, segmentName string) {\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": err.Error()})\n\t\tlog.Panicf(\"Panic in '%s' : %v\", segmentName, err)\n\t}\n}", "func (r *reporter) Fatal(args ...interface{}) {\n\tr.Fail()\n\tpanic(fmt.Sprint(args...))\n}", "func (_KeepRegistry *KeepRegistryFilterer) ParseDefaultPanicButtonUpdated(log types.Log) (*KeepRegistryDefaultPanicButtonUpdated, error) {\n\tevent := new(KeepRegistryDefaultPanicButtonUpdated)\n\tif err := _KeepRegistry.contract.UnpackLog(event, \"DefaultPanicButtonUpdated\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (p *parser) parse(cmdOutput string) []string {\n\tp.ips = []string{}\n\tp.scanner = bufio.NewScanner(strings.NewReader(cmdOutput))\n\tfor p.scanner.Scan() {\n\t\tline := p.scanner.Text()\n\t\tline = strings.TrimLeft(line, \" \\t\")\n\t\tp.parseLine(line)\n\t}\n\treturn p.ips\n}", "func (_Pausable *PausableFilterer) ParseUnpaused(log types.Log) (*PausableUnpaused, error) {\n\tevent := new(PausableUnpaused)\n\tif err := _Pausable.contract.UnpackLog(event, \"Unpaused\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func Exit(err interface{}) {\n\ttmpl, err2 := template.ParseFS(localFS, \"html/crash.html\", \"html/header.html\")\n\tif err2 != nil {\n\t\tlog.Fatalf(\"Failed to load template: %v\", err)\n\t}\n\tlogCache := lineCache.String()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tlogCache += \"\\n\" + fmt.Sprint(err)\n\t}\n\tlogCache += \"\\n\" + string(debug.Stack())\n\tsanitized := sanitizeLog(logCache)\n\tdata := map[string]interface{}{\n\t\t\"Log\": logCache,\n\t\t\"SanitizedLog\": sanitized,\n\t}\n\tif err != nil {\n\t\tdata[\"Err\"] = fmt.Sprintf(\"%s %v\", identifyPanic(), err)\n\t}\n\tfpath := filepath.Join(temp, \"jfa-go-crash-\"+time.Now().Local().Format(\"2006-01-02T15:04:05\"))\n\terr2 = os.WriteFile(fpath+\".txt\", []byte(logCache), 0666)\n\tif err2 != nil {\n\t\tlog.Fatalf(\"Failed to write crash dump file: %v\", err2)\n\t}\n\tlog.Printf(\"\\n------\\nA crash report has been saved to \\\"%s\\\".\\n------\", fpath+\".txt\")\n\tf, err2 := os.OpenFile(fpath+\".html\", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)\n\tif err2 != nil {\n\t\tlog.Fatalf(\"Failed to open crash dump file: %v\", err2)\n\t}\n\tdefer f.Close()\n\terr2 = tmpl.Execute(f, data)\n\tif err2 != nil {\n\t\tlog.Fatalf(\"Failed to execute template: %v\", err2)\n\t}\n\tbrowser.OpenFile(fpath + \".html\")\n\tif TRAY {\n\t\tQuitTray()\n\t} else {\n\t\tos.Exit(1)\n\t}\n}", "func (l *AppLogger) Panic(tag string, message ...interface{}) {\n\tl.logging.SetFormatter(&logrus.JSONFormatter{})\n\tk := getAppFields(l.reqId, tag, l.userId)\n\tl.logging.WithFields(k).Panic(message...)\n}", "func (_Logger *LoggerFilterer) ParseRollbackFinalisation(log types.Log) (*LoggerRollbackFinalisation, error) {\n\tevent := new(LoggerRollbackFinalisation)\n\tif err := _Logger.contract.UnpackLog(event, \"RollbackFinalisation\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}", "func (e ErrParseIP) BadRequest() {}", "func ParsePacket(line string) (Event, error) {\n\tevent := NewEvent(\"packet\", \"\")\n\tevent.Time = time.Now()\n\n\tif len(line) == 0 {\n\t\treturn event, errors.New(\"irc: empty line\")\n\t}\n\n\t// Parse tags\n\tif line[0] == '@' {\n\t\tsplit := strings.SplitN(line, \" \", 2)\n\t\tif len(split) < 2 {\n\t\t\treturn event, errors.New(\"irc: incomplete packet\")\n\t\t}\n\n\t\ttagTokens := strings.Split(split[0][1:], \";\")\n\t\tfor _, token := range tagTokens {\n\t\t\tkv := strings.SplitN(token, \"=\", 2)\n\n\t\t\tif len(kv) == 2 {\n\t\t\t\tevent.Tags[kv[0]] = unescapeTags.Replace(kv[1])\n\t\t\t} else {\n\t\t\t\tevent.Tags[kv[0]] = \"\"\n\t\t\t}\n\t\t}\n\n\t\tline = split[1]\n\t}\n\n\t// Parse prefix\n\tif line[0] == ':' {\n\t\tsplit := strings.SplitN(line, \" \", 2)\n\t\tif len(split) < 2 {\n\t\t\treturn event, errors.New(\"ParsePacket: incomplete packet\")\n\t\t}\n\n\t\tprefixTokens := strings.Split(split[0][1:], \"!\")\n\n\t\tevent.Nick = prefixTokens[0]\n\t\tif len(prefixTokens) > 1 {\n\t\t\tuserhost := strings.Split(prefixTokens[1], \"@\")\n\n\t\t\tif len(userhost) < 2 {\n\t\t\t\treturn event, errors.New(\"ParsePacket: invalid user@host format\")\n\t\t\t}\n\n\t\t\tevent.User = userhost[0]\n\t\t\tevent.Host = userhost[1]\n\t\t}\n\n\t\tline = split[1]\n\t}\n\n\t// Parse body\n\tsplit := strings.SplitN(line, \" :\", 2)\n\ttokens := strings.Split(split[0], \" \")\n\n\tif len(split) == 2 {\n\t\tevent.Text = split[1]\n\t}\n\n\tevent.verb = tokens[0]\n\tevent.Args = tokens[1:]\n\n\t// Parse CTCP\n\tif (event.verb == \"PRIVMSG\" || event.verb == \"NOTICE\") && strings.HasPrefix(event.Text, \"\\x01\") {\n\t\tverbtext := strings.SplitN(strings.Replace(event.Text, \"\\x01\", \"\", 2), \" \", 2)\n\n\t\tif event.verb == \"PRIVMSG\" {\n\t\t\tevent.kind = \"ctcp\"\n\t\t} else {\n\t\t\tevent.kind = \"ctcp-reply\"\n\t\t}\n\n\t\tevent.verb = verbtext[0]\n\t\tif len(verbtext) == 2 {\n\t\t\tevent.Text = verbtext[1]\n\t\t} else {\n\t\t\tevent.Text = \"\"\n\t\t}\n\t}\n\n\tevent.name = event.kind + \".\" + strings.ToLower(event.verb)\n\treturn event, nil\n}", "func Fatal(v ...interface{}) {\n\tFatalFile(token.Position{}, v...)\n}", "func parsePane(s string) (*Pane, error) {\n\ts = strings.Trim(s, \"'\")\n\tfields := strings.Split(s, \" \")\n\n\tif len(fields) != 5 {\n\t\treturn nil, fmt.Errorf(\"expected 5 fields, got %d\", len(fields))\n\t}\n\n\tindex, err := strconv.Atoi(fields[1])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpid, err := strconv.Atoi(fields[4])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tpane := &Pane{\n\t\tID: fields[0],\n\t\tActive: fields[3] == \"1\",\n\t\tIndex: index,\n\t\tPID: int32(pid),\n\t\tTitle: fields[2],\n\t}\n\n\treturn pane, nil\n}", "func Panic(err error, segmentName string) {\n\tif err != nil {\n\t\tlog.Panicf(\"Panic in '%s' : %v\", segmentName, err)\n\t}\n}", "func (l *LogEntry) Panic(v interface{}, stack []byte) {\n\te := l.NewLogEntry(l.req).(*LogEntry)\n\tfmt.Fprintf(e.buf, \"panic: %#v\", v)\n\tlog.Print(e.buf.String())\n\tlog.Print(string(stack))\n}", "func panicErrCollector(e ErrCollector) {\n\tlastErr := len(e.MyErrs) - 1\n\tif e.MyErrs[lastErr].err != nil {\n\t\tcurrtime := time.Now().Format(\"2006-01-02\")\n\t\terrString := fmt.Sprintf(\"PANIC - TIME: %s FUNC: %s ERROR:%s\\n\", currtime, e.MyErrs[len(e.MyErrs)-1].Caller, e.MyErrs[len(e.MyErrs)-1].ErrString)\n\t\ttempDir, _ := os.Getwd()\n\t\tpanicFileName := fmt.Sprintf(\"%s/dumps/%s_%s\", tempDir, currtime, \"PANIC_FILE\")\n\n\t\t//Validates that the dump folder is present on the disk, if not it will create the directory and file needed\n\t\t//for the panic dump file.\n\t\t_, err := os.Stat(\"dumps\")\n\t\tif err != nil {\n\t\t\terr = os.Mkdir(\"dumps\", 0777)\n\t\t\tif err != nil {\n\t\t\t\tpanic(errors.New(\"Default Handler Unable to Create Directory\"))\n\t\t\t}\n\n\t\t\te.PanicFile, err = os.OpenFile(panicFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777)\n\t\t\tif err != nil {\n\t\t\t\tpanic(errors.New(\"Default Handler Unable to Create File\"))\n\t\t\t}\n\n\t\t\tnum, err := e.PanicFile.Write([]byte(errString))\n\t\t\tfmt.Println(num)\n\t\t\tif err != nil {\n\t\t\t\tpanic(errors.New(\"Default Handler Unable to Write File\"))\n\t\t\t}\n\t\t\tfmt.Printf(\"PANIC - TRACE_FILE:\\n\\t%s\\n\", e.PanicFile.Name())\n\t\t\tdefer e.PanicFile.Close()\n\t\t\treturn\n\t\t}\n\n\t\te.PanicFile, err = os.OpenFile(panicFileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0777)\n\t\tif err != nil {\n\t\t\tpanic(errors.New(\"Default Handler Unable to Create File\"))\n\t\t}\n\n\t\tnum, err := e.PanicFile.Write([]byte(errString))\n\t\tfmt.Println(num)\n\t\tif err != nil {\n\t\t\tpanic(errors.New(\"Default Handler Unable to Write File\"))\n\t\t}\n\t\tfmt.Printf(\"PANIC - TRACE_FILE:\\n\\t%s\\n\", e.PanicFile.Name())\n\t\tdefer e.PanicFile.Close()\n\t\treturn\n\n\t}\n}", "func (p *Printer) Parse() error {\n\treturn p.print(p.t.RootNode(), \"\", true, 0)\n}", "func parseWarnings(warnings []string) *PodSecurityViolation {\n\tif len(warnings) == 0 {\n\t\treturn nil\n\t}\n\n\tvar psv PodSecurityViolation\n\n\t// There should be exactly 2 warnings, but lets not rely on the order nor it to stay that way.\n\tfor _, warning := range warnings {\n\t\tregex := regexp.MustCompile(`existing pods in namespace \"([^\"]+)\" violate the new PodSecurity enforce level \"([^\"]+)\"`)\n\t\tmatches := regex.FindStringSubmatch(warning)\n\n\t\t// Namespace Warning Message\n\t\tif len(matches) == 3 {\n\t\t\t// The text should look like \"existing pods in namespace \"my-namespace\" violate the new PodSecurity enforce level \"mylevel:v1.2.3\"\n\t\t\tpsv.Namespace = matches[1]\n\t\t\tpsv.Level = matches[2]\n\t\t\tcontinue\n\t\t}\n\n\t\t// The text should look like this: {pod name}{(optional) more pods hint}: {policy warning A}, {policy warning B}, ...\n\t\t// Verify that we are handling violations\n\t\ttextSplit := strings.Split(warning, \": \")\n\t\tif len(textSplit) != 2 {\n\t\t\tcontinue\n\t\t}\n\n\t\tmatchingList := strings.Split(textSplit[secondMatch], \", \")\n\t\tmatchedCandidates := []string{}\n\t\tfor _, candidate := range matchingList {\n\t\t\t// It could be that there are new violations in the pod-security-admission code.\n\t\t\tif _, ok := violations[candidate]; ok {\n\t\t\t\tmatchedCandidates = append(matchedCandidates, candidate)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\n\t\tif len(matchedCandidates) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\t// Get rid of the potential \" (and x other pods)\" hint.\n\t\tpsv.PodName = strings.Split(textSplit[firstMatch], \" \")[firstMatch]\n\t\tpsv.Violations = matchedCandidates\n\t}\n\n\t// Check if any properties of the psv struct have been set. If not, return nil.\n\tif psv.Namespace == \"\" && psv.Level == \"\" && psv.PodName == \"\" && len(psv.Violations) == 0 {\n\t\treturn nil\n\t}\n\n\treturn &psv\n}", "func (h *TaskHandler) panicHandler(w http.ResponseWriter, r *http.Request, rcv interface{}) {\n\tctx := r.Context()\n\tpe := &errors2.Error{\n\t\tCode: errors2.EInternal,\n\t\tMsg: \"a panic has occurred\",\n\t\tErr: fmt.Errorf(\"%s: %v\", r.URL.String(), rcv),\n\t}\n\n\tif entry := h.log.Check(zapcore.ErrorLevel, pe.Msg); entry != nil {\n\t\tentry.Stack = string(debug.Stack())\n\t\tentry.Write(zap.Error(pe.Err))\n\t}\n\n\th.HandleHTTPError(ctx, pe, w)\n}", "func (se *SubscriberPanic) Panic() interface{} {\n\treturn se.internal\n}", "func DPanicf(template string, args ...interface{}) {\n\tlog.DPanicf(template, args...)\n}", "func panicHandler(w http.ResponseWriter, r *http.Request) {\n\tfuncPanic()\n}", "func (n *Node) Panic(args ...interface{}) {\n\tn.log.Panic(args...)\n}", "func (mi *mountInfoParser) parse() error {\n\n\tdata, err := ioutil.ReadFile(fmt.Sprintf(\"/proc/%d/mountinfo\", mi.pid))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := mi.parseData(data); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func TestFpanicf(t *testing.T) {\n\tdefer func() {\n\t\tif r := recover(); r == nil {\n\t\t\tt.Errorf(\"The code did not panic as expected\")\n\t\t}\n\t}()\n\n\tr, w, _ := os.Pipe()\n\tSetOutputs(Output{\n\t\tName: \"test\",\n\t\tWriter: w,\n\t\tLevels: level.Panic,\n\t})\n\n\tFpanicf(w, \"Test fatal %s\", \"formatted\")\n\toutC := make(chan string)\n\tgo ioCopy(r, outC)\n\tw.Close()\n\tout := <-outC\n\n\texpected := \"Test fatal formatted\"\n\tn := level.Labels[level.Panic]\n\tif !strings.Contains(out, expected) || !strings.Contains(out, n) {\n\t\tt.Errorf(\"Result `%s` doesn't contains `%s` and `%s`\",\n\t\t\tout, expected, n)\n\t}\n}", "func ParsePostInvoicesResponse(rsp *http.Response) (*PostInvoicesResponse, error) {\n\tbodyBytes, err := ioutil.ReadAll(rsp.Body)\n\tdefer rsp.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresponse := &PostInvoicesResponse{\n\t\tBody: bodyBytes,\n\t\tHTTPResponse: rsp,\n\t}\n\n\tswitch {\n\t}\n\n\treturn response, nil\n}", "func (c *T) Fatal(args ...interface{})", "func (_RandomBeacon *RandomBeaconFilterer) ParseDkgTimedOut(log types.Log) (*RandomBeaconDkgTimedOut, error) {\n\tevent := new(RandomBeaconDkgTimedOut)\n\tif err := _RandomBeacon.contract.UnpackLog(event, \"DkgTimedOut\", log); err != nil {\n\t\treturn nil, err\n\t}\n\tevent.Raw = log\n\treturn event, nil\n}", "func Panic(f interface{}, v ...interface{}) {\n\tvar format string\n\tswitch f.(type) {\n\tcase string:\n\t\tformat = f.(string)\n\t\tlog.Panicf(format, v...)\n\tdefault:\n\t\tformat = fmt.Sprint(f)\n\t\tif len(v) == 0 {\n\t\t\tlog.Panic(format)\n\t\t\treturn\n\t\t}\n\t\tformat += strings.Repeat(\" %v\", len(v))\n\t\tlog.Panicf(format, v...)\n\t}\n}", "func fail() parserOutput {\n\treturn parserOutput{nil, nil}\n}", "func isRangePanic(x interface{}) bool {\n\terr, ok := x.(runtime.Error)\n\treturn ok && errRangeRegexp.MatchString(err.Error())\n}", "func DPanic(args ...interface{}) {\n\terrorLogger.DPanic(args...)\n}", "func get_output(){\nrestart:\nif len(stack)==0{\nreturn\n}\nif len(cur_state.byte_field)==0{\ncur_val= -cur_state.section_field/* cast needed because of sign extension */\npop_level()\nif cur_val==0{\ngoto restart\n}\nout_char(section_number)\nreturn\n}\na:=cur_state.byte_field[0]\ncur_state.byte_field= cur_state.byte_field[1:]\nif out_state==verbatim&&a!=strs&&a!=constant&&a!=comment&&a!='\\n'{\nfmt.Fprintf(go_file,\"%c\",a)\n}else if a<unicode.UpperLower{\nout_char(a)\n}else{\nc:=cur_state.byte_field[0]\ncur_state.byte_field= cur_state.byte_field[1:]\nswitch a%unicode.UpperLower{\ncase identifier:\ncur_val= c\nout_char(identifier)\ncase section_name:\n\n\n/*109:*/\n\n\n//line gotangle.w:340\n\n{\nif name_dir[c].equiv!=-1{\npush_level(c)\n}else if a!=0{\nerr_print(\"! Not present: <%s>\",sprint_section_name(c))\n\n}\ngoto restart\n}\n\n\n\n/*:109*/\n\n\n//line gotangle.w:323\n\ncase line_number:\ncur_val= c\nout_char(line_number)\ncase section_number:\ncur_val= c\nif cur_val> 0{\ncur_state.section_field= cur_val\n}\nout_char(section_number)\n}\n}\n}" ]
[ "0.65048236", "0.54496276", "0.53601235", "0.5201537", "0.51885086", "0.5097626", "0.4978919", "0.4973028", "0.4933714", "0.4866331", "0.48482537", "0.4812704", "0.4788998", "0.47884333", "0.47799632", "0.4749531", "0.47438896", "0.47290915", "0.47040343", "0.4703246", "0.46912515", "0.46893874", "0.46762902", "0.46679118", "0.46679118", "0.46667534", "0.46412942", "0.46297446", "0.4612259", "0.46117368", "0.45971167", "0.4596966", "0.45945537", "0.45859784", "0.45828742", "0.45780107", "0.45769894", "0.4570811", "0.45343593", "0.45128572", "0.45075366", "0.4474142", "0.44677472", "0.44579196", "0.44524884", "0.4441642", "0.4420114", "0.44177026", "0.44169384", "0.44075885", "0.44029298", "0.4397053", "0.43928537", "0.43844593", "0.43660158", "0.436462", "0.43633938", "0.43395686", "0.43395433", "0.43272248", "0.4321904", "0.43201953", "0.43110043", "0.4306292", "0.42855385", "0.42838007", "0.4277831", "0.42728674", "0.42710054", "0.4264967", "0.42480823", "0.42412937", "0.42192358", "0.4212214", "0.42107332", "0.42075834", "0.4204285", "0.42025444", "0.4199044", "0.41944262", "0.41938806", "0.41929302", "0.41785395", "0.41783923", "0.4174893", "0.4172196", "0.41718355", "0.4169503", "0.41657832", "0.41646138", "0.41590038", "0.4155218", "0.41550735", "0.41530642", "0.41518402", "0.41396117", "0.41384742", "0.41285893", "0.4120437", "0.41144484" ]
0.7005714
0
Magnify wraps img into Magnifier to scale it up by scale factor usind given scaling mode.
func Magnify(img image.Image, sx, sy int, mode byte) *Magnifier { return &Magnifier{img, sx, sy, mode} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Expand(img image.Image, ratio float64) image.Image {\n\treturn img\n}", "func TestRescale(t *testing.T) {\n\tname := filepath.Join(datadir, \"f1.jpg\")\n\tt.Logf(\"rescaling %s with half-width and half-height\", name)\n\tf, err := os.Open(name)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer f.Close()\n\trescaledIm, _, err := Decode(f, &DecodeOpts{ScaleWidth: 0.5, ScaleHeight: 0.5})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tsmallIm := smallStraightFImage(t)\n\n\tgotB, wantB := rescaledIm.Bounds(), smallIm.Bounds()\n\tif !gotB.Eq(wantB) {\n\t\tt.Errorf(\"(scale) %v bounds not equal, got %v want %v\", name, gotB, wantB)\n\t}\n\tif !equals(rescaledIm, smallIm) {\n\t\tt.Errorf(\"(scale) %v pixels not equal\", name)\n\t}\n\n\t_, err = f.Seek(0, os.SEEK_SET)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\trescaledIm, _, err = Decode(f, &DecodeOpts{MaxWidth: 2000, MaxHeight: 40})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tgotB = rescaledIm.Bounds()\n\tif !gotB.Eq(wantB) {\n\t\tt.Errorf(\"(max) %v bounds not equal, got %v want %v\", name, gotB, wantB)\n\t}\n\tif !equals(rescaledIm, smallIm) {\n\t\tt.Errorf(\"(max) %v pixels not equal\", name)\n\t}\n}", "func TestRescaleEXIF(t *testing.T) {\n\tsmallStraightF := smallStraightFImage(t)\n\tsamples := sampleNames(t)\n\tfor _, v := range samples {\n\t\tif !strings.Contains(v, \"exif\") {\n\t\t\tcontinue\n\t\t}\n\t\tname := filepath.Join(datadir, v)\n\t\tt.Logf(\"rescaling %s with half-width and half-height\", name)\n\t\tf, err := os.Open(name)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tdefer f.Close()\n\t\trescaledIm, _, err := Decode(f, &DecodeOpts{ScaleWidth: 0.5, ScaleHeight: 0.5})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tgotB, wantB := rescaledIm.Bounds(), smallStraightF.Bounds()\n\t\tif !gotB.Eq(wantB) {\n\t\t\tt.Errorf(\"(scale) %v bounds not equal, got %v want %v\", name, gotB, wantB)\n\t\t}\n\t\tif !equals(rescaledIm, smallStraightF) {\n\t\t\tt.Errorf(\"(scale) %v pixels not equal\", name)\n\t\t}\n\n\t\t_, err = f.Seek(0, os.SEEK_SET)\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\trescaledIm, _, err = Decode(f, &DecodeOpts{MaxWidth: 2000, MaxHeight: 40})\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\n\t\tgotB = rescaledIm.Bounds()\n\t\tif !gotB.Eq(wantB) {\n\t\t\tt.Errorf(\"(max) %v bounds not equal, got %v want %v\", name, gotB, wantB)\n\t\t}\n\t\tif !equals(rescaledIm, smallStraightF) {\n\t\t\tt.Errorf(\"(max) %v pixels not equal\", name)\n\t\t}\n\t}\n}", "func TestUpscale(t *testing.T) {\n\tb := new(bytes.Buffer)\n\tw, h := 64, 48\n\tif err := jpeg.Encode(b, image.NewNRGBA(image.Rect(0, 0, w, h)), nil); err != nil {\n\t\tt.Fatal(err)\n\t}\n\tsizes := []struct {\n\t\tmw, mh int\n\t\twantW, wantH int\n\t}{\n\t\t{wantW: w, wantH: h},\n\t\t{mw: w, mh: h, wantW: w, wantH: h},\n\t\t{mw: w, mh: 2 * h, wantW: w, wantH: h},\n\t\t{mw: 2 * w, mh: w, wantW: w, wantH: h},\n\t\t{mw: 2 * w, mh: 2 * h, wantW: w, wantH: h},\n\t\t{mw: w / 2, mh: h / 2, wantW: w / 2, wantH: h / 2},\n\t\t{mw: w / 2, mh: 2 * h, wantW: w / 2, wantH: h / 2},\n\t\t{mw: 2 * w, mh: h / 2, wantW: w / 2, wantH: h / 2},\n\t}\n\tfor i, size := range sizes {\n\t\tvar opts DecodeOpts\n\t\tswitch {\n\t\tcase size.mw != 0 && size.mh != 0:\n\t\t\topts = DecodeOpts{MaxWidth: size.mw, MaxHeight: size.mh}\n\t\tcase size.mw != 0:\n\t\t\topts = DecodeOpts{MaxWidth: size.mw}\n\t\tcase size.mh != 0:\n\t\t\topts = DecodeOpts{MaxHeight: size.mh}\n\t\t}\n\t\tim, _, err := Decode(bytes.NewReader(b.Bytes()), &opts)\n\t\tif err != nil {\n\t\t\tt.Error(i, err)\n\t\t}\n\t\tgotW := im.Bounds().Dx()\n\t\tgotH := im.Bounds().Dy()\n\t\tif gotW != size.wantW || gotH != size.wantH {\n\t\t\tt.Errorf(\"%d got %dx%d want %dx%d\", i, gotW, gotH, size.wantW, size.wantH)\n\t\t}\n\t}\n}", "func NormalizeImage(img image.Image, maxSize int) image.Image {\n\tw := img.Bounds().Max.X\n\th := img.Bounds().Max.Y\n\tif w > h && w > maxSize {\n\t\th = int(float64(maxSize*h) / float64(w))\n\t\tw = maxSize\n\t} else if w < h && h > maxSize {\n\t\tw = int(float64(maxSize*w) / float64(h))\n\t\th = maxSize\n\t} else if w == h && w < maxSize {\n\t\tw = maxSize\n\t\th = maxSize\n\t}\n\treturn Resample(img, w, h, ResampleResize)\n}", "func (me TxsdViewTypeZoomAndPan) IsMagnify() bool { return me.String() == \"magnify\" }", "func (s *Sprite) Zoom(length float64) DrawingBuilder {\n\tif s.op == nil {\n\t\ts.err = errors.New(\"add a &ebiten.DrawImageOptions{} to s.op\")\n\t\treturn s\n\t}\n\ts.scale += length\n\ts.Width += length\n\ts.Height += length\n\n\ts.op.GeoM.Scale(float64(s.scale), float64(s.scale))\n\treturn s\n}", "func scaleImg(filename string, factor int) string {\n\t//Filename path\n\tpath := \"/gorpc/Images/\" + filename\n\n\t//Extract matrix of image file data\n\tpixels := gocv.IMRead(path, 1)\n\n\t//Get dimensions from picture\n\tdimensions := pixels.Size()\n\theight := dimensions[0]\n\twidth := dimensions[1]\n\n\t//Get type of mat\n\tmatType := pixels.Type()\n\n\t//Create a new mat to fill\n\tbigMat := gocv.NewMatWithSize(height * factor, width * factor, matType)\n\n\n\t//Created a wait group to sync row concurrency\n\twg := sync.WaitGroup{}\n\twg.Add(height)\n\n\t//Iterate through array in rows\n\tfor i := 0; i < height; i++ {\n\t\t//Go Routine call to fill in rows of big matrix concurrently\n\t\tgo func (i int){\n\t\t\t//Sync waitgroup\n\t\t\tdefer wg.Done()\n\t\t\tfor j := 0; j < width; j++ {\n\t\t\t\tval := GetVecbAt(pixels, i, j)\n\n\t\t\t\t//Iterate through larger matrix\n\t\t\t\tfor a := i * factor; a < i * factor + factor; a++ {\n\t\t\t\t\tfor b := j * factor; b < j * factor + factor; b++ {\n\t\t\t\t\t\t\tval.SetVecbAt(bigMat, a, b)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}(i)\n\t}\n\n\t//Big matrix is finished when all rows processed\n\twg.Wait()\n\n\t//Remove extension from filename\n\text := filepath.Ext(filename)\n\tname := strings.TrimSuffix(filename, ext)\n\n\t//Rename the new scaled image\n\tnewName := name + \"S\" + ext\n\n\t//New path\n\tnewPath := \"/gorpc/Images/\" + newName\n\n\t//Save the new image from matrix in local directory\n\tgocv.IMWrite(newPath, bigMat)\n\n\treturn newName\n}", "func resizeImage(img *image.Image) image.Image {\n\tFIU.Trace.Println(\"resizeImage()\")\n\tnewimg := resize.Thumbnail(max_width, max_height, *img, resize.Lanczos3)\n\tFIU.Trace.Printf(\"New Bounds : %d, %d\", newimg.Bounds().Max.X, newimg.Bounds().Max.Y)\n\treturn newimg\n}", "func DecodeJpegFancyUpscaling(value bool) DecodeJpegAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"fancy_upscaling\"] = value\n\t}\n}", "func imgHandle(w http.ResponseWriter, r *http.Request) {\n\tquality, err := strconv.Atoi(r.FormValue(\"quality\"))\n\tif err != nil || quality < 0 || quality > 100 {\n\t\tquality = 70\n\t}\n\n\t// Center Gopher in view if possible\n\tgpos := model.Gopher.Pos\n\trect := image.Rect(0, 0, ViewWidth, ViewHeight).Add(image.Pt(int(gpos.X)-ViewWidth/2, int(gpos.Y)-ViewHeight/2))\n\n\t// But needs correction at the edges of the view (it can't be centered)\n\tcorr := image.Point{}\n\tif rect.Min.X < 0 {\n\t\tcorr.X = -rect.Min.X\n\t}\n\tif rect.Min.Y < 0 {\n\t\tcorr.Y = -rect.Min.Y\n\t}\n\tif rect.Max.X > model.LabWidth {\n\t\tcorr.X = model.LabWidth - rect.Max.X\n\t}\n\tif rect.Max.Y > model.LabHeight {\n\t\tcorr.Y = model.LabHeight - rect.Max.Y\n\t}\n\trect = rect.Add(corr)\n\n\tmodel.Mutex.Lock()\n\tjpeg.Encode(w, model.LabImg.SubImage(rect), &jpeg.Options{quality})\n\tmodel.Mutex.Unlock()\n\n\t// Store the new view's position:\n\tPos = rect.Min\n}", "func (w *windowImpl) Scale(dr image.Rectangle, src screen.Texture, sr image.Rectangle, op draw.Op, opts *screen.DrawOptions) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func Pixelate(imageRef *ImageRef, factor float64) (err error) {\n\tif factor < 1 {\n\t\treturn errors.New(\"factor must be greater then 1\")\n\t}\n\n\twidth := imageRef.Width()\n\theight := imageRef.Height()\n\n\tif err = imageRef.Resize(1/factor, KernelAuto); err != nil {\n\t\treturn\n\t}\n\n\thScale := float64(width) / float64(imageRef.Width())\n\tvScale := float64(height) / float64(imageRef.Height())\n\tif err = imageRef.ResizeWithVScale(hScale, vScale, KernelNearest); err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (c DBaseController) ResizeImage(size uint, multipart string, blur float64) []byte {\n\tmImage, err := c.Params.Files[multipart][0].Open()\n\tif err != nil {\n\t\trevel.ERROR.Printf(\"ERROR OPEN Multipart\")\n\t\treturn []byte{}\n\t}\n\tdefer mImage.Close()\n\tbuf := new(bytes.Buffer)\n\n\tif core.GetFileType(c.Params.Files[multipart][0].Filename) != \"image\" {\n\t\trevel.ERROR.Printf(\"ERROR UNSUPORTED FileType\")\n\t\treturn []byte{}\n\t}\n\n\t// Copy image into buffer\n\tif _, err := io.Copy(buf, mImage); err != nil {\n\t\trevel.ERROR.Printf(\"ERROR READ Buffer --- %s\", err.Error())\n\t\treturn []byte{}\n\t}\n\n\tbyteArray := buf.Bytes()\n\timagick.Initialize()\n\n\tdefer imagick.Terminate()\n\n\tmw := imagick.NewMagickWand()\n\n\t// read image with ImageMagick\n\terr = mw.ReadImageBlob(byteArray)\n\tif err != nil {\n\t\trevel.ERROR.Printf(\"ERROR READ ImageMagick --- %s\", err.Error())\n\t\treturn []byte{}\n\t}\n\n\t// Resize the image using the Lanczos filter\n\t// The blur factor is a float, where > 1 is blurry, < 1 is sharp\n\terr = mw.ResizeImage(size, size, imagick.FILTER_LANCZOS, blur)\n\tif err != nil {\n\t\trevel.ERROR.Printf(\"ERROR RESIZE ImageMagick --- %s\", err.Error())\n\t\treturn []byte{}\n\t}\n\n\t// Set the compression quality to 95 (high quality = low compression)\n\terr = mw.SetImageCompressionQuality(95)\n\tif err != nil {\n\t\trevel.ERROR.Printf(\"ERROR COMPRESSING ImageMagick --- %s\", err.Error())\n\t\treturn []byte{}\n\t}\n\treturn mw.GetImageBlob()\n}", "func (v *Pixbuf) ScaleSimple(width, height int, interp InterpType) (*Pixbuf, error) {\n\tc := C.gdk_pixbuf_scale_simple(v.Native(), C.int(width), C.int(height), C.GdkInterpType(interp))\n\tif c == nil {\n\t\treturn nil, nilPtrErr\n\t}\n\tobj := &glib.Object{glib.ToGObject(unsafe.Pointer(c))}\n\tp := &Pixbuf{obj}\n\truntime.SetFinalizer(obj, (*glib.Object).Unref)\n\treturn p, nil\n}", "func (v *Pixbuf) Scale(dst *Pixbuf, x, y, width, height int, offsetX, offsetY, scaleX, scaleY float64, interp InterpType) {\n\tC.gdk_pixbuf_scale(v.Native(), dst.Native(), C.int(x), C.int(y), C.int(width), C.int(height), C.double(offsetX), C.double(offsetY), C.double(scaleX), C.double(scaleY), C.GdkInterpType(interp))\n}", "func (s Size) ScaleUp(x, y int) Size {\n\ts.W *= x\n\ts.H *= y\n\treturn s\n}", "func resize(w io.Writer, r io.Reader, size []int) error {\n\timg, mimetype, err := image.Decode(r)\n\tif size == nil || err != nil {\n\t\tio.Copy(w, r)\n\t\treturn nil\n\t}\n\n\tib := img.Bounds()\n\n\tsize = fitToActualSize(&img, size)\n\tx := size[0]\n\ty := size[1]\n\n\t// set optimal thumbnail size\n\twrat := float64(x) / float64(ib.Dx())\n\thrat := float64(y) / float64(ib.Dy())\n\tif wrat <= hrat {\n\t\ty = int(wrat * float64(ib.Dy()))\n\t} else {\n\t\tx = int(hrat * float64(ib.Dx()))\n\t}\n\n\tdst := image.NewRGBA(image.Rect(0, 0, x, y))\n\tgraphics.Thumbnail(dst, img)\n\n\treturn writeByMimetype(w, dst, mimetype)\n}", "func (mw *MagickWand) Scale(cols, rows uint) error {\n\treturn mw.ScaleImage(cols, rows)\n}", "func adjustSize(dst types.Path, img image.Image, w, h int, crop bool, logger *log.Entry) (int, int, error) {\n\tvar out image.Image\n\tvar err error\n\tif crop {\n\t\tinAR := float64(img.Bounds().Dx()) / float64(img.Bounds().Dy())\n\t\toutAR := float64(w) / float64(h)\n\n\t\tvar scaleW, scaleH uint\n\t\tif inAR > outAR {\n\t\t\t// input has shorter AR than requested output so use requested height and calculate width to match input AR\n\t\t\tscaleW = uint(float64(h) * inAR)\n\t\t\tscaleH = uint(h)\n\t\t} else {\n\t\t\t// input has taller AR than requested output so use requested width and calculate height to match input AR\n\t\t\tscaleW = uint(w)\n\t\t\tscaleH = uint(float64(w) / inAR)\n\t\t}\n\n\t\tscaled := resize.Resize(scaleW, scaleH, img, resize.Lanczos3)\n\n\t\txoff := (scaled.Bounds().Dx() - w) / 2\n\t\tyoff := (scaled.Bounds().Dy() - h) / 2\n\n\t\ttr := image.Rect(0, 0, w, h)\n\t\ttarget := image.NewRGBA(tr)\n\t\tdraw.Draw(target, tr, scaled, image.Pt(xoff, yoff), draw.Src)\n\t\tout = target\n\t} else {\n\t\tout = resize.Thumbnail(uint(w), uint(h), img, resize.Lanczos3)\n\t}\n\n\tif err = writeFile(out, string(dst)); err != nil {\n\t\tlogger.WithError(err).Error(\"Failed to encode and write image\")\n\t\treturn -1, -1, err\n\t}\n\n\treturn out.Bounds().Max.X, out.Bounds().Max.Y, nil\n}", "func resize(src image.Image, targetBounds image.Rectangle, targetScaleDown int, stretch bool) (\n\t*image.NRGBA64, int, int) {\n\tvar xoffset, yoffset int\n\tvar newTargetBounds image.Rectangle\n\tif stretch {\n\t\tnewTargetBounds = image.Rectangle{\n\t\t\tMax: image.Point{\n\t\t\t\tX: targetBounds.Dx() / targetScaleDown,\n\t\t\t\tY: targetBounds.Dy() / targetScaleDown,\n\t\t\t},\n\t\t}\n\t} else {\n\t\t// Check if the source image is wider than the dest, or narrower. The odd multiplication\n\t\t// avoids casting to float, at the risk of possibly overflow. Don't use images taller or\n\t\t// wider than 32K on 32 bits machines.\n\t\tif src.Bounds().Dx()*targetBounds.Dy() > targetBounds.Dx()*src.Bounds().Dy() {\n\t\t\t// source image is wider.\n\t\t\tnewTargetBounds = image.Rectangle{\n\t\t\t\tMax: image.Point{\n\t\t\t\t\tX: targetBounds.Dx() / targetScaleDown,\n\t\t\t\t\tY: src.Bounds().Dy() * targetBounds.Dx() / src.Bounds().Dx() / targetScaleDown,\n\t\t\t\t},\n\t\t\t}\n\t\t\tyoffset = (targetBounds.Dy() - newTargetBounds.Dy()*targetScaleDown) / 2\n\t\t} else {\n\t\t\t// source image is narrower.\n\t\t\tnewTargetBounds = image.Rectangle{\n\t\t\t\tMax: image.Point{\n\t\t\t\t\tX: src.Bounds().Dx() * targetBounds.Dy() / src.Bounds().Dy() / targetScaleDown,\n\t\t\t\t\tY: targetBounds.Dy() / targetScaleDown,\n\t\t\t\t},\n\t\t\t}\n\t\t\txoffset = (targetBounds.Dx() - newTargetBounds.Dx()*targetScaleDown) / 2\n\t\t}\n\t}\n\n\tdst := image.NewNRGBA64(newTargetBounds)\n\tscaler := draw.CatmullRom\n\tscaler.Scale(dst, newTargetBounds, src, src.Bounds(), draw.Over, nil)\n\treturn dst, xoffset, yoffset\n}", "func DecodeAndCropJpegFancyUpscaling(value bool) DecodeAndCropJpegAttr {\n\treturn func(m optionalAttr) {\n\t\tm[\"fancy_upscaling\"] = value\n\t}\n}", "func resizeImage(i image.Image, max int) (image.Image) {\n\tif b := i.Bounds(); b.Dx() > max || b.Dy() > max {\n\t\tw, h := max, max\n if b.Dx() > b.Dy() {\n\t\t\t\th = b.Dy() * h / b.Dx()\n\t\t\t} else {\n\t\t\t\tw = b.Dx() * w / b.Dy()\n\t\t\t}\n\t i = resize.Resize(i, i.Bounds(), w, h)\n }\n\treturn i\n}", "func ResizeImage(src image.Image, maxWidth int64, maxHeight int64, square bool) (image.Image, error) {\n\tvar dst image.Image\n\n\t// Check the original dimensions first, and bail out if this image is not larger than max dimensions\n\tsrcSize := src.Bounds().Size()\n\tif int64(srcSize.X) < maxWidth && int64(srcSize.Y) < maxHeight {\n\t\treturn src, nil\n\t}\n\n\t// Use the original image dimensions to keep it in pro\n\t// Distorting images is a sin of which we are never guilty\n\tratio := float64(maxWidth) / float64(srcSize.X)\n\tyRatio := float64(maxHeight) / float64(srcSize.Y)\n\tif yRatio < ratio {\n\t\tratio = yRatio\n\t}\n\n\t// Now adjust desired width and height according to ratio\n\twidth := float64(srcSize.X) * ratio\n\theight := float64(srcSize.Y) * ratio\n\n\t// Create a new resized image with the desired dimensions and fill it with resized image data\n\t// We switch on input image type - is YCbCrSubsampleRatio444 correct?\n\tswitch src.(type) {\n\tcase *image.YCbCr:\n\t\tdst = image.NewYCbCr(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444)\n\tcase *image.RGBA:\n\t\tdst = image.NewRGBA(image.Rect(0, 0, int(width), int(height)))\n\tdefault:\n\t\tdst = nil\n\t}\n\n\terr := rez.Convert(dst, src, rez.NewBicubicFilter())\n\t// IF we want thumbnails to be square/cropped we could do this\n\t// for now we don't need this. We may not even want it for camping?\n\t// err := imaging.Thumbnail(srcImage, 100, 100, imaging.Lanczos)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn dst, nil\n\n}", "func (mw *MagickWand) PreserveJPEGSamplingFactor() error {\n\tfactors := mw.GetImageAttribute(\"JPEG-Sampling-factors\")\n\tif factors == \"1x1,1x1,1x1\" {\n\t\treturn mw.SetSamplingFactors([]float64{1, 1})\n\t}\n\treturn nil\n}", "func (s *Server) ScaleImage(ctx context.Context, req *api.ScaleImageRequest) (\n\t*api.ScaleImageReply, error) {\n\t// Echo\n\tfmt.Println(\"Recieved image...\")\n conn, err := grpc.Dial(host, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"did not connect: %v\", err)\n\t}\n\tdefer conn.Close()\n\tclient := pb.NewProcessorClient(conn)\n\n ctx = context.Background()\n\tresp, err := client.ProcessImage(ctx, &pb.ProcessImageRequest{\n\t\tImage: &pb.Image{\n Content: req.Image.GetContent(),\n Source: &pb.ImageSource{\n HttpUri: req.Image.Source.GetHttpUri(),\n },\n\t\t},\n Scale: s.Scale,\n Grayscale: s.Grayscale,\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\treturn &api.ScaleImageReply{\n\t\tContent: resp.GetContent(),\n\t}, nil\n}", "func (this *Transformable) Scale(factor Vector2f) {\n\tC.sfTransformable_scale(this.cptr, factor.toC())\n}", "func (dw *DrawingWand) Scale(x, y float64) {\n\tC.MagickDrawScale(dw.dw, C.double(x), C.double(y))\n}", "func Scale(f float64, d Number) Number {\n\treturn Number{Real: f * d.Real, E1mag: f * d.E1mag, E2mag: f * d.E2mag, E1E2mag: f * d.E1E2mag}\n}", "func (image *Image) Resize(dimensions *Dimensions, dest string) {\n\tfmt.Println(\"[Resize] \", image.Filename, dimensions)\n\n\tcmd := exec.Command(\"convert\", image.Filename, \"-auto-orient\", \"-resize\", dimensions.String+\">\", \"-quality\", \"80\", \"-strip\", \"-depth\", \"8\", dest)\n\tfmt.Println(\"[Resize] execute:\", cmd.Args)\n\tout, err := cmd.CombinedOutput()\n\n\tif err != nil {\n\t\tfmt.Println(\"[Resize] error: \", string(out[:]), err)\n\t}\n}", "func checkSize(img image.Image) image.Image {\n\tif img.Bounds().Dx() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(IMAGE_MAX_SIZE, 0, img, resize.Bilinear)\n\t}\n\n\tif img.Bounds().Dy() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(0, IMAGE_MAX_SIZE, img, resize.Bilinear)\n\t}\n\n\treturn img\n}", "func (client *VirtualMachineScaleSetsClient) reimage(ctx context.Context, resourceGroupName string, vmScaleSetName string, options *VirtualMachineScaleSetsBeginReimageOptions) (*http.Response, error) {\n\treq, err := client.reimageCreateRequest(ctx, resourceGroupName, vmScaleSetName, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tresp, err := client.pl.Do(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif !runtime.HasStatusCode(resp, http.StatusOK, http.StatusAccepted) {\n\t\treturn nil, client.reimageHandleError(resp)\n\t}\n\treturn resp, nil\n}", "func downscaleImage(src image.Image, w, h int) image.Image {\n\tdst := image.NewRGBA(image.Rect(0, 0, w, h))\n\n\tsrcwidth := src.Bounds().Dx()\n\tsrcheight := src.Bounds().Dy()\n\tfor y := dst.Bounds().Min.Y; y < dst.Bounds().Max.Y; y++ {\n\t\tfor x := dst.Bounds().Min.X; x < dst.Bounds().Max.X; x++ {\n\t\t\t//c := src.At(x*srcwidth/w, y*srcheight/h) // nearest-neighbour interpolation\n\t\t\tc := avgInterpolateAt(src, x*srcwidth/w, y*srcheight/h, srcwidth/w, srcheight/h)\n\t\t\tdst.Set(x, y, c)\n\t\t}\n\t}\n\treturn dst\n}", "func scaleFinalizer(s *Scale) {\n\truntime.SetFinalizer(s, func(s *Scale) { gobject.Unref(s) })\n}", "func (ki *KernelInfo) Scale(scale float64, normalizeType KernelNormalizeType) {\n\tC.ScaleKernelInfo(ki.info, C.double(scale), C.GeometryFlags(normalizeType))\n\truntime.KeepAlive(ki)\n}", "func ResizeImage(inputBuf []byte, outputWidth int, outputHeight int) ([]byte, error) {\n\t// The decoder instantiation performs some basic checks,\n\t// such as magic bytes checking to match some known formats.\n\tdecoder, err := lilliput.NewDecoder(inputBuf)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to decode image: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\tdefer decoder.Close()\n\n\theader, err := decoder.Header()\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read image header: %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\tif decoder.Duration() != 0 {\n\t\tfmt.Printf(\"duration: %.2f s\\n\", float64(decoder.Duration())/float64(time.Second))\n\t}\n\n\tops := lilliput.NewImageOps(8192)\n\tdefer ops.Close()\n\n\tvar outputImg []byte\n\n\t// If shrinking the file, use a buffer the size of the original image.\n\t// If increasing the size, use a maximum of 50MB.\n\t// This is done to try and conserve memory allocations.\n\tif header.Width() > outputWidth || header.Height() > outputHeight {\n\t\toutputImg = make([]byte, 50*1024*1024)\n\t} else {\n\t\toutputImg = make([]byte, len(inputBuf))\n\t}\n\n\tif outputWidth == 0 {\n\t\toutputWidth = header.Width()\n\t}\n\tif outputHeight == 0 {\n\t\toutputHeight = header.Height()\n\t}\n\n\tresizeMethod := lilliput.ImageOpsResize\n\n\tif outputWidth == header.Width() && outputHeight == header.Height() {\n\t\tresizeMethod = lilliput.ImageOpsNoResize\n\t}\n\n\toutputType := \".\" + strings.ToLower(decoder.Description())\n\n\topts := &lilliput.ImageOptions{\n\t\tFileType: outputType,\n\t\tWidth: outputWidth,\n\t\tHeight: outputHeight,\n\t\tResizeMethod: resizeMethod,\n\t\tNormalizeOrientation: true,\n\t\tEncodeOptions: EncodeOptions[outputType],\n\t}\n\n\toutputImg, err = ops.Transform(decoder, opts, outputImg)\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to transform image, %s\\n\", err)\n\t\treturn nil, err\n\t}\n\n\treturn outputImg, nil\n}", "func (t *Transform) Scale(sx, sy float64) {\n\tout := fmt.Sprintf(\"scale(%g,%g)\", sx, sy)\n\n\tt.transforms = append(t.transforms, out)\n}", "func Resize(img image.Image) image.Image {\n\treturn imaging.Resize(img, width, height, imaging.Linear)\n}", "func resizeImage(buffer []byte, width int, height int) (*resizedImage, error) {\n\timage, err := vips.ResizeImage(buffer, width, height)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &resizedImage{\n\t\tvipsImage: image,\n\t}, nil\n}", "func Hide(w io.Writer, m image.Image, data []byte, o *jpeg.Options) error {\n\tb := m.Bounds()\n\tif b.Dx() >= 1<<16 || b.Dy() >= 1<<16 {\n\t\treturn errors.New(\"jpeg: image is too large to encode\")\n\t}\n\tvar e encoder\n\te.data = data\n\tif ww, ok := w.(writer); ok {\n\t\te.w = ww\n\t} else {\n\t\te.w = bufio.NewWriter(w)\n\t}\n\t// Clip quality to [1, 100].\n\tquality := jpeg.DefaultQuality\n\tif o != nil {\n\t\tquality = o.Quality\n\t\tif quality < 1 {\n\t\t\tquality = 1\n\t\t} else if quality > 100 {\n\t\t\tquality = 100\n\t\t}\n\t}\n\t// Convert from a quality rating to a scaling factor.\n\tvar scale int\n\tif quality < 50 {\n\t\tscale = 5000 / quality\n\t} else {\n\t\tscale = 200 - quality*2\n\t}\n\t// Initialize the quantization tables.\n\tfor i := range e.quant {\n\t\tfor j := range e.quant[i] {\n\t\t\tx := int(unscaledQuant[i][j])\n\t\t\tx = (x*scale + 50) / 100\n\t\t\tif x < 1 {\n\t\t\t\tx = 1\n\t\t\t} else if x > 255 {\n\t\t\t\tx = 255\n\t\t\t}\n\t\t\te.quant[i][j] = uint8(x)\n\t\t}\n\t}\n\t// Compute number of components based on input image type.\n\tnComponent := 3\n\tswitch m.(type) {\n\tcase *image.Gray:\n\t\tnComponent = 1\n\t}\n\t// Write the Start Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd8\n\te.write(e.buf[:2])\n\t// Write the quantization tables.\n\te.writeDQT()\n\t// Write the image dimensions.\n\te.writeSOF0(b.Size(), nComponent)\n\t// Write the Huffman tables.\n\te.writeDHT(nComponent)\n\t// Write the image data.\n\te.writeSOS(m)\n\tif len(e.data) > 0 {\n\t\treturn ErrTooSmall\n\t}\n\t// Write the End Of Image marker.\n\te.buf[0] = 0xff\n\te.buf[1] = 0xd9\n\te.write(e.buf[:2])\n\te.flush()\n\treturn e.err\n}", "func scale_space_extrema(dog_pyr [][]*SiftImage, contr_thr float64, curv_thr int) {\n\toctvs := len(dog_pyr)\n\tintvls := len(dog_pyr[0]) - 2\n\tprelim_contr_thr := 0.5 * contr_thr / float64(intvls) * 256\n\tfor o := 0; o < octvs; o++ {\n\t\timgBounds := dog_pyr[o][0].Bounds()\n\t\tfor i := 1; i <= intvls; i++ {\n\t\t\tfor r := SIFT_IMG_BORDER; r < imgBounds.Dy()-SIFT_IMG_BORDER; r++ {\n\t\t\t\tfor c := SIFT_IMG_BORDER; c < imgBounds.Dx()-SIFT_IMG_BORDER; c++ {\n\t\t\t\t\tif math.Abs(pixval32f(dog_pyr[o][i], r, c)) > prelim_contr_thr {\n\t\t\t\t\t\tif is_extremum(dog_pyr, octvs, intvls, r, c) {\n\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func resize(reader io.Reader, limit int) io.Reader {\n\tif reader == nil {\n\t\tlog.Print(\"[WARN] avatar resize(): reader is nil\")\n\t\treturn nil\n\t}\n\tif limit <= 0 {\n\t\tlog.Print(\"[DEBUG] avatar resize(): limit should be greater than 0\")\n\t\treturn reader\n\t}\n\n\tvar teeBuf bytes.Buffer\n\ttee := io.TeeReader(reader, &teeBuf)\n\tsrc, _, err := image.Decode(tee)\n\tif err != nil {\n\t\tlog.Printf(\"[WARN] avatar resize(): can't decode avatar image, %s\", err)\n\t\treturn &teeBuf\n\t}\n\n\tbounds := src.Bounds()\n\tw, h := bounds.Dx(), bounds.Dy()\n\tif w <= limit && h <= limit || w <= 0 || h <= 0 {\n\t\tlog.Print(\"[DEBUG] resizing image is smaller that the limit or has 0 size\")\n\t\treturn &teeBuf\n\t}\n\tnewW, newH := w*limit/h, limit\n\tif w > h {\n\t\tnewW, newH = limit, h*limit/w\n\t}\n\tm := image.NewRGBA(image.Rect(0, 0, newW, newH))\n\t// Slower than `draw.ApproxBiLinear.Scale()` but better quality.\n\tdraw.BiLinear.Scale(m, m.Bounds(), src, src.Bounds(), draw.Src, nil)\n\n\tvar out bytes.Buffer\n\tif err = png.Encode(&out, m); err != nil {\n\t\tlog.Printf(\"[WARN] avatar resize(): can't encode resized avatar to PNG, %s\", err)\n\t\treturn &teeBuf\n\t}\n\treturn &out\n}", "func (r *ImageRef) Zoom(xFactor int, yFactor int) error {\n\tout, err := vipsZoom(r.image, xFactor, yFactor)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func (r *ImageRef) Multiply(multiplier *ImageRef) error {\n\tout, err := vipsMultiply(r.image, multiplier.image)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func Scale(value float64) *SimpleElement { return newSEFloat(\"scale\", value) }", "func (is imageServiceServer) NewImageResizeAtDimensions(ctx context.Context, images *pb.NewImageRequest) (*pb.NewImageResponse, error) {\n\tdataArray, invalidArray := getValidContentTypes(images.GetImage())\n\tresponse := pb.NewImageResponse{}\n\tdimensions := images.GetDimensions()\n\tw := dimensions.GetHeight()\n\th := dimensions.GetWidth()\n\tif w == 0 || h == 0 {\n\t\tlog.Println(\"Invalid image dimensions.\")\n\t\treturn &response, status.Error(codes.InvalidArgument, invalidDimensionsErrorString)\n\t}\n\tfor _, b := range dataArray {\n\t\tbuf := new(bytes.Buffer)\n\t\t_, e := buf.Write(b)\n\t\tif e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tvar s string\n\t\ts, e = rs.ResizeMem(buf, int(w), int(h))\n\t\tkey := rs.MakeRandomString(15)\n\t\tif e := is.S3.S3Put(s3.DefaultBucket, string(key), buf, s); e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tlink := fmt.Sprintf(\"https://%s/%s/%s\", s3.S3Endpoint, s3.DefaultBucket, string(key))\n\t\tmdl := models.Image{LinkResized: null.NewString(link, true)}\n\t\tif e = mdl.Insert(ctx, db, boil.Infer()); e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tresponse.Structure = append(response.Structure, &pb.NewImageResponseStruct{ResizedLink: link, ResizedID: uint32(mdl.ID)})\n\t}\n\tif len(invalidArray) > 0 {\n\t\treturn &response, status.Error(codes.InvalidArgument, fmt.Sprintf(errorInvalidContentFound, invalidArray))\n\t}\n\treturn &response, nil\n}", "func (canvas *Canvas) Scale(x, y float32) {\n\twriteCommand(canvas.contents, \"cm\", x, 0, 0, y, 0, 0)\n}", "func resize(imagePath string, w, h int) error {\n\ti, e := imgio.Open(imagePath)\n\tif e != nil {\n\t\treturn e\n\t}\n\tresized := transform.Resize(i, w, h, transform.Linear)\n\te = imgio.Save(imagePath, resized, imgio.JPEGEncoder(100))\n\treturn e\n}", "func Thumb(img image.Image, area Area, size Size) image.Image {\n\t// Get absolute crop coordinates and dimension.\n\tmin, max, _ := area.Bounds(img)\n\n\t/*\n\t\tif dim < size.Width {\n\t\t\tlog.Printf(\"crop: image is too small, upscaling %dpx to %dpx\", dim, size.Width)\n\t\t}\n\t*/\n\n\t// Crop area from image.\n\tthumb := imaging.Crop(img, image.Rect(min.X, min.Y, max.X, max.Y))\n\n\t// Resample crop area.\n\treturn Resample(thumb, size.Width, size.Height, size.Options...)\n}", "func MakeThumbnail(encoded []byte, suffix, thumbnailSize string) []byte {\n\tsize := strings.Split(thumbnailSize, \"x\")\n\tif len(size) != 2 {\n\t\treturn nil\n\t}\n\tx, err1 := strconv.Atoi(size[0])\n\ty, err2 := strconv.Atoi(size[1])\n\tif err1 != nil || err2 != nil {\n\t\tlog.Println(thumbnailSize, \"is illegal format\")\n\t\treturn nil\n\t}\n\n\tfile := bytes.NewReader(encoded)\n\timg, _, err := image.Decode(file)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil\n\t}\n\tm := resize.Resize(uint(x), uint(y), img, resize.Lanczos3)\n\tvar out bytes.Buffer\n\tswitch suffix {\n\tcase \"jpg\", \"jpeg\":\n\t\terr = jpeg.Encode(&out, m, nil)\n\tcase \"png\":\n\t\terr = png.Encode(&out, m)\n\tcase \"gif\":\n\t\terr = gif.Encode(&out, m, nil)\n\tdefault:\n\t\tlog.Println(\"illegal format\", suffix)\n\t}\n\tif err != nil {\n\t\tlog.Println(err)\n\t}\n\treturn out.Bytes()\n}", "func (gip *GiftImageProcessor) Hipsterize(src image.Image, buf *bytes.Buffer) error {\n\n\tdst := image.NewRGBA(gip.filterChain.Bounds(src.Bounds()))\n\n\t// Use Draw func to apply the filters to src and store the result in dst:\n\tgip.filterChain.Draw(dst, src)\n\n\treturn jpeg.Encode(buf, dst, nil)\n}", "func (m *GrayImage) Resize(sz Size) {\n\tm.Size = sz\n\tl := sz.Area()\n\tif cap(m.Pixels) >= l {\n\t\tm.Pixels = m.Pixels[:l]\n\t} else {\n\t\tm.Pixels = make([]byte, l)\n\t}\n}", "func main() {\n\toutFilename := flag.String(\"out\", \"\", \"output file name\")\n\tquality := flag.Int(\"q\", 80, \"output JPEG quality\")\n\tflag.Parse()\n\tif len(flag.Args()) != 1 {\n\t\tlog.Fatalf(\"expected exactly 1 input file name\")\n\t}\n\n\tfilename := flag.Args()[0] // Image to convert\n\n\tswitch {\n\tcase *quality < 0:\n\t\t*quality = 0\n\tcase *quality > 100:\n\t\t*quality = 100\n\t}\n\n\tf, err := os.Open(filename)\n\tif err != nil {\n\t\tlog.Panicf(\"open input image: %v\", err)\n\t}\n\tdefer f.Close()\n\n\timg, err := png.Decode(f)\n\tif err != nil {\n\t\tlog.Panicf(\"decode input image: %v\", err)\n\t}\n\n\tif *outFilename == \"\" {\n\t\t*outFilename = strings.ReplaceAll(filename, \"png\", \"jpg\")\n\t}\n\n\toutFile, err := os.Create(*outFilename)\n\tif err != nil {\n\t\tlog.Panicf(\"create file: %v\", err)\n\t}\n\tdefer outFile.Close()\n\n\topts := &jpeg.Options{Quality: *quality}\n\tif err := jpeg.Encode(outFile, img, opts); err != nil {\n\t\tlog.Panicf(\"encode: %v\", err)\n\t}\n}", "func (mw *MagickWand) CubicResize(cols, rows uint) error {\n\treturn mw.ResizeImage(cols, rows, gmagick.FILTER_CUBIC, 0.5)\n}", "func (contour DrawContour) resizeByFactor(factor int) {\n\tcontour.factor = factor\n}", "func (r *ImageRef) Resize(scale float64, kernel Kernel) error {\n\treturn r.ResizeWithVScale(scale, -1, kernel)\n}", "func ScaleSprite(src *ebiten.Image, x, y float64) (*ebiten.Image, error) {\n\tspriteW, spriteH := src.Size()\n\tsSprite, sSpriteErr := ebiten.NewImage(\n\t\tint(float64(spriteW)*x),\n\t\tint(float64(spriteH)*y),\n\t\tebiten.FilterDefault)\n\tif sSpriteErr != nil {\n\t\treturn nil, sSpriteErr\n\t}\n\n\tops := &ebiten.DrawImageOptions{}\n\tops.GeoM.Scale(x, y)\n\tif drawErr := sSprite.DrawImage(src, ops); drawErr != nil {\n\t\treturn nil, drawErr\n\t}\n\n\treturn sSprite, nil\n}", "func (v *IBM) ResizeImage(ctx *lepton.Context, imagename string, hbytes string) error {\n\treturn fmt.Errorf(\"operation not supported\")\n}", "func (l *Legofy) getNewSize(baseImage image.Image, brickImg image.Image, size int) (int, int) {\n\tnewImageSize := baseImage.Bounds()\n\tbrickSize := brickImg.Bounds()\n\tscaleX, scaleY := 0, 0\n\tif size != 0 {\n\t\tscaleX, scaleY = size, size\n\t} else {\n\t\tscaleX, scaleY = brickSize.Max.X, brickSize.Max.Y\n\t}\n\n\tif newImageSize.Max.X > scaleX || newImageSize.Max.Y > scaleY {\n\t\tscale := 0.00\n\t\tif newImageSize.Max.X < newImageSize.Max.Y {\n\t\t\tscale = float64(newImageSize.Max.Y) / float64(scaleY)\n\t\t} else {\n\t\t\tscale = float64(newImageSize.Max.X) / float64(scaleX)\n\t\t}\n\n\t\treturn int(math.Floor(float64(newImageSize.Max.X) / float64(scale))), int(math.Floor(float64(newImageSize.Max.Y) / float64(scale)))\n\t}\n\treturn newImageSize.Max.X, newImageSize.Max.Y\n}", "func expandAutoscalingDimension(autoscale v1.ElasticsearchTopologyAutoscalingTF, model *models.TopologySize, size, sizeResource types.String) error {\n\tif size.ValueString() != \"\" {\n\t\tval, err := deploymentsize.ParseGb(size.ValueString())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tmodel.Value = &val\n\n\t\tif model.Resource == nil {\n\t\t\tmodel.Resource = ec.String(\"memory\")\n\t\t}\n\t}\n\n\tif sizeResource.ValueString() != \"\" {\n\t\tmodel.Resource = ec.String(sizeResource.ValueString())\n\t}\n\n\treturn nil\n}", "func (tr *trooper) setScale(scale float64) { tr.part.SetScale(scale, scale, scale) }", "func applyScaleMeta(meta *runapi.ObjectMeta, scaleType string, scaleValue int) {\n\tif scaleValue > 0 {\n\t\tmeta.Annotations[\"autoscaling.knative.dev\"+scaleType] = strconv.Itoa(scaleValue)\n\t}\n}", "func (this *Decider) OnScale(command common.Command) error {\n\tappMetrical := AppMetrical{}\n\terr := json.Unmarshal([]byte(command.Body), &appMetrical)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tappInfo, strategyName := this.getAppInfo(appMetrical.App)\n\tif appInfo == nil {\n\t\tlog.Printf(\"can not get app info, may be the strategy is disabled.\")\n\t\treturn nil\n\t}\n\n\tscaleNumber, err := getScaleNumber(appMetrical.Metrical, appInfo.AppConf)\n\tif err != nil {\n\t\tlog.Printf(\"get scale number error [%s] : %s\", appMetrical.App, err)\n\t\treturn err\n\t}\n\n\tlog.Printf(\"get scale number: %d\", scaleNumber)\n\n\tif scaleNumber <= 0 {\n\t\t// Do nothing except set the new metrical\n\t\treturn nil\n\t} else if scaleNumber > 0 {\n\t\tappScales := this.getAppScales(strategyName, appInfo, scaleNumber)\n\t\tfmt.Println(\"===need scale=====\", appScales)\n\n\t\tmetricalAppScales := []common.MetricalAppScale{}\n\n\t\tfor _, app := range appScales {\n\t\t\taInfo, _ := this.getAppInfo(app.App)\n\t\t\tmetricalAppScales = append(metricalAppScales,\n\t\t\t\tcommon.MetricalAppScale{app.App, app.Number, aInfo.AppConf.MinNum})\n\t\t}\n\n\t\tmetricalAppScales = append(metricalAppScales,\n\t\t\tcommon.MetricalAppScale{appInfo.AppConf.App,\n\t\t\t\tscaleNumber, appInfo.AppConf.MinNum})\n\n\t\tmetricalAppScaleHosts, e := this.Client.MetricalScaleApps(metricalAppScales)\n\n\t\tif e != nil {\n\t\t\tlog.Printf(\"get metrical app scale hosts failed [%s]\", e)\n\t\t\treturn e\n\t\t}\n\t\tfmt.Println(\"get metrical app scale hosts\", metricalAppScaleHosts)\n\t\t// publish messages to apps\n\t\tpublishMessagesToApps(metricalAppScaleHosts, appInfo.AppConf.App)\n\t}\n\n\tdefer func() {\n\t\t// update current metrical\n\t\t(*appInfo).CurrentMetrical = appMetrical.Metrical\n\t}()\n\n\treturn nil\n}", "func (montage *Montage) drawImage(img image.Image, imageLayout *ImagePlacement) error {\n\t// resize to fit the available space\n\tresizedImg := img\n\tswitch imageLayout.Resize {\n\tcase MontageResizeWidth:\n\t\tresizedImg = imaging.Resize(img, imageLayout.Width, 0, montage.resizing)\n\tcase MontageResizeHeight:\n\t\tresizedImg = imaging.Resize(img, 0, imageLayout.Height, montage.resizing)\n\tcase MontageResizeCrop:\n\t\tresizedImg = imaging.Thumbnail(img, imageLayout.Width, imageLayout.Height, montage.resizing)\n\tcase MontageResizeScale:\n\t\tresizedImg = imaging.Resize(img, imageLayout.Width, imageLayout.Height, montage.resizing)\n\tcase MontageResizeNone:\n\tdefault: // default is not to resize\n\t\t// resizedImg = imaging.Resize(img, 0, imageLayout.Height, montage.Resizing)\n\t\tresizedImg = img\n\t}\n\n\t// Embed the image centered in its place into the main montage image\n\t// imageSize := resizedImg.Bounds()\n\t// xOffset := (imageLayout.Width - imageSize.Max.X) / 2\n\t// if xOffset < 0 {\n\t// \txOffset = 0\n\t// }\n\t// yOffset := (imageLayout.Height - imageSize.Max.Y) / 2\n\t// if yOffset < 0 {\n\t// \tyOffset = 0\n\t// }\n\t// rectangle := image.Rect(imageLayout.X+xOffset, imageLayout.Y+yOffset,\n\t// \timageLayout.X+imageLayout.Width, imageLayout.Y+imageLayout.Height)\n\trectangle := image.Rect(imageLayout.X, imageLayout.Y,\n\t\timageLayout.X+imageLayout.Width, imageLayout.Y+imageLayout.Height)\n\tdraw.Draw(montage.canvas, rectangle, resizedImg, image.ZP, draw.Src)\n\n\tmontage.UpdateCount++\n\treturn nil\n}", "func GenImg(file io.Reader, ext string, numshapes int, mode primitive.Mode) (string, error) {\n\toutput, err := primitive.TransformImg(file, ext, numshapes, primitive.ArgMode(mode))\n\tif err != nil {\n\t\t//http.Error(resp, err.Error(), http.StatusInternalServerError)\n\t\treturn \"\", err\n\t}\n\n\tsaveout, err := getExtFile(\"\", ext)\n\tif err != nil {\n\t\t//http.Error(resp, err.Error(), http.StatusInternalServerError)\n\t\treturn \"\", err\n\t}\n _,err = CopyFunc(saveout, output)\n if err!=nil{\n return \"\",err\n }\n\n\treturn saveout.Name(), err\n}", "func SizedImage(id, ref string, size int64, configName *string) imageapi.Image {\n\timage := ImageWithLayers(id, ref, configName, Layer1, Layer2, Layer3, Layer4, Layer5)\n\timage.CreationTimestamp = metav1.NewTime(metav1.Now().Add(time.Duration(-1) * time.Minute))\n\timage.DockerImageMetadata.Size = size\n\n\treturn image\n}", "func ImageMagickThumbnailer(convertPath string, conf *Config) Thumbnailer {\n\tif conf == nil {\n\t\tconf = defaultCfg\n\t}\n\treturn &ExecThumbnailer{\n\t\tExec: convertPath,\n\t\tAccept: regexp.MustCompilePOSIX(`\\.(png|jpg|jpeg|gif|webp)$`),\n\t\tGenArgs: func(inf, outf string) []string {\n\t\t\tif strings.HasSuffix(inf, \".gif\") {\n\t\t\t\tinf += \"[0]\"\n\t\t\t}\n\t\t\tif conf.JpegOnly {\n\t\t\t\toutf += \".jpeg\"\n\t\t\t}\n\t\t\treturn []string{\"-thumbnail\", fmt.Sprintf(\"%d\", conf.ThumbW), inf, outf}\n\t\t},\n\t}\n}", "func resizeImage(img image.Image, w, h int) image.Image {\n\treturn resize.Resize(uint(w), uint(h), img, resize.Lanczos3)\n}", "func (r *ImageRef) ResizeWithVScale(hScale, vScale float64, kernel Kernel) error {\n\tif err := r.PremultiplyAlpha(); err != nil {\n\t\treturn err\n\t}\n\n\tpages := r.Pages()\n\tpageHeight := r.GetPageHeight()\n\n\tout, err := vipsResizeWithVScale(r.image, hScale, vScale, kernel)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\n\tif pages > 1 {\n\t\tscale := hScale\n\t\tif vScale != -1 {\n\t\t\tscale = vScale\n\t\t}\n\t\tnewPageHeight := int(float64(pageHeight) * scale)\n\t\tif err := r.SetPageHeight(newPageHeight); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn r.UnpremultiplyAlpha()\n}", "func Test_ResizeOperation_MaxWidthIsValidForJPEG(t *testing.T) {\n\timg := getMockImageJPEG()\n\top := &ResizeOperation{\n\t\tNewWidth: 5000,\n\t\tNewHeight: 300,\n\t\tImage: &img,\n\t}\n\n\tassert.Equal(t, false, op.IsValid())\n}", "func downsample(srcImg image.Image) image.Image {\n\tbounds := srcImg.Bounds()\n\treturn resize.Resize(bounds.Dx()/2, bounds.Dy()/2, srcImg, resize.Bilinear)\n}", "func scale(up bool) {\n\tif Font.TTF == nil {\n\t\treturn\n\t}\n\tif up {\n\t\tFont.size++\n\t} else if Font.size < 5 {\n\t\treturn\n\t} else {\n\t\tFont.size--\n\t}\n\tSetFont(Font.TTF, Font.size)\n}", "func Test_ResizeOperation_MaxHeightIsValidJPEG(t *testing.T) {\n\timg := getMockImageJPEG()\n\top := &ResizeOperation{\n\t\tNewWidth: 500,\n\t\tNewHeight: 5000,\n\t\tImage: &img,\n\t}\n\n\tassert.Equal(t, false, op.IsValid())\n}", "func (x *Big) Scale() int { return -x.exp }", "func Imag(x Value) Value {\n\tif _, ok := x.(*ratVal); ok {\n\t\treturn constant.MakeInt64(0)\n\t}\n\treturn constant.Imag(x)\n}", "func TestIssue513(t *testing.T) {\n\topts := &DecodeOpts{MaxWidth: 2000, MaxHeight: 256}\n\tfor _, rect := range issue513tests {\n\t\tbuf := &bytes.Buffer{}\n\t\terr := jpeg.Encode(buf, image.NewRGBA(rect), nil)\n\t\tif err != nil {\n\t\t\tt.Fatalf(\"Failed to encode test image: %v\", err)\n\t\t}\n\t\tfunc() {\n\t\t\tdefer func() {\n\t\t\t\tif r := recover(); r != nil {\n\t\t\t\t\tt.Errorf(\"Unexpected panic for image size %dx%d: %v\", rect.Dx(), rect.Dy(), r)\n\t\t\t\t}\n\t\t\t}()\n\t\t\t_, format, err, needsRescale := decode(buf, opts, false)\n\t\t\tif err != nil {\n\t\t\t\tt.Errorf(\"Unexpected error for image size %dx%d: %v\", rect.Dx(), rect.Dy(), err)\n\t\t\t}\n\t\t\tif format != \"jpeg\" {\n\t\t\t\tt.Errorf(\"Unexpected format for image size %dx%d: got %q want %q\", rect.Dx(), rect.Dy(), format, \"jpeg\")\n\t\t\t}\n\t\t\tif needsRescale != (rect.Dx() > opts.MaxWidth || rect.Dy() > opts.MaxHeight) {\n\t\t\t\tt.Errorf(\"Unexpected rescale for image size %dx%d: needsRescale = %t\", rect.Dx(), rect.Dy(), needsRescale)\n\t\t\t}\n\t\t}()\n\t}\n}", "func Test_QualityOperation_IsValidTrue(t *testing.T) {\n\timg := MakeMockMutableImage()\n\top := &QualityOperation{\n\t\tImage: &img,\n\t\tNewQuality: 90,\n\t}\n\n\tassert.Equal(t, true, op.IsValid())\n}", "func (c *canvasRenderer) Scale(amount sprec.Vec2) {\n\tc.currentLayer.Transform = sprec.Mat4Prod(\n\t\tc.currentLayer.Transform,\n\t\tsprec.ScaleMat4(amount.X, amount.Y, 1.0),\n\t)\n}", "func (self *Rectangle) ScaleI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", args)}\n}", "func HandleImage(w http.ResponseWriter, r *http.Request){\n\timageName := r.FormValue(\"name\")\n\timage := images[imageName]\n\tjpeg.Encode(w, image, &jpeg.Options{Quality: jpeg.DefaultQuality})\n}", "func Transform(mid Middler, file string, name string, outfile string) error {\n\timg, err := loadImage(file)\n\tout, err := os.Create(outfile)\n\tdefer out.Close()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"can't open file for writing\")\n\t}\n\tmiddle, err := mid(img)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Problem with middle detection %v\", err)\n\t}\n\tdst := mirroredImage(img, middle)\n\tjpeg.Encode(out, dst, &jpeg.Options{Quality: 100})\n\treturn nil\n}", "func Imagify(art ASCIIArt, palette CharacterPalette) (image.Image, error) {\n\tbounds := image.Rect(0, 0, len(art[0]), len(art))\n\timg := image.NewRGBA(bounds)\n\n\tfor y, col := range art {\n\t\tfor x, row := range col {\n\t\t\tcol, err := palette.color(row)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\timg.Set(x, y, col)\n\t\t}\n\t}\n\n\treturn img, nil\n}", "func (mg *Groups) Scale(instances int, force bool) error {\n\n\tif mg.group != nil && len(mg.group.ID) > 0 {\n\t\tif appClient := application.New(mg.client); appClient != nil {\n\n\t\t\tcallbackFunc := func(appID string) error {\n\n\t\t\t\tif err := appClient.Get(appID).Scale(instances, force); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn mg.traverseGroupsWithAppID(mg.group, callbackFunc)\n\t\t}\n\t\treturn fmt.Errorf(\"unnable to connect\")\n\t}\n\treturn errors.New(\"group cannot be null nor empty\")\n}", "func hookSetImageSize(e *evtx.GoEvtxMap) {\n\tvar path *evtx.GoEvtxPath\n\tvar modpath *evtx.GoEvtxPath\n\tswitch e.EventID() {\n\tcase 1:\n\t\tpath = &pathSysmonImage\n\t\tmodpath = &pathImSize\n\tdefault:\n\t\tpath = &pathSysmonImageLoaded\n\t\tmodpath = &pathImLoadedSize\n\t}\n\tif image, err := e.GetString(path); err == nil {\n\t\tif fsutil.IsFile(image) {\n\t\t\tif stat, err := os.Stat(image); err == nil {\n\t\t\t\te.Set(modpath, toString(stat.Size()))\n\t\t\t}\n\t\t}\n\t}\n}", "func hookSetImageSize(e *evtx.GoEvtxMap) {\n\tvar path *evtx.GoEvtxPath\n\tvar modpath *evtx.GoEvtxPath\n\tswitch e.EventID() {\n\tcase 1:\n\t\tpath = &sysmonImage\n\t\tmodpath = &imSizePath\n\tdefault:\n\t\tpath = &sysmonImageLoaded\n\t\tmodpath = &imLoadedSizePath\n\t}\n\tif image, err := e.GetString(path); err == nil {\n\t\tif fsutil.IsFile(image) {\n\t\t\tif stat, err := os.Stat(image); err == nil {\n\t\t\t\te.Set(modpath, stat.Size())\n\t\t\t}\n\t\t}\n\t}\n}", "func resizeWrapper() js.Func {\n\treturn js.FuncOf(func(this js.Value, args []js.Value) interface{} {\n\t\tif len(args) != 3 {\n\t\t\treturn \"Should pass 3 arguments\"\n\t\t}\n\t\tjsFile := args[0]\n\t\theight := args[1].Int()\n\t\twidth := args[2].Int()\n\n\t\timgBytes := getBytesFromJsValue(jsFile)\n\t\timg, err := getImageFromByte(imgBytes)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\t\tresized := resizeImage(img, width, height)\n\t\tresizedJsValue, err := imageToJsValue(resized)\n\t\tif err != nil {\n\t\t\treturn err.Error()\n\t\t}\n\n\t\treturn resizedJsValue\n\t})\n}", "func (is imageServiceServer) NewImageResize(ctx context.Context, images *pb.NewImageRequest) (*pb.NewImageResponse, error) {\n\tdataArray, invalidArray := getValidContentTypes(images.GetImage())\n\tresponse := pb.NewImageResponse{}\n\tfor _, b := range dataArray {\n\t\tbuf := new(bytes.Buffer)\n\t\tvar e [2]error\n\t\t_, e[0] = buf.Write(b)\n\t\tvar s string\n\t\ts, e[1] = rs.ResizeMem(buf, defaultWidth, defaultHeight)\n\t\tif haserr(e[:]) {\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tkey := string(rs.MakeRandomString(15))\n\t\tif e := is.S3.S3Put(s3.DefaultBucket, key, buf, fmt.Sprintf(\"image/%s\", s)); e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tlink := fmt.Sprintf(\"https://%s/%s/%s\", s3.S3Endpoint, s3.DefaultBucket, key)\n\t\tnewLink := models.Image{LinkResized: null.NewString(link, true)}\n\t\tif e := newLink.Insert(ctx, db, boil.Infer()); e != nil {\n\t\t\tlog.Println(e.Error())\n\t\t\treturn &response, status.Error(codes.Internal, errorStringInternal)\n\t\t}\n\t\tresponse.Link = append(response.Link, link)\n\t\tresponse.Structure = append(response.Structure, &pb.NewImageResponseStruct{ResizedLink: link, ResizedID: uint32(newLink.ID)})\n\t}\n\tif len(invalidArray) > 0 {\n\t\treturn &response, status.Error(codes.InvalidArgument, fmt.Sprintf(errorInvalidContentFound, invalidArray))\n\t}\n\treturn &response, nil\n}", "func (v *Vec4) Scale(s float32) {\n\tv.X *= s\n\tv.Y *= s\n\tv.Z *= s\n\tv.W *= s\n}", "func MakeImag(x Value) Value {\n\tif v, ok := x.(*ratVal); ok {\n\t\tx = v.Value\n\t}\n\treturn constant.MakeImag(x)\n}", "func MRThumbUp(pid interface{}, id int) error {\n\t_, _, err := lab.AwardEmoji.CreateMergeRequestAwardEmoji(pid, id, &gitlab.CreateAwardEmojiOptions{\n\t\tName: \"thumbsup\",\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func qr_decoder_set_image_size(p _QrDecoderHandle, width, height, depth, channel int) _QrDecoderHandle {\n\tv := C.qr_decoder_set_image_size(C.QrDecoderHandle(p),\n\t\tC.int(width), C.int(height), C.int(depth), C.int(channel),\n\t)\n\treturn _QrDecoderHandle(v)\n}", "func (self *Rectangle) Scale1O(x int, y int) *Rectangle{\n return &Rectangle{self.Object.Call(\"scale\", x, y)}\n}", "func (blk *Block) Scale(sx, sy float64) {\n\tops := contentstream.NewContentCreator().\n\t\tScale(sx, sy).\n\t\tOperations()\n\n\t*blk.contents = append(*ops, *blk.contents...)\n\tblk.contents.WrapIfNeeded()\n\n\tblk.width *= sx\n\tblk.height *= sy\n}", "func (tt *telloTrackT) deriveScale() (scale float32) {\n\tscale = 1.0 // minimum scale value\n\tif tt.maxX > scale {\n\t\tscale = tt.maxX\n\t}\n\tif -tt.minX > scale {\n\t\tscale = -tt.minX\n\t}\n\tif tt.maxY > scale {\n\t\tscale = tt.maxY\n\t}\n\tif -tt.minY > scale {\n\t\tscale = -tt.minY\n\t}\n\tscale = float32(math.Ceil(float64(scale)))\n\treturn scale\n}", "func scale(dst *block, src *[4]block) {\n\tfor i := 0; i < 4; i++ {\n\t\tdstOff := (i&2)<<4 | (i&1)<<2\n\t\tfor y := 0; y < 4; y++ {\n\t\t\tfor x := 0; x < 4; x++ {\n\t\t\t\tj := 16*y + 2*x\n\t\t\t\tsum := src[i][j] + src[i][j+1] + src[i][j+8] + src[i][j+9]\n\t\t\t\tdst[8*y+x+dstOff] = (sum + 2) >> 2\n\t\t\t}\n\t\t}\n\t}\n}", "func (b *Base) Scale(w http.ResponseWriter, r *http.Request) {\n\tb.log.Printf(\"%s %s -> %s\", r.Method, r.URL.Path, r.RemoteAddr)\n\n\tsOptions, pOptions, kOptions, oOptions := render.SetDefaultScaleOptions()\n\n\tpv := render.PageVars{\n\t\tTitle: \"Practice Scales and Arpeggios\", // default scale initially displayed is A Major\n\t\tScalearp: \"Scale\",\n\t\tPitch: \"Major\",\n\t\tKey: \"A\",\n\t\tScaleImgPath: \"img/scale/major/a1.png\",\n\t\tGifPath: \"\",\n\t\tAudioPath: \"mp3/scale/major/a1.mp3\",\n\t\tAudioPath2: \"mp3/drone/a1.mp3\",\n\t\tLeftLabel: \"Listen to Major scale\",\n\t\tRightLabel: \"Listen to Drone\",\n\t\tScaleOptions: sOptions,\n\t\tPitchOptions: pOptions,\n\t\tKeyOptions: kOptions,\n\t\tOctaveOptions: oOptions,\n\t}\n\n\tif err := render.Render(w, \"scale.html\", pv); err != nil {\n\t\tb.log.Printf(\"%s %s -> %s : ERROR : %v\", r.Method, r.URL.Path, r.RemoteAddr, err)\n\t\treturn\n\t}\n}", "func (jpegOptim JpegOptim) Alter(r resource.Resource) (resource.Resource, error) {\n\t// create temporary file\n\tf, err := helpers.TempFile(\"\", \"statix_filter_\", \".jpg\")\n\tif err != nil {\n\t\treturn &resource.Empty{}, err\n\t}\n\tdefer func() {\n\t\tf.Close()\n\t\tos.Remove(f.Name())\n\t}()\n\n\tc, err := r.Dump()\n\tif err != nil {\n\t\treturn &resource.Empty{}, err\n\t}\n\n\t_, err = f.Write(c)\n\tif err != nil {\n\t\treturn &resource.Empty{}, err\n\t}\n\n\t// execute command\n\tvar command *exec.Cmd\n\tbufOut := bytes.NewBuffer(nil)\n\tbufErr := bytes.NewBuffer(nil)\n\tif jpegOptim.StripAll {\n\t\tcommand = exec.Command(jpegOptim.Bin, \"-m\", strconv.Itoa(jpegOptim.Max), f.Name())\n\t} else {\n\t\tcommand = exec.Command(jpegOptim.Bin, \"--strip-all\", \"-m\", strconv.Itoa(jpegOptim.Max), f.Name())\n\t}\n\tcommand.Stdout = bufOut\n\tcommand.Stderr = bufErr\n\terr = command.Run()\n\tif err != nil {\n\t\treturn &resource.Empty{}, fmt.Errorf(\"command error:\\n%s\", bufErr.String())\n\t}\n\n\t// read result\n\tc, err = ioutil.ReadFile(f.Name())\n\tif err != nil {\n\t\treturn &resource.Empty{}, err\n\t}\n\treturn resource.NewBytes(c), nil\n}", "func (p *point) scaleBy(factor int) {\n\tp.x *= factor\n\tp.y *= factor\n}", "func (s Size) ScaleDown(x, y int) Size {\n\ts.W /= x\n\ts.H /= y\n\treturn s\n}", "func (s *Surface) Scale(x, y float64) {\n\ts.Ctx.Call(\"scale\", x, y)\n}" ]
[ "0.58466375", "0.56978995", "0.5452225", "0.5412777", "0.5351255", "0.5282156", "0.525926", "0.5074614", "0.5073612", "0.5039112", "0.49935594", "0.49753124", "0.4956702", "0.49479872", "0.49000466", "0.48680896", "0.4862106", "0.48588043", "0.48502174", "0.47648355", "0.47453874", "0.47449163", "0.47410032", "0.46956298", "0.46955773", "0.4680614", "0.4676583", "0.46759355", "0.46733093", "0.4669077", "0.4667152", "0.46196994", "0.460891", "0.46005812", "0.4593618", "0.45930335", "0.4576779", "0.45747095", "0.4553176", "0.4552463", "0.45478868", "0.45421106", "0.45241237", "0.45102465", "0.45053828", "0.44941002", "0.44700494", "0.44587913", "0.4452592", "0.44459", "0.44440728", "0.44379276", "0.44317016", "0.4429311", "0.4418629", "0.44143015", "0.4402081", "0.4394216", "0.43723145", "0.43712735", "0.4356998", "0.43478987", "0.43404394", "0.43392995", "0.43392736", "0.4338674", "0.43237525", "0.43210784", "0.43199742", "0.43188372", "0.4301115", "0.42965746", "0.428827", "0.42881298", "0.4284843", "0.42847788", "0.4281479", "0.42807266", "0.42655414", "0.42516312", "0.42320845", "0.42315677", "0.42168", "0.4206286", "0.4204948", "0.4202096", "0.4199741", "0.41925576", "0.41912898", "0.41910687", "0.41896987", "0.4189404", "0.4187501", "0.41873392", "0.41840354", "0.41839892", "0.41826388", "0.41795236", "0.41774902", "0.41722748" ]
0.7831992
0
ColorModel implements image.Image interface.
func (p *Magnifier) ColorModel() color.Model { return p.Image.ColorModel() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *Image) ColorModel() color.Model {\n\treturn color.RGBA64Model\n}", "func (image *Image) ColorModel() color.Model {\n\treturn image.colorModel\n}", "func (c *Image) ColorModel() color.Model {\n\treturn color.GrayModel\n}", "func (w *worldImg) ColorModel() color.Model {\n\treturn color.RGBAModel\n}", "func (f *YFastBilateral) ColorModel() color.Model {\n\treturn f.HDRImage.ColorModel()\n}", "func (m *Map) ColorModel() image.ColorModel {\n\treturn image.NRGBAColorModel\n}", "func (p *RGBAf) ColorModel() color.Model { return color.RGBAModel }", "func (m *Model) Image() image.Image {\n\tm.Lock()\n\tdefer m.Unlock()\n\n\timg := image.NewRGBA(image.Rect(0, 0, m.n, m.n))\n\tfor i := 0; i < m.n; i++ {\n\t\tfor j := 0; j < m.n; j++ {\n\t\t\tif m.l[i][j] > 0 {\n\t\t\t\timg.Set(i, j, color.RGBA{68, 68, 68, 255})\n\t\t\t} else {\n\t\t\t\timg.Set(i, j, color.RGBA{255, 255, 249, 255})\n\t\t\t}\n\t\t}\n\t}\n\treturn img\n}", "func (m *CvMat) ColorModel() color.Model {\n\treturn color.GrayModel\n}", "func (e *Emulator) ColorModel() color.Model { return color.RGBAModel }", "func (r Rectangle) ColorModel() color.Model {\n\treturn color.Alpha16Model\n}", "func (d *Dev) ColorModel() color.Model {\n\treturn color.ModelFunc(func(c color.Color) color.Color {\n\t\tr, g, b, _ := c.RGBA()\n\t\tif r == 0 && g == 0 && b == 0 {\n\t\t\treturn color.RGBA{\n\t\t\t\tR: 0,\n\t\t\t\tG: 0,\n\t\t\t\tB: 0,\n\t\t\t\tA: 255,\n\t\t\t}\n\t\t} else if r == 0xffff && g == 0xffff && b == 0xffff {\n\t\t\treturn color.RGBA{\n\t\t\t\tR: 255,\n\t\t\t\tG: 255,\n\t\t\t\tB: 255,\n\t\t\t\tA: 255,\n\t\t\t}\n\t\t}\n\t\treturn color.RGBA{\n\t\t\tR: 255,\n\t\t\tG: 0,\n\t\t\tB: 0,\n\t\t\tA: 255,\n\t\t}\n\t})\n}", "func (device *Dev) ColorModel() color.Model {\n\treturn color.NRGBAModel\n}", "func (s *Color) Image() image.Image {\n\tif s.image == nil {\n\t\ts.image = image.NewRGBA(image.Rect(0, 0, 1, 1))\n\t\ts.image.Set(0, 0, s.Color)\n\t}\n\treturn s.image\n}", "func AverageImageColor(i image.Image) LCH {\n\tvar r, g, b uint32\n\n\tbounds := i.Bounds()\n\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tpr, pg, pb, _ := i.At(x, y).RGBA()\n\n\t\t\tr += pr\n\t\t\tg += pg\n\t\t\tb += pb\n\t\t}\n\t}\n\n\td := uint32(bounds.Dy() * bounds.Dx())\n\n\tr /= d\n\tg /= d\n\tb /= d\n\n\tc := color.NRGBA{uint8(r / 0x101), uint8(g / 0x101), uint8(b / 0x101), 255}\n\n\treturn LCHModel.Convert(c).(LCH)\n}", "func getColorMappedImage(img image.Image) ColorMappedImage {\n\tbounds := img.Bounds()\n\n\t// Drawing image onto a white surface to remove transparency\n\topaqueImg := image.NewRGBA(bounds)\n\tdraw.Draw(opaqueImg, bounds, image.White, image.Point{}, draw.Src)\n\tdraw.Draw(opaqueImg, bounds, img, image.Point{}, draw.Over)\n\n\t// Reduce palette to number of possible colors in GitHub graph\n\tquantizedImg := image.NewGray(bounds)\n\tnumColors := len(GithubPalette)\n\tcolorquant.NoDither.Quantize(opaqueImg, quantizedImg, numColors, true, true)\n\n\t// Create map of all unique grays in the quantized image\n\t// Mapped from gray.Y to GithubPalette index (populated later)\n\tcolorMap := map[int]int{}\n\tfor y := 0; y < bounds.Max.Y; y++ {\n\t\tfor x := 0; x < bounds.Max.X; x++ {\n\t\t\tgray := quantizedImg.GrayAt(x, y)\n\t\t\tcolorMap[int(gray.Y)] = 0\n\t\t}\n\t}\n\n\t// Create slice with grays sorted asc, darkest first\n\tcolorsInMap := []int{}\n\tfor k := range colorMap {\n\t\tcolorsInMap = append(colorsInMap, k)\n\t}\n\tsort.Ints(colorsInMap)\n\n\t// Populate color map values with order of grays\n\tfor index, k := range colorsInMap {\n\t\tcolorMap[k] = len(colorsInMap) - 1 - index\n\t}\n\n\treturn ColorMappedImage{\n\t\timage: quantizedImg,\n\t\tcolorMap: colorMap,\n\t}\n}", "func Image(m *image.RGBA, key string, colors []color.RGBA) {\n\tsize := m.Bounds().Size()\n\tsquares := 6\n\tquad := size.X / squares\n\tmiddle := math.Ceil(float64(squares) / float64(2))\n\tcolorMap := make(map[int]color.RGBA)\n\tvar currentYQuadrand = 0\n\tfor y := 0; y < size.Y; y++ {\n\t\tyQuadrant := y / quad\n\t\tif yQuadrant != currentYQuadrand {\n\t\t\t// when y quadrant changes, clear map\n\t\t\tcolorMap = make(map[int]color.RGBA)\n\t\t\tcurrentYQuadrand = yQuadrant\n\t\t}\n\t\tfor x := 0; x < size.X; x++ {\n\t\t\txQuadrant := x / quad\n\t\t\tif _, ok := colorMap[xQuadrant]; !ok {\n\t\t\t\tif float64(xQuadrant) < middle {\n\t\t\t\t\tcolorMap[xQuadrant] = draw.PickColor(key, colors, xQuadrant+3*yQuadrant)\n\t\t\t\t} else if xQuadrant < squares {\n\t\t\t\t\tcolorMap[xQuadrant] = colorMap[squares-xQuadrant-1]\n\t\t\t\t} else {\n\t\t\t\t\tcolorMap[xQuadrant] = colorMap[0]\n\t\t\t\t}\n\t\t\t}\n\t\t\tm.Set(x, y, colorMap[xQuadrant])\n\t\t}\n\t}\n}", "func GSLuma(img Image) {\n\t// Color.\n\tfor x := 0; x < img.Height; x++ {\n\t\tfor y := 0; y < img.Width; y++ {\n\t\t\tbrightness := int((float64(img.Pixels[x][y].R)*0.2126 +\n\t\t\t\tfloat64(img.Pixels[x][y].G)*0.7152 +\n\t\t\t\tfloat64(img.Pixels[x][y].B)*0.0722) / 3.0)\n\t\t\timg.Pixels[x][y].R = brightness\n\t\t\timg.Pixels[x][y].G = brightness\n\t\t\timg.Pixels[x][y].B = brightness\n\t\t}\n\t}\n}", "func (d UserData) Color() int64 {\n\tval := d.ModelData.Get(models.NewFieldName(\"Color\", \"color\"))\n\tif !d.Has(models.NewFieldName(\"Color\", \"color\")) {\n\t\treturn *new(int64)\n\t}\n\treturn val.(int64)\n}", "func averageColor(src image.Image) color.Color {\n\tb := src.Bounds()\n\tvar sum struct{ c, y, m, k float64 }\n\tn := 0\n\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\tfor x := b.Min.X; x < b.Max.X; x++ {\n\t\t\tc := color.CMYKModel.Convert(src.At(x, y)).(color.CMYK)\n\t\t\tsum.c += float64(c.C)\n\t\t\tsum.m += float64(c.M)\n\t\t\tsum.y += float64(c.Y)\n\t\t\tsum.k += float64(c.K)\n\t\t\tn++\n\t\t}\n\t}\n\td := float64(n)\n\treturn color.CMYK{\n\t\tC: uint8(sum.c / d),\n\t\tM: uint8(sum.m / d),\n\t\tY: uint8(sum.y / d),\n\t\tK: uint8(sum.k / d),\n\t}\n}", "func Color(c color.Color) termbox.Attribute {\n\tswitch termbox.SetOutputMode(termbox.OutputCurrent) {\n\tcase termbox.OutputNormal:\n\t\treturn ColorNormal(c)\n\tcase termbox.Output256:\n\t\treturn Color256(c)\n\tcase termbox.Output216:\n\t\treturn Color216(c)\n\tcase termbox.OutputGrayscale:\n\t\treturn ColorGray(c)\n\tdefault:\n\t\tpanic(\"unexpected output mode\")\n\t}\n}", "func GSSingleColor(img Image, color int) (err error) {\n\t// Check color-parameter.\n\tif (color != RED) && (color != GREEN) && (color != BLUE) {\n\t\terr = errors.New(\"Unknown color-parameter\")\n\t\treturn\n\t}\n\t// Color.\n\tfor x := 0; x < img.Height; x++ {\n\t\tfor y := 0; y < img.Width; y++ {\n\t\t\tbrightness := 0\n\t\t\tif color == RED {\n\t\t\t\tbrightness = img.Pixels[x][y].R\n\t\t\t} else if color == GREEN {\n\t\t\t\tbrightness = img.Pixels[x][y].G\n\t\t\t} else if color == BLUE {\n\t\t\t\tbrightness = img.Pixels[x][y].B\n\t\t\t}\n\t\t\timg.Pixels[x][y].R = brightness\n\t\t\timg.Pixels[x][y].G = brightness\n\t\t\timg.Pixels[x][y].B = brightness\n\t\t}\n\t}\n\treturn\n}", "func (m RGBImage) AsImage() image.Image {\n\trgb := image.NewRGBA(image.Rect(0, 0, m.Width, m.Height))\n\tidx := 0\n\tfor y := 0; y < m.Height; y++ {\n\t\tp := y * rgb.Stride\n\t\tfor x := 0; x < m.Width; x++ {\n\t\t\trgb.Pix[p], rgb.Pix[p+1], rgb.Pix[p+2], rgb.Pix[p+3] = m.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2], 255\n\t\t\tidx++\n\t\t\tp += 4\n\t\t}\n\t}\n\treturn rgb\n}", "func Color(foreColor, backColor, mode gb.UINT8) {}", "func (color *Color) readModel(r io.Reader) (err error) {\n\t// make array for our color model, where four is the max possible\n\t// amount of characters (RGB, LAB, CMYK, Gray).\n\tcolorModel := make([]uint8, 4)\n\tif err = binary.Read(r, binary.BigEndian, colorModel); err != nil {\n\t\treturn\n\t}\n\n\t// Assign the string version of the `colorModel`\n\tcolor.Model = strings.TrimSpace(string(colorModel[0:]))\n\n\treturn\n}", "func (cc Counter) Image(img image.Image) {\n\teachPixel(img, func(x int, y int, c color.Color) {\n\t\trgb := NewRGB(c)\n\t\tcc.Inc(rgb)\n\t})\n}", "func (a *ImageApiService) ImageDetectColor(ctx _context.Context, imageDetectColorParameters ImageDetectColorParameters) (ImageDetectColorResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImageDetectColorResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageDetectColor\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageDetectColorParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ImageDetectColorResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (image *JPGImage) GetColorComponents() uint8 {\n\treturn image.colorComponents\n}", "func Color(value color.Color) *SimpleElement { return newSEColor(\"color\", value) }", "func (display smallEpd) convertImage(image image.Image) (black []byte, red []byte) {\n\t// Resize image to width and height\n\t// Each pixel in image is turned into a bit\n\t// which says 1 or 0\n\t// Create two buffers of (w*h)/8 bytes\n\t// TODO: Allow for other colors. Switch to HSL mode and\n\t// calculate by hue\n\tw := display.Width()\n\th := display.Height()\n\ts := (w * h) / 8\n\tblackBuf := make([]byte, s)\n\tredBuf := make([]byte, s)\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tpixelIdx := ((y * w) + x)\n\t\t\tbyteIdx := pixelIdx / 8\n\t\t\tbitIdx := uint(7 - pixelIdx%8)\n\t\t\tpix := image.At(x, y)\n\t\t\trgba := color.RGBAModel.Convert(pix).(color.RGBA)\n\t\t\tgray := color.GrayModel.Convert(pix).(color.Gray)\n\t\t\t// Flip all bits and mask with 0xFF. Divide by 0xFF to get 1 as last bit for black, 0 for anything else. Then XOR it.\n\t\t\t// black := (((^rgba.R ^ rgba.B ^ rgba.G) & 0xFF) / 0xFF) ^ 0x01 // Black is 1 (white) if not absolute black\n\t\t\t// red := ((rgba.R &^ rgba.B &^ rgba.G) / 0xFF) ^ 0x01 // Red is 1 if only full saturation red. Otherwise 0\n\t\t\tblack := byte(0x00)\n\t\t\tif gray.Y > 180 {\n\t\t\t\tblack = 0x01\n\t\t\t}\n\t\t\tred := byte(0x01)\n\t\t\tif rgba.B < 180 && rgba.G < 180 && rgba.R > 180 {\n\t\t\t\tred = 0x00\n\t\t\t}\n\t\t\tblackBuf[byteIdx] |= black << bitIdx\n\t\t\tredBuf[byteIdx] |= red << bitIdx\n\t\t}\n\t}\n\t// Dither and do another loop for black?\n\treturn blackBuf, redBuf\n}", "func Colorize(hue, saturation, percentage float32) Filter {\n\th := normalizeHue(hue / 360)\n\ts := minf32(maxf32(saturation, 0), 100) / 100\n\tp := minf32(maxf32(percentage, 0), 100) / 100\n\tif p == 0 {\n\t\treturn &copyimageFilter{}\n\t}\n\n\treturn &colorFilter{\n\t\tfn: func(px pixel) pixel {\n\t\t\t_, _, l := convertRGBToHSL(px.R, px.G, px.B)\n\t\t\tr, g, b := convertHSLToRGB(h, s, l)\n\t\t\tpx.R += (r - px.R) * p\n\t\t\tpx.G += (g - px.G) * p\n\t\t\tpx.B += (b - px.B) * p\n\t\t\treturn px\n\t\t},\n\t}\n}", "func LineariseImage(img draw.Image) {\n\tbounds := img.Bounds()\n\n\tswitch inputImg := img.(type) {\n\n\tcase *image.RGBA64:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\tinputImg.SetRGBA64(j, i, LineariseColor(inputImg.RGBA64At(j, i)))\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\timg.Set(j, i, LineariseColor(img.At(j, i)))\n\t\t\t}\n\t\t}\n\t}\n}", "func (m *RGBImage) SetImage(img image.Image) {\n\tbounds := img.Bounds()\n\tw, h := bounds.Dx(), bounds.Dy()\n\tm.Resize(Size{w, h})\n\n\tswitch img := img.(type) {\n\tcase *image.Gray:\n\t\tidx := 0\n\t\tfor y := 0; y < h; y++ {\n\t\t\ts := y * img.Stride\n\t\t\tfor x := 0; x < w; x++ {\n\t\t\t\tc := img.Pix[s]\n\t\t\t\tm.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2] = c, c, c\n\t\t\t\tidx++\n\t\t\t\ts++\n\t\t\t}\n\t\t}\n\n\tcase *image.NRGBA:\n\t\tidx := 0\n\t\tfor y := 0; y < h; y++ {\n\t\t\ts := y * img.Stride\n\t\t\tfor x := 0; x < w; x++ {\n\t\t\t\tr, g, b, a := img.Pix[s], img.Pix[s+1], img.Pix[s+2], img.Pix[s+3]\n\t\t\t\tswitch a {\n\t\t\t\tcase 0:\n\t\t\t\t\tm.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2] = 0, 0, 0\n\t\t\t\tcase 0xff:\n\t\t\t\t\tm.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2] = r, g, b\n\t\t\t\tdefault:\n\t\t\t\t\tm.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2] =\n\t\t\t\t\t\tbyte(uint32(r)*uint32(a)/255), byte(uint32(g)*uint32(a)/255), byte(uint32(b)*uint32(a)/255)\n\t\t\t\t}\n\t\t\t\tidx++\n\t\t\t\ts += 4\n\t\t\t}\n\t\t}\n\n\tcase *image.Paletted:\n\t\tpal := make([]RGB, len(img.Palette))\n\t\tfor i, c := range img.Palette {\n\t\t\tr, g, b, _ := c.RGBA()\n\t\t\tpal[i][0], pal[i][1], pal[i][2] = byte(r>>8), byte(g>>8), byte(b>>8)\n\t\t}\n\t\tidx := 0\n\t\tfor y := 0; y < h; y++ {\n\t\t\ts := y * img.Stride\n\t\t\tfor x := 0; x < w; x++ {\n\t\t\t\tm.Pixels[idx] = pal[img.Pix[s]]\n\t\t\t\tidx++\n\t\t\t\ts++\n\t\t\t}\n\t\t}\n\t\t/*\n\t\t\tcase *image.YCbCr:\n\t\t\t\tif img.YStride == w {\n\t\t\t\t\tcopy(m.Pixels, img.Y)\n\t\t\t\t} else {\n\t\t\t\t\tfor y := 0; y < h; y++ {\n\t\t\t\t\t\tcopy(m.Pixels[y*w:], img.Y[y*img.YStride:y*img.YStride+w])\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t*/\n\tdefault:\n\t\tidx := 0\n\t\tfor y := 0; y < h; y++ {\n\t\t\tfor x := 0; x < w; x++ {\n\t\t\t\tc := img.At(x, y)\n\t\t\t\tr, g, b, _ := c.RGBA()\n\t\t\t\tm.Pixels[idx][0], m.Pixels[idx][1], m.Pixels[idx][2] = byte(r>>8), byte(g>>8), byte(b>>8)\n\t\t\t\tidx++\n\t\t\t}\n\t\t}\n\t}\n}", "func ConvertColor(pixelColor *Vec3, samplesPerPixel int) {\n\tscale := 1.0 / float64(samplesPerPixel)\n\tpixelColor.X = Clamp(math.Sqrt(pixelColor.X*scale), 0, 1)\n\tpixelColor.Y = Clamp(math.Sqrt(pixelColor.Y*scale), 0, 1)\n\tpixelColor.Z = Clamp(math.Sqrt(pixelColor.Z*scale), 0, 1)\n}", "func MakeColor(width, height int) Texture {\n\treturn Make(width, height, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, nil,\n\t\tgl.LINEAR, gl.LINEAR, gl.CLAMP_TO_BORDER, gl.CLAMP_TO_BORDER)\n}", "func (dw *DrawingWand) Color(x, y float64, pm PaintMethod) {\n\tC.MagickDrawColor(dw.dw, C.double(x), C.double(y), C.PaintMethod(pm))\n}", "func (img *IplImage) ToImage() image.Image {\n\tvar height, width, channels, step int = img.Height(), img.Width(), img.Channels(), img.WidthStep()\n\tout := image.NewNRGBA(image.Rect(0, 0, width, height))\n\tif img.Depth() != IPL_DEPTH_8U {\n\t\treturn nil // TODO return error\n\t}\n\t// Turn opencv.Iplimage.imageData(*char) to slice\n\tvar limg *C.char = img.imageData\n\tvar limg_ptr unsafe.Pointer = unsafe.Pointer(limg)\n\tvar data []C.char = (*[1 << 30]C.char)(limg_ptr)[:height*step : height*step]\n\n\tc := color.NRGBA{R: uint8(0), G: uint8(0), B: uint8(0), A: uint8(255)}\n\t// Iteratively assign imageData's color to Go's image\n\tfor y := 0; y < height; y++ {\n\t\tfor x := 0; x < step; x = x + 3 {\n\t\t\tc.B = uint8(data[y*step+x])\n\t\t\tc.G = uint8(data[y*step+x+1])\n\t\t\tc.R = uint8(data[y*step+x+2])\n\t\t\tif channels == 4 {\n\t\t\t\tc.A = uint8(data[y*step+x+3])\n\t\t\t}\n\t\t\tout.SetNRGBA(int(x/3), y, c)\n\t\t}\n\t}\n\n\treturn out\n}", "func (c *Canvas) Color(at pixel.Vec) pixel.RGBA {\n\treturn c.gf.Color(at)\n}", "func (r *RGBARotator) Image() image.Image {\n\treturn r.Img\n}", "func (fb FrameBuffer) ColorAt(x int, y int) color.Color {\n\tc := fb.img.At(x, y)\n\treturn c\n}", "func (s UserSet) Color() int64 {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"Color\", \"color\")).(int64)\n\treturn res\n}", "func AverageImageColor(i image.Image) color.Color {\n\tvar r, g, b uint32\n\n\tbounds := i.Bounds()\n\n\tfor y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n\t\tfor x := bounds.Min.X; x < bounds.Max.X; x++ {\n\t\t\tpr, pg, pb, _ := i.At(x, y).RGBA()\n\t\t\tr += pr\n\t\t\tg += pg\n\t\t\tb += pb\n\t\t}\n\t}\n\n\td := uint32(bounds.Dy() * bounds.Dx() * 0x101)\n\n\tr /= d\n\tg /= d\n\tb /= d\n\n\treturn color.NRGBA{uint8(r), uint8(g), uint8(b), 255}\n}", "func (color *Color) writeModel(w io.Writer) (err error) {\n\tmodel := make([]uint8, 4)\n\n\t// Populate model with the uint8 version of the each character in the string.\n\tfor i, _ := range model {\n\t\tcolorModel := color.Model\n\n\t\t// Our iterator over model needs to match the number of elements in color.Model.\n\t\t// If color.Model has a length less than four, append an empty space.\n\t\tif len(color.Model) < 4 {\n\t\t\tfor len(colorModel) < 4 {\n\t\t\t\tcolorModel += \" \"\n\t\t\t}\n\t\t}\n\t\tmodel[i] = uint8([]rune(colorModel)[i])\n\t}\n\n\treturn binary.Write(w, binary.BigEndian, model)\n}", "func (s *Solver) PlotToImage(rgba *image.RGBA, plotType int) {\n\n\tvar cIndex = 0\n\tvar contrast = float32(1.2)\n\tif plotType == 4 {\n\t\ts.ComputeCurl()\n\t}\n\n\tfor y := 0; y < s.ydim; y++ {\n\t\tfor x := 0; x < s.xdim; x++ {\n\t\t\tif s.barrier[x+y*s.xdim] {\n\t\t\t\tcIndex = s.nColors + 1 // kludge for barrier color which isn't really part of color map\n\t\t\t} else {\n\t\t\t\tif plotType == 0 {\n\t\t\t\t\tcIndex = int(float32(s.nColors) * ((s.rho[x+y*s.xdim]-float32(1))*float32(6)*float32(contrast) + float32(0.5)))\n\t\t\t\t} else if plotType == 1 {\n\t\t\t\t\tcIndex = int(float32(s.nColors) * ((s.ux[x+y*s.xdim] * float32(2.0) * contrast) + float32(0.5)))\n\t\t\t\t} else if plotType == 2 {\n\t\t\t\t\tcIndex = int(float32(s.nColors) * ((s.uy[x+y*s.xdim] * float32(2.0) * contrast) + float32(0.5)))\n\t\t\t\t} else if plotType == 3 {\n\t\t\t\t\tspeed := float32(math.Sqrt(float64(s.ux[x+y*s.xdim]*s.ux[x+y*s.xdim] + s.uy[x+y*s.xdim]*s.uy[x+y*s.xdim])))\n\t\t\t\t\tcIndex = int(float32(s.nColors) * (speed * float32(4) * float32(contrast)))\n\t\t\t\t} else {\n\t\t\t\t\tcIndex = int(float32(s.nColors) * (s.curl[x+y*s.xdim]*float32(5)*float32(contrast) + float32(0.5)))\n\t\t\t\t}\n\n\t\t\t\tif cIndex < 0 {\n\t\t\t\t\tcIndex = 0\n\t\t\t\t}\n\t\t\t\tif cIndex > s.nColors {\n\t\t\t\t\tcIndex = s.nColors\n\t\t\t\t}\n\t\t\t}\n\t\t\trgba.SetRGBA(x, y,\n\t\t\t\timage_color.RGBA{uint8(s.redList[cIndex]), uint8(s.greenList[cIndex]), uint8(s.blueList[cIndex]), 255})\n\t\t}\n\t}\n}", "func (p PalettedColorModel) Convert(c Color) Color {\n\tif len(p) == 0 {\n\t\treturn nil\n\t}\n\t// TODO(nigeltao): Revisit the \"pick the palette color which minimizes sum-squared-difference\"\n\t// algorithm when the premultiplied vs unpremultiplied issue is resolved.\n\t// Currently, we only compare the R, G and B values, and ignore A.\n\tcr, cg, cb, _ := c.RGBA();\n\t// Shift by 17 bits to avoid potential uint32 overflow in sum-squared-difference.\n\tcr >>= 17;\n\tcg >>= 17;\n\tcb >>= 17;\n\tresult := Color(nil);\n\tbestSSD := uint32(1<<32 - 1);\n\tfor _, v := range p {\n\t\tvr, vg, vb, _ := v.RGBA();\n\t\tvr >>= 17;\n\t\tvg >>= 17;\n\t\tvb >>= 17;\n\t\tdr, dg, db := diff(cr, vr), diff(cg, vg), diff(cb, vb);\n\t\tssd := (dr * dr) + (dg * dg) + (db * db);\n\t\tif ssd < bestSSD {\n\t\t\tbestSSD = ssd;\n\t\t\tresult = v;\n\t\t}\n\t}\n\treturn result;\n}", "func FromImage(img image.Image) *IplImage {\n\tb := img.Bounds()\n\tmodel := color.RGBAModel\n\tdst := CreateImage(\n\t\tb.Max.X-b.Min.X,\n\t\tb.Max.Y-b.Min.Y,\n\t\tIPL_DEPTH_8U, 4)\n\n\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\tfor x := b.Min.X; x < b.Max.X; x++ {\n\t\t\tpx := img.At(x, y)\n\t\t\tc := model.Convert(px).(color.RGBA)\n\n\t\t\tvalue := NewScalar(float64(c.B), float64(c.G), float64(c.R), float64(c.A))\n\t\t\tdst.Set2D(x-b.Min.X, y-b.Min.Y, value)\n\t\t}\n\t}\n\n\treturn dst\n}", "func (p *Palette) Image() *image.RGBA {\n\tw := 256\n\th := 10\n\tm := image.NewRGBA(image.Rect(0, 0, w, h))\n\n\tfor x := 0; x < w; x++ {\n\t\tfor y := 0; y < h; y++ {\n\t\t\tm.Set(x, y, p[x])\n\t\t}\n\t}\n\n\treturn m\n}", "func (this *osmSourceStruct) transformColor(in color.NRGBA, scale float64) color.NRGBA {\n\tr := in.R\n\tg := in.G\n\tb := in.B\n\trFloat := float64(r) / 255.0\n\tgFloat := float64(g) / 255.0\n\tbFloat := float64(b) / 255.0\n\trInvFloat := 1.0 - rFloat\n\tgInvFloat := 1.0 - gFloat\n\tbInvFloat := 1.0 - bFloat\n\tlumaFloat := (0.22 * rInvFloat) + (0.72 * gInvFloat) + (0.06 * bInvFloat)\n\tlumaFloatScaled := scale * lumaFloat\n\tlumaFloatByte := math.Round(lumaFloatScaled * 255.0)\n\tlumaByte := uint8(lumaFloatByte)\n\n\t/*\n\t * Create resulting color value.\n\t */\n\tc := color.NRGBA{\n\t\tR: lumaByte,\n\t\tG: lumaByte,\n\t\tB: lumaByte,\n\t\tA: 255,\n\t}\n\n\treturn c\n}", "func (r *ImageRef) ColorSpace() Interpretation {\n\treturn r.Interpretation()\n}", "func New(color string) *ml.Color {\n\tcolor = Normalize(color)\n\n\t//check if it's indexed color\n\tfor i, c := range indexed {\n\t\tif color == c {\n\t\t\treturn &ml.Color{Indexed: &i}\n\t\t}\n\t}\n\n\treturn &ml.Color{RGB: color}\n}", "func (f *Frame) Image() image.Image {\n\tvar ssr image.YCbCrSubsampleRatio\n\tswitch f.Chroma {\n\tcase \"444\", \"444alpha\":\n\t\tssr = image.YCbCrSubsampleRatio444\n\tcase \"422\":\n\t\tssr = image.YCbCrSubsampleRatio422\n\tcase \"420jpeg\", \"420mpeg2\", \"420paldv\":\n\t\tssr = image.YCbCrSubsampleRatio420\n\tcase \"411\":\n\t\tssr = image.YCbCrSubsampleRatio411\n\tcase \"mono\":\n\t\tlog.Fatal(\"Mono images should be handled by another function\")\n\t}\n\tr := image.Rect(0, 0, f.Width, f.Height)\n\tif len(f.Alpha) > 0 {\n\t\timg := image.NewNYCbCrA(r, ssr)\n\t\timg.YCbCr.Y = f.Y\n\t\timg.YCbCr.Cb = f.Cb\n\t\timg.YCbCr.Cr = f.Cr\n\t\timg.A = f.Alpha\n\t\treturn img\n\t} else if f.Chroma == \"mono\" {\n\t\timg := image.NewGray(r)\n\t\timg.Pix = f.Y\n\t\treturn img\n\t} else {\n\t\timg := image.NewYCbCr(r, ssr)\n\t\timg.Y = f.Y\n\t\timg.Cb = f.Cb\n\t\timg.Cr = f.Cr\n\t\treturn img\n\t}\n}", "func (s Sphere) Color() Material {\n\treturn s.Mat\n}", "func (cg *colorChartController) GenerateColorPatchImage(data []models.ColorCode, filesavepath, dirname string, width, height int) bool {\n\n\t// initialize image controller\n\timgcontroller := NewImageController()\n\n\t// initialize directory handler\n\tdirhandler := util.NewDirectoryHandler()\n\tdirhandler.MakeDirectory(filesavepath, dirname)\n\n\t// create path string for file save\n\tpath := filesavepath + dirname + \"/\"\n\n\t// initalize IO handler\n\tiohandler := util.NewIOUtil()\n\n\t// generate color patches\n\tfor _, rawdata := range data {\n\t\trawimage := imgcontroller.CreateSolidImage(*rawdata.GenerateColorRGBA(), height, width)\n\t\tif !iohandler.StreamOutPNGFile(path, rawdata.GetName(), rawimage) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// return\n\treturn true\n}", "func (m Model) GetImage() image.Image {\n\treturn m.Image\n}", "func colorPointsForModel(model string) (points []XY) {\n\tpoints = make([]XY, 3)\n\tswitch model {\n\tcase \"LCT001\", \"LCT002\", \"LCT003\":\n\t\tpoints[colorPointRed].X = 0.674\n\t\tpoints[colorPointRed].Y = 0.322\n\t\tpoints[colorPointGreen].X = 0.408\n\t\tpoints[colorPointGreen].Y = 0.517\n\t\tpoints[colorPointBlue].X = 0.168\n\t\tpoints[colorPointBlue].Y = 0.041\n\t\treturn\n\n\tcase \"LLC001\", \"LLC005\", \"LLC006\", \"LLC007\", \"LLC011\", \"LLC012\", \"LLC013\", \"LST001\":\n\t\tpoints[colorPointRed].X = 0.703\n\t\tpoints[colorPointRed].Y = 0.296\n\t\tpoints[colorPointGreen].X = 0.214\n\t\tpoints[colorPointGreen].Y = 0.709\n\t\tpoints[colorPointBlue].X = 0.139\n\t\tpoints[colorPointBlue].Y = 0.081\n\t\treturn\n\t}\n\n\tpoints[colorPointRed].X = 1.0\n\tpoints[colorPointRed].Y = 0.0\n\tpoints[colorPointGreen].X = 0.0\n\tpoints[colorPointGreen].Y = 1.0\n\tpoints[colorPointBlue].X = 0.0\n\tpoints[colorPointBlue].Y = 0.0\n\treturn\n}", "func linearImage(srcim image.Image, gamma float64) *image.NRGBA64 {\n\tdstim := image.NewNRGBA64(image.Rectangle{\n\t\tMax: image.Point{\n\t\t\tX: srcim.Bounds().Dx(),\n\t\t\tY: srcim.Bounds().Dy(),\n\t\t},\n\t})\n\tvar dsty int\n\tfor srcy := srcim.Bounds().Min.Y; srcy < srcim.Bounds().Max.Y; srcy++ {\n\t\tvar dstx int\n\t\tfor srcx := srcim.Bounds().Min.X; srcx < srcim.Bounds().Max.X; srcx++ {\n\t\t\tnrgba64 := color.NRGBA64Model.Convert(srcim.At(srcx, srcy)).(color.NRGBA64)\n\t\t\tnrgba64.R = uint16(nrgba64Max * math.Pow(float64(nrgba64.R)/nrgba64Max, gamma))\n\t\t\tnrgba64.G = uint16(nrgba64Max * math.Pow(float64(nrgba64.G)/nrgba64Max, gamma))\n\t\t\tnrgba64.B = uint16(nrgba64Max * math.Pow(float64(nrgba64.B)/nrgba64Max, gamma))\n\t\t\t// Alpha is not affected\n\t\t\tdstim.SetNRGBA64(dstx, dsty, nrgba64)\n\t\t\tdstx++\n\t\t}\n\t\tdsty++\n\t}\n\treturn dstim\n}", "func ColorRGB24(r, g, b int) Attribute {\n\treturn ColorRGB(r/51, g/51, b/51)\n}", "func NewRGB(c color.Color) RGB {\n\tc = color.RGBAModel.Convert(c)\n\trgba, ok := c.(color.RGBA)\n\tif !ok {\n\t\t// This type assertion should always succeed\n\t\t// based on https://godoc.org/image/color#Model\n\t\t// If we see this panic triggered in practice we might need to revisit.\n\t\tpanic(\"color conversion failure\")\n\t}\n\treturn RGB{\n\t\tR: rgba.R,\n\t\tG: rgba.G,\n\t\tB: rgba.B,\n\t}\n}", "func colorDestinationImage(\n\tdestinationImage *image.NRGBA,\n\tsourceImage image.Image,\n\tdestinationCoordinates []complex128,\n\ttransformedCoordinates []complex128,\n\tcolorValueBoundMin complex128,\n\tcolorValueBoundMax complex128,\n) {\n\tsourceImageBounds := sourceImage.Bounds()\n\tfor index, transformedCoordinate := range transformedCoordinates {\n\t\tvar sourceColorR, sourceColorG, sourceColorB, sourceColorA uint32\n\n\t\tif real(transformedCoordinate) < real(colorValueBoundMin) ||\n\t\t\timag(transformedCoordinate) < imag(colorValueBoundMin) ||\n\t\t\treal(transformedCoordinate) > real(colorValueBoundMax) ||\n\t\t\timag(transformedCoordinate) > imag(colorValueBoundMax) {\n\t\t\tsourceColorR, sourceColorG, sourceColorB, sourceColorA = 0, 0, 0, 0\n\t\t} else {\n\t\t\tsourceImagePixelX := int(mathutility.ScaleValueBetweenTwoRanges(\n\t\t\t\tfloat64(real(transformedCoordinate)),\n\t\t\t\treal(colorValueBoundMin),\n\t\t\t\treal(colorValueBoundMax),\n\t\t\t\tfloat64(sourceImageBounds.Min.X),\n\t\t\t\tfloat64(sourceImageBounds.Max.X),\n\t\t\t))\n\t\t\tsourceImagePixelY := int(mathutility.ScaleValueBetweenTwoRanges(\n\t\t\t\tfloat64(imag(transformedCoordinate)),\n\t\t\t\timag(colorValueBoundMin),\n\t\t\t\timag(colorValueBoundMax),\n\t\t\t\tfloat64(sourceImageBounds.Min.Y),\n\t\t\t\tfloat64(sourceImageBounds.Max.Y),\n\t\t\t))\n\t\t\tsourceColorR, sourceColorG, sourceColorB, sourceColorA = sourceImage.At(sourceImagePixelX, sourceImagePixelY).RGBA()\n\t\t}\n\n\t\tdestinationPixelX := int(real(destinationCoordinates[index]))\n\t\tdestinationPixelY := int(imag(destinationCoordinates[index]))\n\n\t\tdestinationImage.Set(\n\t\t\tdestinationPixelX,\n\t\t\tdestinationPixelY,\n\t\t\tcolor.NRGBA{\n\t\t\t\tR: uint8(sourceColorR >> 8),\n\t\t\t\tG: uint8(sourceColorG >> 8),\n\t\t\t\tB: uint8(sourceColorB >> 8),\n\t\t\t\tA: uint8(sourceColorA >> 8),\n\t\t\t},\n\t\t)\n\t}\n}", "func newImageBinaryChannels(imgSrc image.Image, colorChannelTypes ...channelType) []*imageBinaryChannel {\n\tchannels := make([]*imageBinaryChannel, 3)\n\tmax := imgSrc.Bounds().Max\n\tw, h := max.X, max.Y\n\tfor i, channelType := range colorChannelTypes {\n\t\tcolorChannel := image.NewGray(image.Rectangle{Max: image.Point{w, h}})\n\t\tfor x := 0; x < w; x++ {\n\t\t\tfor y := 0; y < h; y++ {\n\t\t\t\tcolorPixel := imgSrc.At(x, y).(color.NRGBA)\n\t\t\t\tvar c uint8\n\t\t\t\tswitch channelType {\n\t\t\t\tcase red:\n\t\t\t\t\tc = colorPixel.R\n\t\t\t\tcase green:\n\t\t\t\t\tc = colorPixel.G\n\t\t\t\tcase blue:\n\t\t\t\t\tc = colorPixel.B\n\t\t\t\t}\n\t\t\t\tgrayPixel := color.Gray{Y: c}\n\t\t\t\tcolorChannel.Set(x, y, grayPixel)\n\t\t\t}\n\t\t}\n\t\tchannels[i] = newImageBinaryChannel(colorChannel, channelType)\n\t}\n\treturn channels\n}", "func New() *Color {\n\treturn new(Color)\n}", "func (pw *PixelWand) GetMagickColor() *MagickPixelPacket {\n\tvar mpp C.MagickPixelPacket\n\tC.PixelGetMagickColor(pw.pw, &mpp)\n\truntime.KeepAlive(pw)\n\treturn newMagickPixelPacketFromCAPI(&mpp)\n}", "func ConvertCustom(img image.Image, pal color.Palette) (image.Image, error) {\n\tif len(pal) > 256 {\n\t\treturn nil, errors.New(\"can reduce to a maximum of 256 colors\")\n\t}\n\tpalImg := image.NewPaletted(img.Bounds(), pal)\n\t// For each pixel, go through each color in the palette and pick out the closest one.\n\tfor y := img.Bounds().Min.Y; y < img.Bounds().Max.Y; y++ {\n\t\tfor x := img.Bounds().Min.X; x < img.Bounds().Max.X; x++ {\n\t\t\tsourceColor := img.At(x, y)\n\t\t\tcolorIndex := uint8(pal.Index(sourceColor))\n\t\t\tpalImg.SetColorIndex(x, y, colorIndex)\n\t\t}\n\t}\n\treturn palImg, nil\n}", "func (model *MLModel) PredictWithImageFile(filepath string, color string) ([][]float32, error) {\n\tvar img gocv.Mat\n\n\tswitch color {\n\tcase \"rgb\":\n\t\timg = gocv.IMRead(filepath, gocv.IMReadColor)\n\t\tconvertedImg := gocv.NewMat()\n\t\tgocv.CvtColor(img, &convertedImg, gocv.ColorBGRToRGB)\n\t\treturn model.predict(&convertedImg)\n\n\tcase \"gray\":\n\t\timg = gocv.IMRead(filepath, gocv.IMReadGrayScale)\n\t\treturn model.predict(&img)\n\n\tdefault:\n\t\timg = gocv.IMRead(filepath, gocv.IMReadColor)\n\t\treturn model.predict(&img)\n\t}\n}", "func (im *imageContrller) SerializeImage(img *image.RGBA) []color.RGBA {\n\tdata := make([]color.RGBA, 0)\n\n\tif img != nil {\n\t\tfor i := 0; i < img.Bounds().Size().X; i++ {\n\t\t\tfor j := 0; j < img.Bounds().Size().Y; j++ {\n\n\t\t\t\t// extract point data\n\t\t\t\trgba := img.At(i, j)\n\n\t\t\t\t// each channel data\n\t\t\t\tr, g, b, a := rgba.RGBA()\n\n\t\t\t\t// create raw data\n\t\t\t\trawdata := color.RGBA{\n\t\t\t\t\tR: uint8(r),\n\t\t\t\t\tG: uint8(g),\n\t\t\t\t\tB: uint8(b),\n\t\t\t\t\tA: uint8(a),\n\t\t\t\t}\n\n\t\t\t\t// stack data\n\t\t\t\tdata = append(data, rawdata)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn data\n}", "func (s Sprite) Image() *image.RGBA {\n\tim := image.NewRGBA(image.Rect(0, 0, 8, 8))\n\tfor i, v := range s.Colors() {\n\t\tim.Set(i%8, i/8, colors[v])\n\t}\n\treturn im\n}", "func computeAverageColor(img image.Image) color.NRGBA {\n\tbounds := img.Bounds()\n\tpoints := uint64(0)\n\tred := uint64(0)\n\tgreen := uint64(0)\n\tblue := uint64(0)\n\tfor y := 0; y < bounds.Max.Y; y++ {\n\t\tfor x := 0; x < bounds.Max.X; x++ {\n\t\t\tcurColor := color.NRGBAModel.Convert(img.At(x, y)).(color.NRGBA)\n\t\t\tpoints++\n\t\t\tred += uint64(curColor.R)\n\t\t\tgreen += uint64(curColor.G)\n\t\t\tblue += uint64(curColor.B)\n\t\t}\n\t}\n\n\tavgRed := red / points\n\tavgGreen := green / points\n\tavgBlue := blue / points\n\n\treturn color.NRGBA{\n\t\tR: uint8(avgRed),\n\t\tG: uint8(avgGreen),\n\t\tB: uint8(avgBlue),\n\t\tA: 255,\n\t}\n}", "func Interpolate(src image.Image, cube colorcube.Cube, intensity float64) (image.Image, error) {\n\tif intensity < 0 || intensity > 1 {\n\t\treturn src, errors.New(\"intensity must be between 0 and 1\")\n\t}\n\n\tbounds := src.Bounds()\n\n\tout := image.NewNRGBA(image.Rectangle{\n\t\timage.Point{0, 0},\n\t\timage.Point{bounds.Max.X, bounds.Max.Y},\n\t})\n\n\tk := (float64(cube.Size) - 1) / bpc\n\n\tspace := &image.NRGBA{}\n\tmodel := space.ColorModel()\n\n\tdKR := cube.DomainMax[0] - cube.DomainMin[0]\n\tdKG := cube.DomainMax[1] - cube.DomainMin[1]\n\tdKB := cube.DomainMax[2] - cube.DomainMin[2]\n\n\twidth, height := bounds.Dx(), bounds.Dy()\n\tparallel.Line(height, func(start, end int) {\n\t\tfor y := start; y < end; y++ {\n\t\t\tfor x := 0; x < width; x++ {\n\t\t\t\tpx := src.At(x, y)\n\t\t\t\tc := model.Convert(px).(color.NRGBA)\n\n\t\t\t\trgb := getFromRGBTrilinear(\n\t\t\t\t\tint(c.R),\n\t\t\t\t\tint(c.G),\n\t\t\t\t\tint(c.B),\n\t\t\t\t\tcube.Size,\n\t\t\t\t\tk,\n\t\t\t\t\tcube,\n\t\t\t\t)\n\n\t\t\t\to := color.NRGBA{}\n\t\t\t\to.R = uint8(float64(c.R)*(1-intensity) + float64(toIntCh(rgb[0]*dKR))*intensity)\n\t\t\t\to.G = uint8(float64(c.G)*(1-intensity) + float64(toIntCh(rgb[1]*dKG))*intensity)\n\t\t\t\to.B = uint8(float64(c.B)*(1-intensity) + float64(toIntCh(rgb[2]*dKB))*intensity)\n\t\t\t\to.A = c.A\n\n\t\t\t\tout.Set(x, y, o)\n\t\t\t}\n\t\t}\n\t})\n\n\treturn out, nil\n}", "func TestColorConversion(t *testing.T) {\n\trgb := color.RGBA{64, 0, 128, 255}\n\tcoef := colorToCoef(rgb)\n\tif !equal(coef, Coef{0.131975, -0.0117025, 0.2084315}) {\n\t\tt.Errorf(\"Conversion failed (%v to %v)\", rgb, coef)\n\t}\n}", "func Linear(img image.Image, value float64) image.Image {\n\treturn utils.MapColor(img, LinearC(value))\n}", "func (c FieldsCollection) Color() *models.Field {\n\treturn c.MustGet(\"Color\")\n}", "func GenerateImage(seed float64, size float64, pixelBitMask []float64) image.Image {\n\tisize := int(size)\n\timg := image.NewRGBA(image.Rect(0, 0, isize, isize))\n\n\tpixelBase := uint64(seed + 1)\n\t// Fill up each pixel in the image\n\tfor px := 0; px < isize*isize; px++ {\n\t\tx := px / isize\n\t\ty := px % isize\n\n\t\t// Get this permutations value for each pixel (divide with that bit's positional value to normalizeit to 1)\n\t\tpixelBitVal := uint64(pixelBitMask[px])\n\t\tisDark := pixelBase & pixelBitVal / pixelBitVal\n\n\t\tcol := uint8(isDark * darkPixel)\n\t\timg.Set(x, y, color.RGBA{col, col, col, 255})\n\t}\n\treturn img\n}", "func (m *Module) OutputColor(colorFunc func(Info) color.Color) *Module {\n\tc := m.getFormat()\n\tc.colorFunc = colorFunc\n\tm.format.Set(c)\n\treturn m\n}", "func colorToMode(c cell.Color, colorMode terminalapi.ColorMode) cell.Color {\n\tif c == cell.ColorDefault {\n\t\treturn c\n\t}\n\tswitch colorMode {\n\tcase terminalapi.ColorModeNormal:\n\t\tc %= 16 + 1 // Add one for cell.ColorDefault.\n\tcase terminalapi.ColorMode256:\n\t\tc %= 256 + 1 // Add one for cell.ColorDefault.\n\tcase terminalapi.ColorMode216:\n\t\tif c <= 216 { // Add one for cell.ColorDefault.\n\t\t\treturn c + 16\n\t\t}\n\t\tc = c%216 + 16\n\tcase terminalapi.ColorModeGrayscale:\n\t\tif c <= 24 { // Add one for cell.ColorDefault.\n\t\t\treturn c + 232\n\t\t}\n\t\tc = c%24 + 232\n\tdefault:\n\t\tc = cell.ColorDefault\n\t}\n\treturn c\n}", "func EncodeImage(img draw.Image) {\n\tbounds := img.Bounds()\n\n\tswitch inputImg := img.(type) {\n\n\tcase *image.RGBA64:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\tinputImg.SetRGBA64(j, i, EncodeColor(inputImg.RGBA64At(j, i)))\n\t\t\t}\n\t\t}\n\n\tdefault:\n\t\tfor i := bounds.Min.Y; i < bounds.Max.Y; i++ {\n\t\t\tfor j := bounds.Min.X; j < bounds.Max.X; j++ {\n\t\t\t\timg.Set(j, i, EncodeColor(img.At(j, i)))\n\t\t\t}\n\t\t}\n\t}\n}", "func (img Image) groupPixelOverColor() map[color.Color]int {\n\tcol := img.height\n\trow := img.width\n\n\tm := make(map[color.Color]int)\n\tfor i := 0; i < col*row; i++ {\n\n\t\tr, g, b, a := getP9RGBA(img.pixels[i])\n\t\tcurrentColor := color.RGBA{r, g, b, a}\n\n\t\tif _, ok := m[currentColor]; ok {\n\t\t\tm[currentColor]++\n\t\t} else {\n\t\t\tm[currentColor] = 0\n\t\t}\n\t}\n\n\treturn m\n}", "func (a *ImageApiService) ImageConvertColorDepth(ctx _context.Context, imageConvertColorDepthParameters ImageConvertColorDepthParameters) (ImageConvertColorDepthResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ImageConvertColorDepthResponse\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/api/image/ImageConvertColorDepth\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json-patch+json\", \"application/json\", \"text/json\", \"application/_*+json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"text/plain\", \"application/json\", \"text/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = &imageConvertColorDepthParameters\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v ImageConvertColorDepthResponse\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (m *TagManager) ChangeColor(name, color string) error {\n\ttag, err := m.Get(name)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error getting tag %v\", err)\n\t}\n\tif color != tag.Color {\n\t\tif err := m.DB.Model(&tag).Update(\"color\", color).Error; err != nil {\n\t\t\treturn fmt.Errorf(\"Update %v\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (im *imageContrller) CreateImage(data []color.RGBA, height, width int) *image.RGBA {\n\timg := new(image.RGBA)\n\n\tif height > 0 && width > 0 {\n\t\t// check data size\n\t\tif (height * width) == len(data) {\n\n\t\t\t// create image\n\t\t\tcanvas := image.NewRGBA(image.Rect(0, 0, width, height))\n\t\t\tfor i := 0; i < width; i++ {\n\t\t\t\tfor j := 0; j < height; j++ {\n\t\t\t\t\tindex := width*i + j\n\n\t\t\t\t\t// raw data\n\t\t\t\t\trawData := color.RGBA{\n\t\t\t\t\t\tR: data[index].R,\n\t\t\t\t\t\tG: data[index].G,\n\t\t\t\t\t\tB: data[index].B,\n\t\t\t\t\t\tA: 255,\n\t\t\t\t\t}\n\n\t\t\t\t\t// draw the raw data on canvas\n\t\t\t\t\tcanvas.Set(i, j, rawData)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// update image\n\t\t\timg = canvas\n\t\t}\n\t}\n\treturn img\n}", "func newColorsImage(width, height int, colors []colorFreq, save bool) image.Image {\n\timg := image.NewRGBA(image.Rectangle{image.Point{0, 0}, image.Point{width, height}})\n\tvar xStart, xEnd int\n\t// for each color, calculate the start and end x positions, then fill in the column\n\tfor i, c := range colors {\n\t\tif i == 0 {\n\t\t\txStart = 0\n\t\t} else {\n\t\t\txStart = xEnd\n\t\t}\n\t\txEnd = xStart + int(c.freq*float32(width))\n\n\t\tfor x := xStart; x < xEnd; x++ {\n\t\t\tfor y := 0; y < height; y++ {\n\t\t\t\timg.Set(x, y, c.color)\n\t\t\t}\n\t\t}\n\t}\n\n\tif save {\n\t\tout, _ := os.Create(\"./newColorsImage.png\")\n\t\tjpeg.Encode(out, img, nil)\n\t}\n\n\treturn img\n}", "func (b *Base) getColor() bool {\n\treturn b.isBlack\n}", "func (n *Node) Color(c color.Color) *Node {\n\tcol, alpha := colorAndAlpha(c)\n\tn.setAttr(\"alpha\", alpha)\n\treturn n.setAttr(\"color\", col)\n}", "func NewColor(r, g, b float64) *Color {\n\treturn &Color{r, g, b}\n}", "func WriteColor(w io.Writer, color *Vec3, samplesPerPixel int) error {\n\tr := color.X\n\tg := color.Y\n\tb := color.Z\n\n\t// Divide the color by the number of samples and gamma-correct for gamma = 2.0\n\tscale := 1.0 / float64(samplesPerPixel)\n\tr = math.Sqrt(r * scale)\n\tg = math.Sqrt(g * scale)\n\tb = math.Sqrt(b * scale)\n\n\t// Write the translated [0,255] value of each color component\n\toutput := fmt.Sprintf(\"%d %d %d\\n\", int(256*clamp(r, 0.0, 0.999)), int(256*clamp(g, 0.0, 0.999)), int(256*clamp(b, 0.0, 0.999)))\n\t_, err := w.Write([]byte(output))\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func ColorMaterial(face uint32, mode uint32) {\n\tsyscall.Syscall(gpColorMaterial, 2, uintptr(face), uintptr(mode), 0)\n}", "func (cv *ColorValue) GetColor(u float64, v float64) vmath.Vector3d {\n\treturn cv.Color\n}", "func BgColor(value color.Color) *SimpleElement { return newSEColor(\"bgColor\", value) }", "func NewColor(r, g, b float32) Color {\n\treturn Color{geo.NewVec3(r, g, b)}\n}", "func Map(f func() Composable) func(image.Image) image.Image {\n\treturn func(img image.Image) image.Image {\n\t\treturn MapColor(img, f())\n\t}\n}", "func NewColor(r, g, b float64) *Color {\n\treturn &Color{\n\t\tr: r,\n\t\tg: g,\n\t\tb: b,\n\t}\n}", "func (r ApiGetBitlinkQRCodeRequest) Color(color string) ApiGetBitlinkQRCodeRequest {\n\tr.color = &color\n\treturn r\n}", "func GetColor(c *fiber.Ctx) error {\n\tdb := database.DBConn\n\tid := c.Params(\"id\")\n\n\tvar color models.Color\n\tdb.First(&color, id)\n\n\tif color.ID == 0 {\n\t\treturn c.Status(404).JSON(fiber.Map{\n\t\t\t\"detail\": \"color not found\",\n\t\t})\n\t}\n\treturn c.JSON(color)\n}", "func (l *Legofy) applyColorOverlay(brickImg image.Image, brickColor color.Color, pixel int) *image.RGBA {\n\n\toverlayR, overlayG, overlayB, overlayA := brickColor.RGBA()\n\tbrickY := brickImg.Bounds().Max.Y\n\tbrickX := brickImg.Bounds().Max.X\n\n\tcimg := image.NewRGBA(brickImg.Bounds())\n\tdraw.Draw(cimg, brickImg.Bounds(), brickImg, image.Point{}, draw.Src)\n\tfor y := 0; y < brickY; y++ {\n\t\tfor x := 0; x < brickX; x++ {\n\t\t\tcimg.Set(x, y, color.RGBA{l.overLayeffect(uint8(overlayR)), l.overLayeffect(uint8(overlayG)), l.overLayeffect(uint8(overlayB)), uint8(overlayA)})\n\t\t}\n\t}\n\n\treturn blend.Overlay(cimg, brickImg)\n}", "func (r *ImageRef) ToColorSpace(interpretation Interpretation) error {\n\tout, err := vipsToColorSpace(r.image, interpretation)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.setImage(out)\n\treturn nil\n}", "func ColorMaterial(face uint32, mode uint32) {\n C.glowColorMaterial(gpColorMaterial, (C.GLenum)(face), (C.GLenum)(mode))\n}", "func makeEmptyColoredImage(width, height int, color color.RGBA) *image.RGBA {\n\treturnImage := image.NewRGBA(image.Rect(0, 0, width, height))\n\tfor x := 0; x < width; x++ {\n\t\tfor y := 0; y < height; y++ {\n\t\t\treturnImage.Set(x, y, color)\n\t\t}\n\t}\n\treturn returnImage\n}", "func (c *Color) Mul(o *Color) *Color {\n\treturn NewColor(\n\t\tc.r*o.r,\n\t\tc.g*o.g,\n\t\tc.b*o.b,\n\t)\n}", "func NewColorful(color colorful.Color) Colored {\n\tr, g, b := color.RGB255()\n\th := (0xFF << 24) + (uint32(r) << 16) + (uint32(g) << 8) + (uint32(b))\n\treturn NewColored(h)\n}", "func convert(img image.Image, w, h int) (*Image, error) {\n\tif img == nil {\n\t\treturn nil, errors.New(\"No image found\")\n\t}\n\t// set output image size\n\twidth := w\n\theight := h\n\tif w <= 0 || h <= 0 {\n\t\twidth = imageWidth\n\t\tsz := img.Bounds()\n\t\theight = (sz.Max.Y * width * 10) / (sz.Max.X * 16)\n\t}\n\timg = resize.Resize(uint(width), uint(height), img, resize.Lanczos3)\n\n\ttable := []byte(ASCII)\n\tbuf := new(bytes.Buffer)\n\n\tfor i := 0; i < height; i++ {\n\t\tfor j := 0; j < width; j++ {\n\t\t\tp := img.At(j, i)\n\t\t\tg := color.GrayModel.Convert(p)\n\t\t\ty, _, _, _ := g.RGBA()\n\t\t\tpos := int(y * 16 / 1 >> 16)\n\t\t\t_ = buf.WriteByte(table[pos])\n\t\t}\n\t\t_ = buf.WriteByte('\\n')\n\t}\n\n\treturn &Image{Data: string(buf.Bytes())}, nil\n}", "func createFilter(img image.Image, factor [2]float32, size int, kernel func(float32) float32) (f Filter) {\n\tsizeX := size * (int(math.Ceil(float64(factor[0]))))\n\tsizeY := size * (int(math.Ceil(float64(factor[1]))))\n\n\tswitch img.(type) {\n\tdefault:\n\t\tf = &filterModel{\n\t\t\t&genericConverter{img},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\tcase *image.RGBA:\n\t\tf = &filterModel{\n\t\t\t&rgbaConverter{img.(*image.RGBA)},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\tcase *image.RGBA64:\n\t\tf = &filterModel{\n\t\t\t&rgba64Converter{img.(*image.RGBA64)},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\tcase *image.Gray:\n\t\tf = &filterModel{\n\t\t\t&grayConverter{img.(*image.Gray)},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\tcase *image.Gray16:\n\t\tf = &filterModel{\n\t\t\t&gray16Converter{img.(*image.Gray16)},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\tcase *image.YCbCr:\n\t\tf = &filterModel{\n\t\t\t&ycbcrConverter{img.(*image.YCbCr)},\n\t\t\tfactor, kernel,\n\t\t\tmake([]colorArray, sizeX), make([]colorArray, sizeY),\n\t\t}\n\t}\n\treturn\n}" ]
[ "0.8242761", "0.80681044", "0.79899585", "0.75097203", "0.73353606", "0.70004386", "0.6947597", "0.6749219", "0.67215693", "0.66763604", "0.64292216", "0.6392971", "0.6297295", "0.62861013", "0.5768457", "0.5669885", "0.5514518", "0.5475005", "0.5404894", "0.54047644", "0.5381148", "0.53669256", "0.5342372", "0.53009826", "0.52654046", "0.52571064", "0.5147455", "0.5100304", "0.50843304", "0.5064566", "0.50509155", "0.5039767", "0.50280404", "0.4980993", "0.4978749", "0.49610546", "0.49600032", "0.49363723", "0.4932463", "0.49152824", "0.48491436", "0.48138407", "0.47968662", "0.47868773", "0.47822264", "0.47774723", "0.47748643", "0.47705317", "0.47644904", "0.4750739", "0.47421086", "0.47330675", "0.47270033", "0.47023612", "0.46700317", "0.46635666", "0.46457973", "0.46440193", "0.464041", "0.46386832", "0.46280926", "0.4619887", "0.4609814", "0.4592958", "0.4584692", "0.4570739", "0.45627084", "0.45429912", "0.45374227", "0.4525003", "0.4509918", "0.45031983", "0.44996244", "0.44959286", "0.44956917", "0.44943538", "0.4494183", "0.4491033", "0.4474522", "0.44700906", "0.44652325", "0.44635823", "0.44634435", "0.44558078", "0.44527638", "0.44509956", "0.4450307", "0.44499618", "0.44463214", "0.4442516", "0.4434129", "0.44299987", "0.4428463", "0.44178048", "0.44141975", "0.44008365", "0.43887678", "0.43851233", "0.43849498", "0.4380693" ]
0.75799555
3
Bounds implements image.Image interface.
func (p *Magnifier) Bounds() image.Rectangle { r := p.Image.Bounds() r.Min.X *= p.Sx r.Min.Y *= p.Sy r.Max.X *= p.Sx r.Max.Y *= p.Sy return r }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Image) Bounds() image.Rectangle {\n\td := (c.Size + 8) * c.Scale\n\treturn image.Rect(0, 0, d, d)\n}", "func (p *RGBAf) Bounds() image.Rectangle { return p.Rect }", "func (w *worldImg) Bounds() image.Rectangle {\n\treturn image.Rect(0, 0, w.W, w.H)\n}", "func (receiver Type) Bounds() image.Rectangle {\n\treturn image.Rect(minX,minY, maxX,maxY)\n}", "func (e *Emulator) Bounds() image.Rectangle { return image.Rect(0, 0, e.Width, e.Height) }", "func (f *YFastBilateral) Bounds() image.Rectangle {\n\treturn f.HDRImage.Bounds()\n}", "func (vb *ViewBox2D) Bounds() image.Rectangle {\n\treturn image.Rect(vb.Min.X, vb.Min.Y, vb.Min.X+vb.Size.X, vb.Min.Y+vb.Size.Y)\n}", "func (p *PalettedBitmap) Bounds() image.Rectangle {\n\treturn p.Image.Bounds()\n}", "func (g GIF) Bounds() image.Rectangle {\n\treturn g.GIF.Image[0].Bounds()\n}", "func (f *Face) Bounds() image.Rectangle {\n\treturn image.Rect(f.xpixels(int(f.handle.bbox.xMin)),\n\t\tf.ypixels(int(f.handle.bbox.yMin)),\n\t\tf.xpixels(int(f.handle.bbox.xMax)),\n\t\tf.ypixels(int(f.handle.bbox.yMax)))\n}", "func (f *Frame) Bounds() image.Rectangle {\n\treturn f.r.Bounds()\n}", "func (b Buffer) Bounds() image.Rectangle {\n\tx0, y0, x1, y1 := 0, 0, 0, 0\n\tfor p := range b.CellMap {\n\t\tif p.X > x1 {\n\t\t\tx1 = p.X\n\t\t}\n\t\tif p.X < x0 {\n\t\t\tx0 = p.X\n\t\t}\n\t\tif p.Y > y1 {\n\t\t\ty1 = p.Y\n\t\t}\n\t\tif p.Y < y0 {\n\t\t\ty0 = p.Y\n\t\t}\n\t}\n\treturn image.Rect(x0, y0, x1+1, y1+1)\n}", "func (m *CvMat) Bounds() image.Rectangle {\n\n\ts := m.Size()\n\n\t// check if matrix has two dimensions\n\tif len(s) != 2 {\n\t\t// We have to panic here in order to fulfill the image.Image()\n\t\t// interface. An error check should be made earlier if you are\n\t\t// really unsure if the matrix has more than two dimensions.\n\t\tpanic(fmt.Sprintf(\"Expected matrix dimension to be 2, was: %d\", len(s)))\n\t}\n\n\treturn image.Rectangle{Min: image.Point{0, 0}, Max: image.Point{s[1], s[0]}}\n}", "func (c *Canvas) Bounds() pixel.Rect {\n\treturn c.gf.Bounds()\n}", "func (gd Grid) Bounds() Range {\n\treturn gd.Rg\n}", "func (s *vSite) Bounds() image.Rectangle {\n\tif s.points == nil {\n\t\ts.build()\n\t}\n\treturn s.bounds\n}", "func (o *Object) Bounds() Rect {\n\treturn R(o.Pos.X, o.Pos.Y, o.Pos.X+o.Size.X, o.Pos.Y+o.Size.Y)\n}", "func (a *ArcParams) Bounds() Rect {\n\tminX, maxX := a.minMaxX()\n\tminY, maxY := a.minMaxY()\n\treturn Rect{Point{minX, minY}, Point{maxX, maxY}}\n}", "func (f *Font) Bounds(scale int32) Bounds {\n\tb := f.bounds\n\tb.XMin = f.scale(scale * b.XMin)\n\tb.YMin = f.scale(scale * b.YMin)\n\tb.XMax = f.scale(scale * b.XMax)\n\tb.YMax = f.scale(scale * b.YMax)\n\treturn b\n}", "func (wb *WidgetBase) Bounds() Rectangle {\n\treturn wb.RectangleTo96DPI(wb.BoundsPixels())\n}", "func (tm *Tilemap) Bounds() pixel.Rect {\n\treturn tm.bounds\n}", "func (eps *EPS) Bounds() (box image.Rectangle) {\n\t// TODO exploit the z-curve to do better and/or cache/pre-compute\n\tit := eps.Iter()\n\tfor it.Next() {\n\t\tif i := it.ID() - 1; eps.ix.flg[i]&epsDef != 0 {\n\t\t\tbox.Min = eps.pt[i]\n\t\t\tbox.Max = box.Min.Add(image.Pt(1, 1))\n\t\t\tbreak\n\t\t}\n\t}\n\tfor it.Next() {\n\t\tif i := it.ID() - 1; eps.ix.flg[i]&epsDef != 0 {\n\t\t\tbox = rectangle.Capture(box, eps.pt[i])\n\t\t}\n\t}\n\treturn box\n}", "func (self *TileSprite) GetBoundsI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"getBounds\", args)}\n}", "func (m *Circle) Bounds() s2.Rect {\n\tr := s2.EmptyRect()\n\tr = r.AddPoint(m.getLatLng(false))\n\tr = r.AddPoint(m.getLatLng(true))\n\treturn r\n}", "func (p *Area) Bounds() s2.Rect {\n\tr := s2.EmptyRect()\n\tfor _, ll := range p.Positions {\n\t\tr = r.AddPoint(ll)\n\t}\n\treturn r\n}", "func (me *Point) Bounds() Rect {\n\treturn Rect{Min: *me, Max: *me}\n}", "func (self *Graphics) GetBoundsI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"getBounds\", args)}\n}", "func (tp Tiles) Bounds() coord.Range {\n\tbounds := coord.Range{\n\t\tMin: coord.Make(math.MaxInt32, math.MaxInt32),\n\t\tMax: coord.Make(math.MinInt32, math.MinInt32),\n\t}\n\n\tfor _, p := range tp {\n\t\tbounds = bounds.Include(p.Coord)\n\t}\n\n\treturn bounds\n}", "func (b Boundary) Rectangle() image.Rectangle {\n\treturn image.Rect(\n\t\tb.X, b.Y,\n\t\tb.X+b.Width, b.Y+b.Height,\n\t)\n}", "func (r Rectangle) Bounds() Rectangle {\n\treturn r\n}", "func (p *Particle) Bounds(maxx, maxy float64) {\n\tif p.Position[0] > maxx {\n\t\tp.Position[0] = 0.0\n\t}\n\tif p.Position[1] > maxy {\n\t\tp.Position[1] = 0.0\n\t}\n\n\tif p.Position[0] < 0.0 {\n\t\tp.Position[0] = maxx\n\t}\n\tif p.Position[1] < 0.0 {\n\t\tp.Position[1] = maxy\n\t}\n}", "func (p Polygon) Bounds() *Bounds {\n\tb := NewBounds()\n\tb.extendPointss(p)\n\treturn b\n}", "func (c *Camera) santizeBounds() {\n\t// x and y\n\tif c.x < 0 {\n\t\tc.x = 0\n\t}\n\tif c.y < 0 {\n\t\tc.y = 0\n\t}\n\tif c.x+c.width > c.worldWidth {\n\t\tc.x = c.worldWidth - c.width\n\t}\n\tif c.y+c.height > c.worldHeight {\n\t\tc.y = c.worldHeight - c.height\n\t}\n\n\t// width and height\n\tif c.width < 100 {\n\t\tc.width = 100\n\t}\n\tif c.height < 100 {\n\t\tc.height = 100\n\t}\n\tif c.width > c.worldWidth {\n\t\tc.width = c.worldWidth\n\t}\n\tif c.height > c.worldHeight {\n\t\tc.height = c.worldHeight\n\t}\n}", "func (s *ShapeIndexRegion) RectBound() Rect {\n\tcu := CellUnion(s.CellUnionBound())\n\treturn cu.RectBound()\n}", "func BoundsRect(b Bounder) *Rect {\n\treturn NewRect(b.Min(), b.Max())\n}", "func (g *Grid) Bounds() (topleft, bottonright Point) {\n\tmin := Point{BIG, BIG}\n\tmax := Point{-1 * BIG, -1 * BIG}\n\tfor _, p := range g.Points {\n\t\tif p[0] < min[0] {\n\t\t\tmin[0] = p[0]\n\t\t}\n\t\tif p[1] < min[1] {\n\t\t\tmin[1] = p[1]\n\t\t}\n\t\tif p[0] > max[0] {\n\t\t\tmax[0] = p[0]\n\t\t}\n\t\tif p[1] > max[1] {\n\t\t\tmax[1] = p[1]\n\t\t}\n\t}\n\t// add some padding\n\tmin[0] -= PAD\n\tmin[1] -= PAD\n\tmax[0] += PAD\n\tmax[1] += PAD\n\n\treturn min, max\n}", "func (wb *WidgetBase) BoundsPixels() Rectangle {\n\tb := wb.WindowBase.BoundsPixels()\n\n\tif wb.parent != nil {\n\t\tp := b.Location().toPOINT()\n\t\tif !win.ScreenToClient(wb.parent.Handle(), &p) {\n\t\t\tnewError(\"ScreenToClient failed\")\n\t\t\treturn Rectangle{}\n\t\t}\n\t\tb.X = int(p.X)\n\t\tb.Y = int(p.Y)\n\t}\n\n\treturn b\n}", "func Bounds(x, y, w, h int) {\n\tgl.Viewport(int32(x), int32(y), int32(w), int32(h))\n\tgl.Scissor(int32(x), int32(y), int32(w), int32(h))\n}", "func (n *Node) SliceBounds() (low, high, max *Node)", "func DrawRect(img *ebiten.Image, bounds vec2.Rect, clr color.Color) {\n\trectImg, _ := ebiten.NewImage(\n\t\tint(bounds.Width()),\n\t\tint(bounds.Height()),\n\t\tebiten.FilterDefault,\n\t)\n\tfor x := 0; x < int(bounds.Width()); x++ {\n\t\trectImg.Set(x, 0, clr)\n\t\trectImg.Set(x, int(bounds.Height())-1, clr)\n\t}\n\tfor y := 0; y < int(bounds.Height()); y++ {\n\t\trectImg.Set(0, y, clr)\n\t\trectImg.Set(int(bounds.Width())-1, y, clr)\n\t}\n\timg.DrawImage(rectImg, &ebiten.DrawImageOptions{\n\t\tGeoM: ebiten.TranslateGeo(bounds.X(), bounds.Y()),\n\t})\n}", "func (m *AssignedEntitiesWithMetricTile) Bounds() *TileBounds {\n\treturn m.boundsField\n}", "func (r *FlakeRegion) Bounds(p float64) (start, stop int) {\n\tdist := GeometricDist{P: r.FailureProbability}\n\tdelta := dist.InvCDF(1 - p)\n\treturn r.First - delta, r.Last + delta\n}", "func resizeImage(img *image.Image) image.Image {\n\tFIU.Trace.Println(\"resizeImage()\")\n\tnewimg := resize.Thumbnail(max_width, max_height, *img, resize.Lanczos3)\n\tFIU.Trace.Printf(\"New Bounds : %d, %d\", newimg.Bounds().Max.X, newimg.Bounds().Max.Y)\n\treturn newimg\n}", "func (f *Feature) Bounds() *rtreego.Rect {\n\treturn f.location\n}", "func Rect(size image.Rectangle) clip.Op {\n\treturn clip.Rect(size).Op()\n}", "func (p *Image64) SubImage(r image.Rectangle) image.Image {\n\tr = r.Intersect(p.Rect)\n\tif r.Empty() {\n\t\treturn &Image64{}\n\t}\n\ti := (r.Min.Y-p.Rect.Min.Y)*p.Stride + (r.Min.X - p.Rect.Min.X)\n\treturn &Image64{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (self *TileSprite) GetBounds() *Rectangle{\n return &Rectangle{self.Object.Call(\"getBounds\")}\n}", "func (p *Gray) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Gray{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Gray{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (self *TileSprite) GetLocalBoundsI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"getLocalBounds\", args)}\n}", "func (self *Graphics) GetBounds() *Rectangle{\n return &Rectangle{self.Object.Call(\"getBounds\")}\n}", "func (d *Driver) Bounds() *rtreego.Rect {\n\treturn rtreego.Point{d.LastLocation.Lat, d.LastLocation.Lon}.ToRect(0.01)\n}", "func (s *State) WindowBounds() image.Rectangle {\n\treturn s.windowSize.Sub(s.bounds.Min)\n}", "func (o *WObj) Bounds() (float64, float64) {\n\tbnds := o.Hitbox.Bounds()\n\treturn bnds.X, bnds.Y\n}", "func (c Cell) RectBound() Rect {\n\tif c.level > 0 {\n\t\t// Except for cells at level 0, the latitude and longitude extremes are\n\t\t// attained at the vertices. Furthermore, the latitude range is\n\t\t// determined by one pair of diagonally opposite vertices and the\n\t\t// longitude range is determined by the other pair.\n\t\t//\n\t\t// We first determine which corner (i,j) of the cell has the largest\n\t\t// absolute latitude. To maximize latitude, we want to find the point in\n\t\t// the cell that has the largest absolute z-coordinate and the smallest\n\t\t// absolute x- and y-coordinates. To do this we look at each coordinate\n\t\t// (u and v), and determine whether we want to minimize or maximize that\n\t\t// coordinate based on the axis direction and the cell's (u,v) quadrant.\n\t\tu := c.uv.X.Lo + c.uv.X.Hi\n\t\tv := c.uv.Y.Lo + c.uv.Y.Hi\n\t\tvar i, j int\n\t\tif uAxis(int(c.face)).Z == 0 {\n\t\t\tif u < 0 {\n\t\t\t\ti = 1\n\t\t\t}\n\t\t} else if u > 0 {\n\t\t\ti = 1\n\t\t}\n\t\tif vAxis(int(c.face)).Z == 0 {\n\t\t\tif v < 0 {\n\t\t\t\tj = 1\n\t\t\t}\n\t\t} else if v > 0 {\n\t\t\tj = 1\n\t\t}\n\t\tlat := r1.IntervalFromPoint(c.latitude(i, j)).AddPoint(c.latitude(1-i, 1-j))\n\t\tlng := s1.EmptyInterval().AddPoint(c.longitude(i, 1-j)).AddPoint(c.longitude(1-i, j))\n\n\t\t// We grow the bounds slightly to make sure that the bounding rectangle\n\t\t// contains LatLngFromPoint(P) for any point P inside the loop L defined by the\n\t\t// four *normalized* vertices. Note that normalization of a vector can\n\t\t// change its direction by up to 0.5 * dblEpsilon radians, and it is not\n\t\t// enough just to add Normalize calls to the code above because the\n\t\t// latitude/longitude ranges are not necessarily determined by diagonally\n\t\t// opposite vertex pairs after normalization.\n\t\t//\n\t\t// We would like to bound the amount by which the latitude/longitude of a\n\t\t// contained point P can exceed the bounds computed above. In the case of\n\t\t// longitude, the normalization error can change the direction of rounding\n\t\t// leading to a maximum difference in longitude of 2 * dblEpsilon. In\n\t\t// the case of latitude, the normalization error can shift the latitude by\n\t\t// up to 0.5 * dblEpsilon and the other sources of error can cause the\n\t\t// two latitudes to differ by up to another 1.5 * dblEpsilon, which also\n\t\t// leads to a maximum difference of 2 * dblEpsilon.\n\t\treturn Rect{lat, lng}.expanded(LatLng{s1.Angle(2 * dblEpsilon), s1.Angle(2 * dblEpsilon)}).PolarClosure()\n\t}\n\n\t// The 4 cells around the equator extend to +/-45 degrees latitude at the\n\t// midpoints of their top and bottom edges. The two cells covering the\n\t// poles extend down to +/-35.26 degrees at their vertices. The maximum\n\t// error in this calculation is 0.5 * dblEpsilon.\n\tvar bound Rect\n\tswitch c.face {\n\tcase 0:\n\t\tbound = Rect{r1.Interval{-math.Pi / 4, math.Pi / 4}, s1.Interval{-math.Pi / 4, math.Pi / 4}}\n\tcase 1:\n\t\tbound = Rect{r1.Interval{-math.Pi / 4, math.Pi / 4}, s1.Interval{math.Pi / 4, 3 * math.Pi / 4}}\n\tcase 2:\n\t\tbound = Rect{r1.Interval{poleMinLat, math.Pi / 2}, s1.FullInterval()}\n\tcase 3:\n\t\tbound = Rect{r1.Interval{-math.Pi / 4, math.Pi / 4}, s1.Interval{3 * math.Pi / 4, -3 * math.Pi / 4}}\n\tcase 4:\n\t\tbound = Rect{r1.Interval{-math.Pi / 4, math.Pi / 4}, s1.Interval{-3 * math.Pi / 4, -math.Pi / 4}}\n\tdefault:\n\t\tbound = Rect{r1.Interval{-math.Pi / 2, -poleMinLat}, s1.FullInterval()}\n\t}\n\n\t// Finally, we expand the bound to account for the error when a point P is\n\t// converted to an LatLng to test for containment. (The bound should be\n\t// large enough so that it contains the computed LatLng of any contained\n\t// point, not just the infinite-precision version.) We don't need to expand\n\t// longitude because longitude is calculated via a single call to math.Atan2,\n\t// which is guaranteed to be semi-monotonic.\n\treturn bound.expanded(LatLng{s1.Angle(dblEpsilon), s1.Angle(0)})\n}", "func (o *ToolOverlay) GetBounds() (x1, y1, x2, y2 float64) {\n\treturn o.leftBound, o.topBound, o.rightBound, o.bottomBound\n}", "func (sfnt *SFNT) GlyphBounds(glyphID uint16) (int16, int16, int16, int16, error) {\n\tif sfnt.IsTrueType {\n\t\tcontour, err := sfnt.Glyf.Contour(glyphID, 0)\n\t\tif err != nil {\n\t\t\treturn 0, 0, 0, 0, err\n\t\t}\n\t\treturn contour.XMin, contour.YMin, contour.XMax, contour.YMax, nil\n\t} else if sfnt.IsCFF {\n\t\tp := &boundsPather{}\n\t\tif err := sfnt.CFF.ToPath(p, glyphID, 0, 0, 0, 1.0, NoHinting); err != nil {\n\t\t\treturn 0, 0, 0, 0, err\n\t\t}\n\t\treturn int16(p.xmin), int16(p.ymin), int16(math.Ceil(p.xmax)), int16(math.Ceil(p.ymax)), nil\n\t}\n\treturn 0, 0, 0, 0, fmt.Errorf(\"only TrueType is supported\")\n}", "func (b BoundingBox) Bounds() BoundingBox {\n\treturn b\n}", "func inBound(x int, y int, length int, width int) bool {\n\tif 0 <= x && x < length && y >= 0 && y < width {\n\t\treturn true\n\t}\n\treturn false\n}", "func Bounds(tileid TileID) Extrema {\n\ta := Ul(tileid)\n\tb := Ul(TileID{tileid.X + 1, tileid.Y + 1, tileid.Z})\n\treturn Extrema{W: a.X, S: b.Y, E: b.X, N: a.Y}\n}", "func (self *Graphics) GetLocalBoundsI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"getLocalBounds\", args)}\n}", "func (p *RGBA64) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &RGBA64{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &RGBA64{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func resizeImage(i image.Image, max int) (image.Image) {\n\tif b := i.Bounds(); b.Dx() > max || b.Dy() > max {\n\t\tw, h := max, max\n if b.Dx() > b.Dy() {\n\t\t\t\th = b.Dy() * h / b.Dx()\n\t\t\t} else {\n\t\t\t\tw = b.Dx() * w / b.Dy()\n\t\t\t}\n\t i = resize.Resize(i, i.Bounds(), w, h)\n }\n\treturn i\n}", "func (p *Paletted) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Paletted{\n\t\t\tPalette: p.Palette,\n\t\t}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Paletted{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: p.Rect.Intersect(r),\n\t\tPalette: p.Palette,\n\t}\n}", "func (p *NRGBA) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &NRGBA{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &NRGBA{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (p *Gray16) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Gray16{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Gray16{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (s Sample) Bounds() (min, max float64) {\n\tif len(s.Xs) == 0 || !s.Sorted {\n\t\treturn Bounds(s.Xs)\n\t}\n\n\treturn s.Xs[0], s.Xs[len(s.Xs)-1]\n}", "func (me *Span) Bounds() Rect {\n\tresult := me.A.Bounds()\n\tresult.AddPoint(&me.Z)\n\n\tvar outs int8\n\tstraight := me.Vector().C()\n\tcurve := complex(1, -me.Bulge)\n\tcurve *= curve\n\tfor i := 0; i < 2; i++ {\n\t\ttangent := straight * curve\n\t\tt2 := signumPair(tangent)\n\t\ts2 := signumPair(straight)\n\t\tfor j, sign := range t2 {\n\t\t\tif sign != 0 && sign != s2[j] {\n\t\t\t\touts |= 1 << (uint(j) + uint(sign+1))\n\t\t\t}\n\t\t}\n\t\tif 0 == i {\n\t\t\t// Other end of Span\n\t\t\tstraight = -straight\n\t\t\tcurve = cmplx.Conj(curve)\n\t\t}\n\t}\n\tif outs != 0 {\n\t\tRadius := me.Radius()\n\t\tCenter := me.Center()\n\n\t\tif outs&1 != 0 {\n\t\t\tresult.Min.X = Center.X - Radius\n\t\t}\n\t\tif outs&2 != 0 {\n\t\t\tresult.Min.Y = Center.Y - Radius\n\t\t}\n\t\tif outs&4 != 0 {\n\t\t\tresult.Max.X = Center.X + Radius\n\t\t}\n\t\tif outs&8 != 0 {\n\t\t\tresult.Max.Y = Center.Y + Radius\n\t\t}\n\t}\n\treturn result\n}", "func (p *NRGBA64) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &NRGBA64{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &NRGBA64{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (l Line) Bounds() Rect {\n\treturn R(l.A.X, l.A.Y, l.B.X, l.B.Y).Norm()\n}", "func (p *RGBA) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &RGBA{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &RGBA{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (ref *UIElement) BoundsForRange(r Range) Rect {\n\ta := cfstr(BoundsForRangeParameterizedAttribute)\n\tdefer C.CFRelease(C.CFTypeRef(a))\n\tcfRange := C.CFRangeMake(C.CFIndex(r.Location), C.CFIndex(r.Length))\n\taxRangeValue := C.AXValueCreate(C.kAXValueTypeCFRange, unsafe.Pointer(&cfRange))\n\tdefer C.CFRelease(C.CFTypeRef(axRangeValue))\n\tvar value C.CFTypeRef\n\tC.AXUIElementCopyParameterizedAttributeValue(ref.obj, a, axRangeValue, &value)\n\tret := convertCFType(value)\n\to, ok := ret.(Rect)\n\tif !ok {\n\t\treturn Rect{Point{0, 0}, Size{0, 0}}\n\t}\n\treturn o\n}", "func (p *CMYK) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &CMYK{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &CMYK{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (p *Gray16) SubImage(r image.Rectangle) image.Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are image.Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Gray16{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Gray16{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (c *TransformComponent) GetBounds() sdl.Rect {\n\treturn sdl.Rect{\n\t\tX: c.Position.X,\n\t\tY: c.Position.Y,\n\t\tW: c.Size.X,\n\t\tH: c.Size.Z,\n\t}\n}", "func (m *AssignedEntitiesWithMetricTile) SetBounds(val *TileBounds) {\n\tm.boundsField = val\n}", "func (mp MultiPolygon) Bounds() *Bounds {\n\tb := NewBounds()\n\tfor _, polygon := range mp {\n\t\tb.Extend(polygon.Bounds())\n\t}\n\treturn b\n}", "func (pa *PodAutoscaler) ScaleBounds(asConfig *autoscalerconfig.Config) (int32, int32) {\n\tvar min int32\n\tif pa.Spec.Reachability != ReachabilityUnreachable {\n\t\tmin = asConfig.MinScale\n\t\tif paMin, ok := pa.annotationInt32(autoscaling.MinScaleAnnotation); ok {\n\t\t\tmin = paMin\n\t\t}\n\t}\n\n\tmax := asConfig.MaxScale\n\tif paMax, ok := pa.annotationInt32(autoscaling.MaxScaleAnnotation); ok {\n\t\tmax = paMax\n\t}\n\n\treturn min, max\n}", "func (p *Alpha) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Alpha{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Alpha{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (c *Canvas) SetBounds(bounds pixel.Rect) {\n\tc.gf.SetBounds(bounds)\n\tif c.sprite == nil {\n\t\tc.sprite = pixel.NewSprite(nil, pixel.Rect{})\n\t}\n\tc.sprite.Set(c, c.Bounds())\n\t//c.sprite.SetMatrix(pixel.IM.Moved(c.Bounds().Center()))\n}", "func Crop(src image.Image, rect image.Rectangle) (dst image.Image, err error) {\n\tif dst, ok := src.(subImageSupported); ok {\n\t\t// fmt.Println(ok)\n\t\treturn dst.SubImage(rect), nil\n\t}\n\treturn cropWithCopy(src, rect)\n}", "func (p *Alpha16) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Alpha16{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &Alpha16{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func checkSize(img image.Image) image.Image {\n\tif img.Bounds().Dx() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(IMAGE_MAX_SIZE, 0, img, resize.Bilinear)\n\t}\n\n\tif img.Bounds().Dy() > IMAGE_MAX_SIZE {\n\t\timg = resize.Resize(0, IMAGE_MAX_SIZE, img, resize.Bilinear)\n\t}\n\n\treturn img\n}", "func (self *TileSprite) GetLocalBounds() *Rectangle{\n return &Rectangle{self.Object.Call(\"getLocalBounds\")}\n}", "func (n *Node) SliceBounds() (low, high, max *Node) {\n\tif n.List.Len() == 0 {\n\t\treturn nil, nil, nil\n\t}\n\n\tswitch n.Op {\n\tcase OSLICE, OSLICEARR, OSLICESTR:\n\t\ts := n.List.Slice()\n\t\treturn s[0], s[1], nil\n\tcase OSLICE3, OSLICE3ARR:\n\t\ts := n.List.Slice()\n\t\treturn s[0], s[1], s[2]\n\t}\n\tFatalf(\"SliceBounds op %v: %v\", n.Op, n)\n\treturn nil, nil, nil\n}", "func (ac *Activity) WindowBounds(ctx context.Context) (Rect, error) {\n\tt, err := ac.getTaskInfo(ctx)\n\tif err != nil {\n\t\treturn Rect{}, errors.Wrap(err, \"failed to get task info\")\n\t}\n\n\t// Fullscreen and maximized windows already include the caption height. PiP windows don't have caption.\n\tif t.windowState == WindowStateFullscreen ||\n\t\tt.windowState == WindowStateMaximized ||\n\t\tt.windowState == WindowStatePIP {\n\t\treturn t.bounds, nil\n\t}\n\n\t// But the rest must have the caption height added to their bounds.\n\tcaptionHeight, err := ac.disp.CaptionHeight(ctx)\n\tif err != nil {\n\t\treturn Rect{}, errors.Wrap(err, \"failed to get caption height\")\n\t}\n\tt.bounds.Top -= captionHeight\n\tt.bounds.Height += captionHeight\n\treturn t.bounds, nil\n}", "func (self *Graphics) GetLocalBounds() *Rectangle{\n return &Rectangle{self.Object.Call(\"getLocalBounds\")}\n}", "func (d *Div) Bounds() *layoutResult {\n\treturn d.layout\n}", "func (p *RGBAf) SubImage(r image.Rectangle) *RGBAf {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &RGBAf{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &RGBAf{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (p *Gray16) SubImage(r image.Rectangle) image.Image {\n\tr = r.Intersect(p.M.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &Gray16{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn new(Gray16).Init(\n\t\tp.M.Pix[i:],\n\t\tp.M.Stride,\n\t\tr,\n\t)\n}", "func (self *Graphics) BoundsPadding() int{\n return self.Object.Get(\"boundsPadding\").Int()\n}", "func (o *BakedLightmapData) GetBounds() gdnative.Aabb {\n\t//log.Println(\"Calling BakedLightmapData.GetBounds()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"BakedLightmapData\", \"get_bounds\")\n\n\t// Call the parent method.\n\t// AABB\n\tretPtr := gdnative.NewEmptyAabb()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewAabbFromPointer(retPtr)\n\treturn ret\n}", "func (vb *ViewBox2D) SizeRect() image.Rectangle {\n\treturn image.Rect(0, 0, vb.Size.X, vb.Size.Y)\n}", "func ResizeImage(img image.Image) image.Image {\n\tbounds := img.Bounds()\n\tif bounds.Max.Y > 7 {\n\t\tw := uint(bounds.Max.X / (bounds.Max.Y / 7))\n\t\timg = resize.Resize(w, 7, img, resize.NearestNeighbor)\n\t}\n\treturn img\n}", "func Crop(img image.Image, rect image.Rectangle) *image.RGBA {\n\tsrc := clone.AsRGBA(img)\n\treturn clone.AsRGBA(src.SubImage(rect))\n}", "func resize(src image.Image, targetBounds image.Rectangle, targetScaleDown int, stretch bool) (\n\t*image.NRGBA64, int, int) {\n\tvar xoffset, yoffset int\n\tvar newTargetBounds image.Rectangle\n\tif stretch {\n\t\tnewTargetBounds = image.Rectangle{\n\t\t\tMax: image.Point{\n\t\t\t\tX: targetBounds.Dx() / targetScaleDown,\n\t\t\t\tY: targetBounds.Dy() / targetScaleDown,\n\t\t\t},\n\t\t}\n\t} else {\n\t\t// Check if the source image is wider than the dest, or narrower. The odd multiplication\n\t\t// avoids casting to float, at the risk of possibly overflow. Don't use images taller or\n\t\t// wider than 32K on 32 bits machines.\n\t\tif src.Bounds().Dx()*targetBounds.Dy() > targetBounds.Dx()*src.Bounds().Dy() {\n\t\t\t// source image is wider.\n\t\t\tnewTargetBounds = image.Rectangle{\n\t\t\t\tMax: image.Point{\n\t\t\t\t\tX: targetBounds.Dx() / targetScaleDown,\n\t\t\t\t\tY: src.Bounds().Dy() * targetBounds.Dx() / src.Bounds().Dx() / targetScaleDown,\n\t\t\t\t},\n\t\t\t}\n\t\t\tyoffset = (targetBounds.Dy() - newTargetBounds.Dy()*targetScaleDown) / 2\n\t\t} else {\n\t\t\t// source image is narrower.\n\t\t\tnewTargetBounds = image.Rectangle{\n\t\t\t\tMax: image.Point{\n\t\t\t\t\tX: src.Bounds().Dx() * targetBounds.Dy() / src.Bounds().Dy() / targetScaleDown,\n\t\t\t\t\tY: targetBounds.Dy() / targetScaleDown,\n\t\t\t\t},\n\t\t\t}\n\t\t\txoffset = (targetBounds.Dx() - newTargetBounds.Dx()*targetScaleDown) / 2\n\t\t}\n\t}\n\n\tdst := image.NewNRGBA64(newTargetBounds)\n\tscaler := draw.CatmullRom\n\tscaler.Scale(dst, newTargetBounds, src, src.Bounds(), draw.Over, nil)\n\treturn dst, xoffset, yoffset\n}", "func (self *PhysicsP2) SetBoundsI(args ...interface{}) {\n self.Object.Call(\"setBounds\", args)\n}", "func (img *Image) DataRange() (xmin, xmax, ymin, ymax float64) {\n\treturn img.xmin, img.xmax, img.ymin, img.ymax\n}", "func CropBorders(img image.Image) image.Image {\n\tbounds := img.Bounds()\n\tix, iy, w, h := bounds.Min.X, bounds.Min.Y, bounds.Max.X, bounds.Max.Y\n\tbackground := img.At(ix, iy)\n\tfor {\n\t\tdone := false\n\t\tfor y := iy; y < h; y++ {\n\t\t\tif !IsTransparent(img.At(ix, y)) && img.At(ix, y) != background {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\tix++\n\t\tif ix == w {\n\t\t\tbreak\n\t\t}\n\t}\n\tfor {\n\t\tdone := false\n\t\tfor x := ix; x < w; x++ {\n\t\t\tif !IsTransparent(img.At(x, iy)) && img.At(x, iy) != background {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\tiy++\n\t\tif iy == h {\n\t\t\tbreak\n\t\t}\n\t}\n\tfor {\n\t\tdone := false\n\t\tfor y := iy; y < h; y++ {\n\t\t\tif !IsTransparent(img.At(w-1, y)) && img.At(w-1, y) != background {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\tw--\n\t\tif w == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tfor {\n\t\tdone := false\n\t\tfor x := ix; x < w; x++ {\n\t\t\tif !IsTransparent(img.At(x, h-1)) && img.At(x, h-1) != background {\n\t\t\t\tdone = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif done {\n\t\t\tbreak\n\t\t}\n\t\th--\n\t\tif h == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tif ix == bounds.Min.X && iy == bounds.Min.Y && w == bounds.Max.X && h == bounds.Max.Y {\n\t\treturn img\n\t}\n\tresult := image.NewRGBA(image.Rect(0, 0, w-ix, h-iy))\n\tfor y := 0; y < h; y++ {\n\t\tfor x := 0; x < w; x++ {\n\t\t\tresult.Set(x, y, img.At(ix+x, iy+y))\n\t\t}\n\t}\n\treturn result\n}", "func dim(img image.Image) (w, h int) {\n\tw, h = img.Bounds().Max.X, img.Bounds().Max.Y\n\treturn\n}", "func (m *Matrix) InBounds(x, y int) bool {\n\treturn false\n}" ]
[ "0.81484884", "0.74995613", "0.7365385", "0.72676134", "0.7171734", "0.7087118", "0.7081115", "0.7054121", "0.70005727", "0.6923694", "0.65649325", "0.6472582", "0.63779503", "0.63676745", "0.62129", "0.6207373", "0.6186396", "0.61705816", "0.61667764", "0.6163117", "0.60668397", "0.6037902", "0.59630233", "0.5929298", "0.58742094", "0.58612347", "0.5851847", "0.58250594", "0.58249116", "0.58220774", "0.5815406", "0.5765211", "0.5745276", "0.57347137", "0.5712219", "0.57030463", "0.569013", "0.56729925", "0.56711626", "0.56690186", "0.56453145", "0.5625791", "0.5620827", "0.55842584", "0.5570588", "0.55692667", "0.5545985", "0.55305105", "0.5529811", "0.55246586", "0.55147505", "0.55097604", "0.5503847", "0.5500657", "0.54739445", "0.54649997", "0.5460297", "0.5457431", "0.5454257", "0.54249805", "0.5410351", "0.5409792", "0.5403835", "0.53914946", "0.5389766", "0.53866524", "0.53809655", "0.5376543", "0.5375102", "0.5372349", "0.5359363", "0.5352701", "0.52855515", "0.5266608", "0.52647793", "0.524188", "0.5240829", "0.5215914", "0.5213486", "0.5196571", "0.5194245", "0.5192564", "0.51817167", "0.5166279", "0.51329285", "0.51264215", "0.51203996", "0.51192576", "0.5113331", "0.50793946", "0.50791425", "0.5068882", "0.5057963", "0.50481117", "0.5029431", "0.500597", "0.50042284", "0.49908894", "0.49423242", "0.4941342" ]
0.7626049
1
At implements image.Image interface.
func (p *Magnifier) At(x, y int) color.Color { if p.Mode != Nearest { x -= p.Sx / 2 y -= p.Sy / 2 } x0 := x if x0 < 0 { x0 -= p.Sx - 1 // make division round down even for negative x0 } y0 := y if y0 < 0 { y0 -= p.Sy - 1 // make division round down even for negative y0 } x0 /= p.Sx y0 /= p.Sy if p.Mode == Nearest { return p.Image.At(x0, y0) } return magnify(p, x, y, x0, y0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *Image) At(x, y int) (color.RGBA, error) {\n\tw, h := i.image.Size()\n\tif x < 0 || y < 0 || w <= x || h <= y {\n\t\treturn color.RGBA{}, nil\n\t}\n\n\tif i.basePixels == nil || i.drawImageHistory != nil || i.stale {\n\t\tif err := graphics.FlushCommands(); err != nil {\n\t\t\treturn color.RGBA{}, err\n\t\t}\n\t\tif err := i.readPixelsFromGPU(); err != nil {\n\t\t\treturn color.RGBA{}, err\n\t\t}\n\t\ti.drawImageHistory = nil\n\t\ti.stale = false\n\t}\n\tidx := 4*x + 4*y*w\n\tr, g, b, a := i.basePixels[idx], i.basePixels[idx+1], i.basePixels[idx+2], i.basePixels[idx+3]\n\treturn color.RGBA{r, g, b, a}, nil\n}", "func (i *Image) At(x, y int) color.Color {\n\tif x+y%2 == 0 {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}", "func (i2dt *image2DTransformInt) At(x, y int) color.Color {\n\txx, yy := i2dt.m.mul(x, y)\n\treturn i2dt.src.At(xx, yy)\n}", "func (c *Image) At(x, y int) color.Color {\n\tx = x/c.Scale - c.halfScale\n\ty = y/c.Scale - c.halfScale\n\tif x < 0 || y < 0 {\n\t\treturn whiteColor\n\t}\n\tif c.Black(x, y) {\n\t\treturn blackColor\n\t}\n\treturn whiteColor\n}", "func (w *worldImg) At(x, y int) color.Color {\n\tp := w.probs[x*w.W+y]\n\tloc := w.World.At(x, y)\n\tmin, max := 0.1, 1.0\n\tf := (p/w.mx)*(max-min) + min\n\tc := colors[loc.Terrain.Char[0]]\n\treturn color.RGBA{\n\t\tR: uint8(float64(c.R) * f),\n\t\tG: uint8(float64(c.G) * f),\n\t\tB: uint8(float64(c.B) * f),\n\t\tA: c.A,\n\t}\n}", "func (t *Texture) At(x uint16, y uint16) rgb565.Rgb565Color {\n\treturn t.pixels[y*t.width+x]\n}", "func DrawImageAt(img image.Image, posx, posy int) {\n\tb := img.Bounds()\n\tfor x := b.Min.X; x < b.Max.X; x++ {\n\t\tfor y := b.Min.Y; y < b.Max.Y; y++ {\n\t\t\tfb.Set(x+posx, y+posy, img.At(x, y))\n\t\t}\n\t}\n\tfb.FullRefresh()\n}", "func (b Buffer) At(x, y int) Cell {\n\treturn b.CellMap[image.Pt(x, y)]\n}", "func (m *CvMat) At(x, y int) color.Color {\n\tcolorAtPoint := C.cvMatAt(m.ptr, C.int(x), C.int(y))\n\treturn color.Gray{uint8(colorAtPoint)}\n}", "func (c *Canvas) At(p point.Point2D) int {\n\treturn c.paint[p]\n}", "func (ki *Iterator) At() frames.Frame {\n\treturn ki.currFrame\n}", "func (l Line) imageValueAt(x, y float64) (int, int, float64) {\n\ti, k := l.imageCoordsToIndexes(x, y)\n\tif i == -1 || k == -1 {\n\t\treturn 0, 0, math.NaN()\n\t}\n\tif i < 0 || i > len(l.Image) || k < 0 || k > len(l.Image[i]) {\n\t\treturn 0, 0, math.NaN()\n\t}\n\tz := xmath.Scale(float64(l.Image[i][k]), 0.0, 255.0, l.ImageMin, l.ImageMax)\n\treturn i, k, z\n}", "func (c *Composite) At(x, y int) float32 {\n\treturn c.AtZ(x, y, 0)\n}", "func (fb FrameBuffer) ColorAt(x int, y int) color.Color {\n\tc := fb.img.At(x, y)\n\treturn c\n}", "func (this ActivityStreamsImageProperty) At(index int) vocab.ActivityStreamsImagePropertyIterator {\n\treturn this.properties[index]\n}", "func (p *RGBAf) At(x, y int) color.Color {\n\treturn p.RGBAAt(x, y)\n}", "func (p *PixelLine) At(pos int) color.Color {\n\treturn putParts(p.model, p.AtParts(pos))\n}", "func (c *Canvas) Image(x, y float64, w, h int, name string) {\n\tx, y = dimen(x, y, c.Width, c.Height)\n\tAbsImage(c.Container, int(x), int(y), w, h, name)\n}", "func (eps *EPS) At(pt image.Point) []ecs.Entity {\n\teps.reindex()\n\tk := eps.frame.Key(pt)\n\ti, m := eps.ix.searchRun(k)\n\tif m == 0 {\n\t\treturn nil\n\t}\n\tif m <= cap(eps.resEnts) {\n\t\teps.resEnts = eps.resEnts[:m]\n\t} else {\n\t\teps.resEnts = make([]ecs.Entity, m)\n\t}\n\tfor j := 0; j < m; i, j = i+1, j+1 {\n\t\txi := eps.ix.ix[i]\n\t\teps.resEnts[j] = eps.core.Ref(ecs.EntityID(xi + 1))\n\t}\n\treturn eps.resEnts\n}", "func (d *Decoder) at(i int) byte {\n\tif d.r1+i < len(d.buf) {\n\t\treturn d.buf[d.r1+i]\n\t}\n\treturn 0\n}", "func (self *GameObjectCreator) Image1O(x int, y int, key interface{}, frame interface{}) *Image{\n return &Image{self.Object.Call(\"image\", x, y, key, frame)}\n}", "func (k *Kernel) At(x, y int) float64 {\n\treturn k.Matrix[y*k.Width+x]\n}", "func (a *Animation) FrameAt(time float64) *Picture {\n\tindex := int(time / (a.Duration / float64(len(a.Frames))))\n\n\tif a.Cycle {\n\t\tindex = index % len(a.Frames)\n\t\tif index < 0 { // stupid C-style modulo\n\t\t\tindex += len(a.Frames)\n\t\t}\n\t} else {\n\t\tif index < 0 {\n\t\t\tindex = 0\n\t\t}\n\t\tif index >= len(a.Frames) {\n\t\t\tindex = len(a.Frames) - 1\n\t\t}\n\t}\n\n\treturn a.Frames[index]\n}", "func (receiver Type) At(x, y int) color.Color {\n\tconst black = 0\n\tconst white = 255\n\n\tif x < minX || maxX < x || y < minY || maxY < y {\n\t\treturn color.Gray{black}\n\t}\n\n\tresult := receiver[y] & (0x01 << byte(x))\n\n\tif 0 == result {\n\t\treturn color.Gray{black}\n\t}\n\n\treturn color.Gray{white}\n}", "func (c Color) At(idx int) float64 {\n\treturn c[idx]\n}", "func (p *PalettedBitmap) BitAt(x, y int) bool {\n\tc := p.Image.At(x, y)\n\treturn color.Model(p.Palette).Convert(c) != p.Palette[0]\n}", "func (p *SliceOfMap) At(i int) (elem *Object) {\n\telem = &Object{}\n\tif p == nil {\n\t\treturn\n\t}\n\tif i = absIndex(len(*p), i); i == -1 {\n\t\treturn\n\t}\n\telem.o = (*p)[i]\n\treturn\n}", "func (ff *fftag) at(id int) (x, y int) { return id / ff.msize, id % ff.msize }", "func (b *Board) At(p Position) byte {\n\treturn b[p.row][p.col]\n}", "func (s *Seriet) At(i int) Point {\n\treturn s.serie[i]\n}", "func (t *Dense) at(coords ...int) (at int, err error) {\n\treturn Ltoi(t.Shape(), t.Strides(), coords...)\n}", "func (v *V) At(i int) float64 {\n\tif i < 0 || i >= v.Dim() {\n\t\tpanic(ErrIndex)\n\t}\n\treturn v.Data[i]\n}", "func (gd Grid) At(p Point) Cell {\n\tq := p.Add(gd.Rg.Min)\n\tif !q.In(gd.Rg) {\n\t\treturn Cell{}\n\t}\n\ti := q.Y*gd.Ug.Width + q.X\n\treturn gd.Ug.Cells[i]\n}", "func (p Point) At(idx int) float64 {\n\treturn p[idx]\n}", "func (m *Maps) At(c types.Coordinate) io.Runeable {\n\treturn m.active[c.Y][c.X]\n}", "func (s Stream) At(index int) *Output {\n\tcurrent := s.run()\n\tif current.err != nil {\n\t\treturn &Output{reflect.ValueOf(nil), current.err}\n\t}\n\tval, err := (&at2.At{ItemsValue: current.itemsValue, Len: current.itemsLen, Index: index}).Run()\n\treturn &Output{val, err}\n}", "func (b BC5) At(x, y int) color.RGBA {\n\n\tif x < 0 || x >= b.Rect.Size().X || y < 0 || y >= b.Rect.Size().Y {\n\t\t//Out of bounds\n\t\treturn color.RGBA{}\n\t}\n\n\tblockIx := (int(float32(y)/4) * b.Rect.Size().Y) + int(float32(x)/4)*16\n\tblock := decompressBlock(b.Data[blockIx:blockIx+16], b.BlueMode)\n\treturn block.RGBAAt(x%4, y%4)\n}", "func (m IntMatrix2D) At(i, j int) (int, error) {\n\tif i >= m.nrows || j >= m.ncols {\n\t\treturn 0, fmt.Errorf(\"[%dx%d Matrix]: Invalid Location (%d,%d)\",\n\t\t\tm.nrows, m.ncols, i, j)\n\t}\n\treturn m.mat[i][j], nil\n}", "func (tt PMap) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (img *Img) GrayAt(x, y int) uint8 {\n\tc := img.i.At(x, y)\n\tr, g, b, _ := c.RGBA()\n\treturn uint8(((r + g + b) / 3) >> 8)\n}", "func GridAt(t *time.Time, depth, row, col int) (image.Image, error) {\n\t// Construct the url.\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprintf(buf, imagePath, depth, t.Format(imageFormat), row, col)\n\n\t// Get the image from the url.\n\tres, err := http.Get(buf.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\t// Create an image from the response.\n\timg, _, err := image.Decode(res.Body)\n\treturn img, err\n}", "func (A *Matrix) At(i, j int) float64 {\n\treturn A.data[i * A.stride + j]\n}", "func (s *Sprite) DrawAt(x, y int32, scale float32) {\n\tif s.tex == nil {\n\t\treturn\n\t}\n\n\tdstRect := &sdl.Rect{\n\t\tX: x,\n\t\tY: y,\n\t\tW: int32(float32(s.w) * scale),\n\t\tH: int32(float32(s.h) * scale),\n\t}\n\ts.rend.Copy(s.tex, nil, dstRect)\n}", "func (tt Slice) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func OverwriteImage(buff draw.Image, img image.Image, x, y int) {\n\tdraw.Draw(buff, buff.Bounds(),\n\t\timg, image.Point{-x, -y}, draw.Src)\n}", "func (p *IntVector) At(i int) int\t{ return p.Vector.At(i).(int) }", "func (f *YFastBilateral) At(x, y int) color.Color {\n\tr, g, b, _ := f.HDRAt(x, y).HDRRGBA()\n\treturn color.RGBA{\n\t\tR: uint8(xmath.Clamp(0, 255, int(r*255))),\n\t\tG: uint8(xmath.Clamp(0, 255, int(g*255))),\n\t\tB: uint8(xmath.Clamp(0, 255, int(b*255))),\n\t\tA: 255,\n\t}\n}", "func (fe FullEdge) At(i int) Dimensional {\n\treturn fe[i]\n}", "func (t *Tensor) ItemAt(pos ...int) *Tensor {\n\tif !t.idx.Validate(pos) {\n\t\tpanic(errorc.New(\"invalid position %v for %v\", pos, t.idx))\n\t}\n\n\treturn &Tensor{\n\t\tidx: t.idx.Scalar(pos),\n\t\tbuf: t.buf,\n\t}\n}", "func (c *Canvas) PixelAt(x, y int) (color.Color, error) {\n\terr := c.ValidateInCanvasBounds(x, y)\n\tif err != nil {\n\t\treturn *color.NewColor(0, 0, 0), err\n\t}\n\n\treturn c.Pixels[y][x], nil\n}", "func (p *Picture) RayAt(x, y int) Ray {\r\n\tdeltaX := p.camera.direction.x.Mul(float64(x) * p.pixelWidthDistance)\r\n\tdeltaY := p.camera.direction.y.Mul(float64(y) * p.pixelHeightDistance)\r\n\to := p.camera.plane.topLeft.Add(deltaX).Sub(deltaY)\r\n\tr := o.Sub(p.camera.viewPoint).Normalize()\r\n\treturn Ray{\r\n\t\tOrigin: o,\r\n\t\tDirection: r}\r\n}", "func (self *GameObjectCreator) Image(x int, y int, key interface{}) *Image{\n return &Image{self.Object.Call(\"image\", x, y, key)}\n}", "func (b *Board) At(p Position) *Piece {\n\treturn &b.Pieces[p[1]-1][p[0]-1]\n}", "func (d *Dense) At(i, j int) float64 {\n\tidx := i*d.columns + j\n\treturn d.data[idx]\n}", "func iImage(x, y, w, h int, name string) *canvas.Image {\n\tfx, fy, fw, fh := float32(x), float32(y), float32(w), float32(h)\n\ti := canvas.NewImageFromFile(name)\n\ti.Move(fyne.Position{X: fx - (fw / 2), Y: fy - (fh / 2)})\n\ti.Resize(fyne.Size{Width: fw, Height: fh})\n\treturn i\n}", "func (it *emptyIterator) At() (int64, float64) { return 0, 0 }", "func (f *finder) At(ctx context.Context, at int64, _ uint64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\tif i > 0 {\n\t\t\t\tcurrent = &index{i - 1}\n\t\t\t}\n\t\t\treturn ch, current, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\t// if index is later than the `at` target index, then return previous chunk and index\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func (p Pipeline) At(i int) OpUnion { return p.Operations[i] }", "func (tt PSlice) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (f *Face) Image(dst draw.Image, pt image.Point, ch rune) error {\n\terrno := C.FT_Load_Char(f.handle, C.FT_ULong(ch), C.FT_LOAD_RENDER)\n\tif errno != 0 {\n\t\treturn fmt.Errorf(\"freetype2: %s\", errstr(errno))\n\t}\n\tbitmap := &f.handle.glyph.bitmap\n\tif bitmap.pixel_mode != C.FT_PIXEL_MODE_GRAY || bitmap.num_grays != 256 {\n\t\treturn fmt.Errorf(\"freetype2: unsupported pixel mode\")\n\t}\n\tsrc := imageFromBitmap(bitmap)\n\tswitch dst.(type) {\n\tcase *image.Alpha:\n\t\tdrawAlpha(dst.(*image.Alpha), pt, src)\n\tdefault:\n\t\treturn fmt.Errorf(\"freetype2: unsupported dst type %T\", dst)\n\t}\n\treturn nil\n}", "func (b BitString) At(i int) int {}", "func (tt Map) At(at int) interface{} {\n\tif len(tt) > at {\n\t\treturn tt[at]\n\t}\n\treturn nil\n}", "func (r *Ray) At(t float64) Vector {\n\treturn r.Origin.Plus(r.Direction.MultiplyScalar(t))\n}", "func (t *Dense) At(coords ...int) (interface{}, error) {\n\tif len(coords) != t.Dims() {\n\t\treturn nil, errors.Errorf(dimMismatch, t.Dims(), len(coords))\n\t}\n\n\tat, err := t.at(coords...)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"At()\")\n\t}\n\n\treturn t.Get(at), nil\n}", "func (g *Graph) At(x Node, i int, j int) Node {\n\treturn g.NewOperator(fn.NewAt(x, i, j), x)\n}", "func AbsImage(cont *fyne.Container, x, y, w, h int, name string) {\n\tfx, fy, fw, fh := float32(x), float32(y), float32(w), float32(h)\n\ti := canvas.NewImageFromFile(name)\n\ti.Move(fyne.Position{X: fx - (fw / 2), Y: fy - (fh / 2)})\n\ti.Resize(fyne.Size{Width: fw, Height: fh})\n\tcont.AddObject(i)\n}", "func (a Slice[T]) At(index int) *T {\n\tlen := len(a)\n\n\tif index < 0 {\n\t\tif -index <= len {\n\t\t\treturn &a[len+index]\n\t\t}\n\t\treturn nil\n\t}\n\n\tif index < len {\n\t\treturn &a[index]\n\t}\n\n\treturn nil\n}", "func at[T interface{ ~[]E }, E any](x T, i int) E {\n\treturn x[i]\n}", "func (ns Seq) At(pos int) byte {\n\tif pos%2 == 0 {\n\t\treturn n16TableRev[ns.Seq[pos/2]>>4]\n\t}\n\treturn n16TableRev[ns.Seq[pos/2]&0xf]\n}", "func (fb *FrameBuffer) SetColorAt(x int, y int, c color.Color) {\n\tif x >= 0 && y >= 0 && x < fb.width && y < fb.height {\n\t\tfb.img.Set(x, y, c) // = c\n\t}\n}", "func (a Vector) At(p int) float64 {\n\treturn a[p]\n}", "func (r Rectangle) At(x, y int) color.Color {\n\tif (Point{x, y}).In(r) {\n\t\treturn color.Opaque\n\t}\n\treturn color.Transparent\n}", "func (cc Counter) Image(img image.Image) {\n\teachPixel(img, func(x int, y int, c color.Color) {\n\t\trgb := NewRGB(c)\n\t\tcc.Inc(rgb)\n\t})\n}", "func MethodAt(obj *IDispatch, method string) (int32, error) {\n\tvar displayID []int32\n\tdisplayID, err = obj.GetIDsOfName([]string{method})\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn displayID[0], nil\n}", "func (h heightmap) at(x, z uint8) uint8 {\n\treturn h[(uint16(x)<<4)|uint16(z)]\n}", "func (ms Float64Slice) At(i int) float64 {\n\treturn (*ms.getOrig())[i]\n}", "func (f *finder) At(ctx context.Context, at, after int64) (ch swarm.Chunk, current, next feeds.Index, err error) {\n\tfor i := uint64(0); ; i++ {\n\t\tu, err := f.getter.Get(ctx, &index{i})\n\t\tif err != nil {\n\t\t\tif !errors.Is(err, storage.ErrNotFound) {\n\t\t\t\treturn nil, nil, nil, err\n\t\t\t}\n\t\t\treturn ch, &index{i - 1}, &index{i}, nil\n\t\t}\n\t\tts, err := feeds.UpdatedAt(u)\n\t\tif err != nil {\n\t\t\treturn nil, nil, nil, err\n\t\t}\n\t\tif ts > uint64(at) {\n\t\t\treturn ch, &index{i}, nil, nil\n\t\t}\n\t\tch = u\n\t}\n}", "func (na *NArray) At(indices ...int) float32 {\n\n\tif len(indices) != na.Rank {\n\t\tfmt.Errorf(\"inconsistent number of indices for narray - [%d] vs [%d]\", len(indices), na.Rank)\n\t}\n\n\t//\treturn na.Data[na.Index(indices...)]\n\treturn na.Data[na.Index(indices...)]\n}", "func (a *file_asset) ReadAt(b []byte, off int64) (n int, err error) {\n\treturn a.f.ReadAt(b, off)\n}", "func Index() {\n\n\tfhnd, err := os.Open(\"testdata/the-wall-sample.jpg\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\timage, err := imgmeta.ReadJpeg(fhnd)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn\n\t}\n\n\tbasicInfo := GetBasicInfo(image)\n\tlog.Info(fmt.Sprintf(\"Title: %v\", basicInfo.Title))\n\tlog.Info(fmt.Sprintf(\"Image: width: %v, height: %v\", basicInfo.Width, basicInfo.Height))\n\tlog.Info(fmt.Sprintf(\"Keywords: %v\", basicInfo.Keywords))\n\n}", "func (seq *Sequence) At(i int) Node { return seq.Nodes[i] }", "func (c *camera) point_at(v Vector) {\n c.front = v.Sub(c.pos).Normalize().Add(c.pos)\n}", "func (self *Graphics) GetChildAtI(args ...interface{}) *DisplayObject{\n return &DisplayObject{self.Object.Call(\"getChildAt\", args)}\n}", "func (self *GameObjectCreator) ImageI(args ...interface{}) *Image{\n return &Image{self.Object.Call(\"image\", args)}\n}", "func (win *window) Pixel(pt image.Point) {\n\txwin.PolyPoint(xgb.CoordModeOrigin, win.id, win.gc, []xgb.Point{xgb.Point{int16(pt.X), int16(pt.Y)}})\n}", "func ImageOf(comic string) (image string) {\n\tvar date []string = strings.Split(comic, \"/\")\n\tdate = date[len(date)-3:]\n\timage = fmt.Sprintf(direct_fmt, date[0], date[0], date[1], date[2])\n\treturn\n}", "func (r ApiGetHyperflexVmSnapshotInfoListRequest) At(at string) ApiGetHyperflexVmSnapshotInfoListRequest {\n\tr.at = &at\n\treturn r\n}", "func (g *GifView) SetImage(image *gif.GIF) (*GifView, error) {\n\tg.Lock()\n\tdefer g.Unlock()\n\n\t// Store delay in milliseconds\n\tg.totalDuration = time.Duration(0)\n\tfor _, i := range image.Delay {\n\t\td := time.Duration(i*10) * time.Millisecond\n\t\tg.delay = append(g.delay, d)\n\t\tg.totalDuration += d\n\t}\n\n\t// Set height,width of the box\n\tg.SetRect(0, 0, image.Config.Width, image.Config.Height)\n\n\t// Convert images to text\n\tframes := []string{}\n\tfor i, img := range image.Image {\n\t\tparsed, err := pixelview.FromImage(img)\n\t\tif err != nil {\n\t\t\treturn g, fmt.Errorf(\"Unable to convert frame %d: %v\", i, err)\n\t\t}\n\t\tframes = append(frames, parsed)\n\t}\n\n\t// Store the output\n\tg.frames = frames\n\n\treturn g, nil\n}", "func (self *TileSprite) GetChildAtI(args ...interface{}) *DisplayObject{\n return &DisplayObject{self.Object.Call(\"getChildAt\", args)}\n}", "func (g Grid) GetValueAt(p *Point) float32 {\n\n\tif(p.X<g.Header.Lo1 || p.X>g.Header.Lo2){\n\t\treturn float32(-9999);\n\t}\n\n\tif(p.Y>g.Header.La1 || p.Y<g.Header.La2){\n\t\treturn float32(-9999);\n\t}\n\n\tidxX := int(((p.X - g.Header.Lo1) / g.Width()) * float64(g.Header.Nx-1))\n\tidxY := int(((g.Header.La1 - p.Y) / g.Height()) * float64(g.Header.Ny-1))\n\n\tul := g.GetValueAtIdx(idxX, idxY)\n\tur := g.GetValueAtIdx(idxX+1, idxY)\n\tll := g.GetValueAtIdx(idxX, idxY+1)\n\tlr := g.GetValueAtIdx(idxX+1, idxY+1)\n\n\tv:=BilinearInterpolation(&ll,&ul,&lr,&ur,p)\n\n\treturn float32(v)\n}", "func (self *Rectangle) OffsetPointI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"offsetPoint\", args)}\n}", "func (self *Rectangle) OffsetI(args ...interface{}) *Rectangle{\n return &Rectangle{self.Object.Call(\"offset\", args)}\n}", "func (nl *nodeList) at(i int) *Node {\n\tif i > len(nl.elements) - 1 || i < 0 {\n\t\treturn nil\n\t}\n\n\treturn nl.elements[i]\n}", "func (a *file_asset) WriteAt(b []byte, off int64) (n int, err error) {\n\t// TODO: WriteAt cannot ID with MultiWriter\n\treturn a.f.WriteAt(b, off)\n}", "func DrawImage(img image.Image) {\n\tDrawImageAt(img, 0, 0)\n}", "func avgInterpolateAt(src image.Image, x, y, kw, kh int) color.Color {\n\tymin := max(y-kh/2, src.Bounds().Min.Y)\n\tymax := min(y+kh/2+1, src.Bounds().Max.Y)\n\txmin := max(x-kw/2, src.Bounds().Min.X)\n\txmax := min(x+kw/2+1, src.Bounds().Max.X)\n\n\treturn averager(src, image.Rect(xmin, ymin, xmax, ymax))\n}", "func (bio *BinaryIO) WriteAt(off int64, buf []byte) {\n\t_, err := bio.base.WriteAt(buf, off)\n\texc.ThrowOnError(err)\n}", "func (p *Alpha16) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2\n}", "func (w *LDRWrapper) HDRAt(x, y int) hdrcolor.Color {\n\tr, g, b, _ := w.At(x, y).RGBA()\n\treturn hdrcolor.RGB{R: float64(r) / 0xFFFF, G: float64(g) / 0xFFFF, B: float64(b) / 0xFFFF}\n}", "func (dw *DrawingWand) Annotation(x, y float64, text string) {\n\tcstext := (*C.uchar)((unsafe.Pointer)(C.CString(text)))\n\tdefer C.free(unsafe.Pointer(cstext))\n\tC.MagickDrawAnnotation(dw.dw, C.double(x), C.double(y), cstext)\n}" ]
[ "0.7447265", "0.7107189", "0.6874271", "0.6664863", "0.642484", "0.6338206", "0.6305397", "0.629791", "0.6208162", "0.6173454", "0.60526973", "0.6033094", "0.5956543", "0.59556687", "0.5929034", "0.5887311", "0.5842724", "0.58209306", "0.57103056", "0.570447", "0.5704004", "0.56954867", "0.5659506", "0.56540996", "0.5608953", "0.55990636", "0.5587291", "0.5554836", "0.5542164", "0.5512339", "0.55044293", "0.5503163", "0.54897565", "0.5469342", "0.54375076", "0.5437501", "0.54318726", "0.54278076", "0.5400841", "0.53999454", "0.5399773", "0.5391993", "0.5359942", "0.5359555", "0.5337155", "0.5322597", "0.5299196", "0.5277639", "0.5257722", "0.52404106", "0.5237166", "0.52275", "0.52250427", "0.521944", "0.5190473", "0.51843894", "0.51600504", "0.5148148", "0.5140524", "0.51368964", "0.5125489", "0.5117144", "0.51084924", "0.51030076", "0.51010627", "0.50884867", "0.50743484", "0.5071294", "0.5058166", "0.5047592", "0.5028616", "0.50253934", "0.50193065", "0.49998152", "0.49868548", "0.49799645", "0.4969967", "0.49548855", "0.4934578", "0.49074763", "0.49035108", "0.48963854", "0.48945698", "0.48945504", "0.48936212", "0.48911294", "0.48892936", "0.48876658", "0.48787928", "0.48717904", "0.487132", "0.48675516", "0.48649028", "0.48599344", "0.48091373", "0.4789368", "0.47844028", "0.47815767", "0.4779395", "0.477873" ]
0.65637755
4
RGBA64At implements image.RGBA64Image interface.
func (p *Magnifier) RGBA64At(x, y int) color.RGBA64 { if p.Mode != Nearest { x -= p.Sx / 2 y -= p.Sy / 2 } x0 := x if x0 < 0 { x0 -= p.Sx - 1 // make division round down even for negative x0 } y0 := y if y0 < 0 { y0 -= p.Sy - 1 // make division round down even for negative y0 } x0 /= p.Sx y0 /= p.Sy if p.Mode == Nearest { if img, ok := p.Image.(image.RGBA64Image); ok { return img.RGBA64At(x0, y0) } r, g, b, a := p.Image.At(x0, y0).RGBA() return color.RGBA64{uint16(r), uint16(g), uint16(b), uint16(a)} } return magnify(p, x, y, x0, y0) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (i *Image) At(x, y int) (color.RGBA, error) {\n\tw, h := i.image.Size()\n\tif x < 0 || y < 0 || w <= x || h <= y {\n\t\treturn color.RGBA{}, nil\n\t}\n\n\tif i.basePixels == nil || i.drawImageHistory != nil || i.stale {\n\t\tif err := graphics.FlushCommands(); err != nil {\n\t\t\treturn color.RGBA{}, err\n\t\t}\n\t\tif err := i.readPixelsFromGPU(); err != nil {\n\t\t\treturn color.RGBA{}, err\n\t\t}\n\t\ti.drawImageHistory = nil\n\t\ti.stale = false\n\t}\n\tidx := 4*x + 4*y*w\n\tr, g, b, a := i.basePixels[idx], i.basePixels[idx+1], i.basePixels[idx+2], i.basePixels[idx+3]\n\treturn color.RGBA{r, g, b, a}, nil\n}", "func NewRGBA64(r Rectangle) *RGBA64 {\n\treturn &RGBA64{\n\t\tPix: make([]uint8, pixelBufferLength(8, r, \"RGBA64\")),\n\t\tStride: 8 * r.Dx(),\n\t\tRect: r,\n\t}\n}", "func NewRGBA64(w, h int) *RGBA64 {\n\tpixel := make([][]RGBA64Color, h);\n\tfor y := 0; y < int(h); y++ {\n\t\tpixel[y] = make([]RGBA64Color, w)\n\t}\n\treturn &RGBA64{pixel};\n}", "func (p *RGBAf) At(x, y int) color.Color {\n\treturn p.RGBAAt(x, y)\n}", "func NewNRGBA64(r Rectangle) *NRGBA64 {\n\treturn &NRGBA64{\n\t\tPix: make([]uint8, pixelBufferLength(8, r, \"NRGBA64\")),\n\t\tStride: 8 * r.Dx(),\n\t\tRect: r,\n\t}\n}", "func (p *RGBAf) RGBAAt(x, y int) RGBAFC {\n\tif !(image.Point{x, y}.In(p.Rect)) {\n\t\treturn RGBAFC{}\n\t}\n\ti := p.PixOffset(x, y)\n\ts := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857\n\treturn RGBAFC{s[0], s[1], s[2], s[3]}\n}", "func rgba64ToGray(dst *image.Gray, src *image.RGBA64) {\n\tconcurrentIterate(src.Rect.Dy(), func(y int) {\n\t\tfor x := 0; x < dst.Stride; x++ {\n\t\t\ti := y*src.Stride + x*8\n\t\t\ts := src.Pix[i : i+6 : i+6]\n\t\t\tvar (\n\t\t\t\tr = uint32(s[0])<<8 | uint32(s[1])\n\t\t\t\tg = uint32(s[2])<<8 | uint32(s[3])\n\t\t\t\tb = uint32(s[4])<<8 | uint32(s[5])\n\t\t\t)\n\t\t\tdst.Pix[y*dst.Stride+x] = rgbToGray(r, g, b)\n\t\t}\n\t})\n}", "func NewNRGBA64(w, h int) *NRGBA64 {\n\tpixel := make([][]NRGBA64Color, h);\n\tfor y := 0; y < int(h); y++ {\n\t\tpixel[y] = make([]NRGBA64Color, w)\n\t}\n\treturn &NRGBA64{pixel};\n}", "func nrgba64ToGray(dst *image.Gray, src *image.NRGBA64) {\n\tconcurrentIterate(src.Rect.Dy(), func(y int) {\n\t\tfor x := 0; x < dst.Stride; x++ {\n\t\t\ti := y*src.Stride + x*8\n\t\t\ts := src.Pix[i : i+8 : i+8]\n\t\t\tvar (\n\t\t\t\tr = uint32(s[0])<<8 | uint32(s[1])\n\t\t\t\tg = uint32(s[2])<<8 | uint32(s[3])\n\t\t\t\tb = uint32(s[4])<<8 | uint32(s[5])\n\t\t\t\ta = uint32(s[6])<<8 | uint32(s[7])\n\t\t\t)\n\t\t\tr = r * a / 0xffff\n\t\t\tg = g * a / 0xffff\n\t\t\tb = b * a / 0xffff\n\t\t\tdst.Pix[y*dst.Stride+x] = rgbToGray(r, g, b)\n\t\t}\n\t})\n}", "func (l Line) imageValueAt(x, y float64) (int, int, float64) {\n\ti, k := l.imageCoordsToIndexes(x, y)\n\tif i == -1 || k == -1 {\n\t\treturn 0, 0, math.NaN()\n\t}\n\tif i < 0 || i > len(l.Image) || k < 0 || k > len(l.Image[i]) {\n\t\treturn 0, 0, math.NaN()\n\t}\n\tz := xmath.Scale(float64(l.Image[i][k]), 0.0, 255.0, l.ImageMin, l.ImageMax)\n\treturn i, k, z\n}", "func ToImage64(i image.Image) *Image64 {\n\tbounds := i.Bounds()\n\tresult := NewImage64(bounds)\n\tswitch i.(type) {\n\t// case Image64:\n\t// TODO copy parts of underlying slice\n\tdefault:\n\t\tdraw.Draw(result, result.Rect, i, bounds.Min, draw.Src)\n\t}\n\treturn result\n}", "func (t *Texture) At(x uint16, y uint16) rgb565.Rgb565Color {\n\treturn t.pixels[y*t.width+x]\n}", "func (img *Img) GrayAt(x, y int) uint8 {\n\tc := img.i.At(x, y)\n\tr, g, b, _ := c.RGBA()\n\treturn uint8(((r + g + b) / 3) >> 8)\n}", "func (w *worldImg) At(x, y int) color.Color {\n\tp := w.probs[x*w.W+y]\n\tloc := w.World.At(x, y)\n\tmin, max := 0.1, 1.0\n\tf := (p/w.mx)*(max-min) + min\n\tc := colors[loc.Terrain.Char[0]]\n\treturn color.RGBA{\n\t\tR: uint8(float64(c.R) * f),\n\t\tG: uint8(float64(c.G) * f),\n\t\tB: uint8(float64(c.B) * f),\n\t\tA: c.A,\n\t}\n}", "func (p *Magnifier) At(x, y int) color.Color {\n\tif p.Mode != Nearest {\n\t\tx -= p.Sx / 2\n\t\ty -= p.Sy / 2\n\t}\n\tx0 := x\n\tif x0 < 0 {\n\t\tx0 -= p.Sx - 1 // make division round down even for negative x0\n\t}\n\ty0 := y\n\tif y0 < 0 {\n\t\ty0 -= p.Sy - 1 // make division round down even for negative y0\n\t}\n\tx0 /= p.Sx\n\ty0 /= p.Sy\n\tif p.Mode == Nearest {\n\t\treturn p.Image.At(x0, y0)\n\t}\n\treturn magnify(p, x, y, x0, y0)\n}", "func (p *RGBA64) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8\n}", "func toRGBA(i image.Image) *image.RGBA {\n\tbounds := i.Bounds()\n\tni := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))\n\tdraw.Draw(ni, ni.Bounds(), i, bounds.Min, draw.Src)\n\treturn ni\n}", "func toNRGBA(i image.Image) *image.NRGBA {\n srcBounds := i.Bounds()\n if srcBounds.Min.X == 0 && srcBounds.Min.Y == 0 {\n if src0, ok := i.(*image.NRGBA); ok {\n return src0\n }\n }\n return Clone(i)\n}", "func (c Color) At(idx int) float64 {\n\treturn c[idx]\n}", "func (p *NRGBA64) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*8\n}", "func (i *Image) At(x, y int) color.Color {\n\tif x+y%2 == 0 {\n\t\treturn color.Black\n\t}\n\treturn color.White\n}", "func NewImage64(r image.Rectangle) *Image64 {\n\twidth, height := r.Dx(), r.Dy()\n\treturn &Image64{\n\t\tPix: make([]Color64, width*height),\n\t\tStride: width,\n\t\tRect: image.Rectangle{image.ZP, image.Point{width, height}},\n\t}\n}", "func (image *Image2D) GetRGBA(x, y int) (uint8, uint8, uint8, uint8) {\n\tidx := image.getIdx(x, y)\n\treturn image.data[idx],\n\t\timage.data[idx+1],\n\t\timage.data[idx+2],\n\t\timage.data[idx+3]\n}", "func (f *YFastBilateral) At(x, y int) color.Color {\n\tr, g, b, _ := f.HDRAt(x, y).HDRRGBA()\n\treturn color.RGBA{\n\t\tR: uint8(xmath.Clamp(0, 255, int(r*255))),\n\t\tG: uint8(xmath.Clamp(0, 255, int(g*255))),\n\t\tB: uint8(xmath.Clamp(0, 255, int(b*255))),\n\t\tA: 255,\n\t}\n}", "func PngGetColorAt(filename string, x int, y int) color.RGBA {\n\n\tfile, err := os.Open(filename)\n\n\tif err != nil {\n\t\tfmt.Println(\"Error: File could not be opened.\")\n\t\tos.Exit(1)\n\t}\n\tdefer file.Close()\n\n\timg, _, err := image.Decode(file)\n\n\tr, g, b, a := img.At(x, y).RGBA()\n\ttopleftColor := Pixel{uint8(r / 257), uint8(g / 257), uint8(b / 257), uint8(a / 257)}\n\n\treturn color.RGBA{topleftColor.R, topleftColor.G, topleftColor.B, topleftColor.A}\n\n}", "func (i2dt *image2DTransformInt) At(x, y int) color.Color {\n\txx, yy := i2dt.m.mul(x, y)\n\treturn i2dt.src.At(xx, yy)\n}", "func (c NGrayA64) RGBA() (uint32, uint32, uint32, uint32) {\n\ty := fromFloat(float64(c.Y), 1.0/2.2)\n\tswitch {\n\tcase c.A >= 1:\n\t\treturn y, y, y, 0xffff\n\tcase c.A <= 0:\n\t\treturn 0, 0, 0, 0\n\t}\n\ta := uint32(c.A * 0xffff)\n\ty = y * a / 0xffff\n\treturn y, y, y, a\n}", "func linearImage(srcim image.Image, gamma float64) *image.NRGBA64 {\n\tdstim := image.NewNRGBA64(image.Rectangle{\n\t\tMax: image.Point{\n\t\t\tX: srcim.Bounds().Dx(),\n\t\t\tY: srcim.Bounds().Dy(),\n\t\t},\n\t})\n\tvar dsty int\n\tfor srcy := srcim.Bounds().Min.Y; srcy < srcim.Bounds().Max.Y; srcy++ {\n\t\tvar dstx int\n\t\tfor srcx := srcim.Bounds().Min.X; srcx < srcim.Bounds().Max.X; srcx++ {\n\t\t\tnrgba64 := color.NRGBA64Model.Convert(srcim.At(srcx, srcy)).(color.NRGBA64)\n\t\t\tnrgba64.R = uint16(nrgba64Max * math.Pow(float64(nrgba64.R)/nrgba64Max, gamma))\n\t\t\tnrgba64.G = uint16(nrgba64Max * math.Pow(float64(nrgba64.G)/nrgba64Max, gamma))\n\t\t\tnrgba64.B = uint16(nrgba64Max * math.Pow(float64(nrgba64.B)/nrgba64Max, gamma))\n\t\t\t// Alpha is not affected\n\t\t\tdstim.SetNRGBA64(dstx, dsty, nrgba64)\n\t\t\tdstx++\n\t\t}\n\t\tdsty++\n\t}\n\treturn dstim\n}", "func (b BC5) At(x, y int) color.RGBA {\n\n\tif x < 0 || x >= b.Rect.Size().X || y < 0 || y >= b.Rect.Size().Y {\n\t\t//Out of bounds\n\t\treturn color.RGBA{}\n\t}\n\n\tblockIx := (int(float32(y)/4) * b.Rect.Size().Y) + int(float32(x)/4)*16\n\tblock := decompressBlock(b.Data[blockIx:blockIx+16], b.BlueMode)\n\treturn block.RGBAAt(x%4, y%4)\n}", "func (c *Image) At(x, y int) color.Color {\n\tx = x/c.Scale - c.halfScale\n\ty = y/c.Scale - c.halfScale\n\tif x < 0 || y < 0 {\n\t\treturn whiteColor\n\t}\n\tif c.Black(x, y) {\n\t\treturn blackColor\n\t}\n\treturn whiteColor\n}", "func (b Buffer) At(x, y int) Cell {\n\treturn b.CellMap[image.Pt(x, y)]\n}", "func (fb FrameBuffer) ColorAt(x int, y int) color.Color {\n\tc := fb.img.At(x, y)\n\treturn c\n}", "func (image *Image2D) SetRGBA(x, y int, r, g, b, a uint8) {\n\tidx := image.getIdx(x, y)\n\timage.data[idx] = r\n\timage.data[idx+1] = g\n\timage.data[idx+2] = b\n\timage.data[idx+3] = a\n}", "func (c *Canvas) PixelAt(x, y int) (color.Color, error) {\n\terr := c.ValidateInCanvasBounds(x, y)\n\tif err != nil {\n\t\treturn *color.NewColor(0, 0, 0), err\n\t}\n\n\treturn c.Pixels[y][x], nil\n}", "func (p *NRGBA64) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &NRGBA64{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &NRGBA64{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func (p *RGBA64) SubImage(r Rectangle) Image {\n\tr = r.Intersect(p.Rect)\n\t// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside\n\t// either r1 or r2 if the intersection is empty. Without explicitly checking for\n\t// this, the Pix[i:] expression below can panic.\n\tif r.Empty() {\n\t\treturn &RGBA64{}\n\t}\n\ti := p.PixOffset(r.Min.X, r.Min.Y)\n\treturn &RGBA64{\n\t\tPix: p.Pix[i:],\n\t\tStride: p.Stride,\n\t\tRect: r,\n\t}\n}", "func NormalizeRGBA64(v [4]float32) [4]uint16 {\n\treturn [4]uint16{\n\t\tuint16(deliniarize(v[0]) * 65535),\n\t\tuint16(deliniarize(v[1]) * 65535),\n\t\tuint16(deliniarize(v[2]) * 65535),\n\t\tuint16(v[3] * 65535),\n\t}\n}", "func decodeRGBA(r io.Reader, c image.Config) (image.Image, error) {\n\trgba := image.NewRGBA(image.Rect(0, 0, c.Width, c.Height))\n\t// There are 3 bytes per pixel, and each row is 4-byte aligned.\n\tb := make([]byte, (3*c.Width+3)&^3)\n\t// BMP images are stored bottom-up rather than top-down.\n\tfor y := c.Height - 1; y >= 0; y-- {\n\t\t_, err := io.ReadFull(r, b)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tp := rgba.Pix[y*rgba.Stride : y*rgba.Stride+c.Width*4]\n\t\tfor i, j := 0, 0; i < len(p); i, j = i+4, j+3 {\n\t\t\t// BMP images are stored in BGR order rather than RGB order.\n\t\t\tp[i+0] = b[j+2]\n\t\t\tp[i+1] = b[j+1]\n\t\t\tp[i+2] = b[j+0]\n\t\t\tp[i+3] = 0xFF\n\t\t}\n\t}\n\treturn rgba, nil\n}", "func (ms Float64Slice) At(i int) float64 {\n\treturn (*ms.getOrig())[i]\n}", "func opUI64Bitor(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := ReadUI64(fp, expr.Inputs[0]) | ReadUI64(fp, expr.Inputs[1])\n\tWriteUI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func (receiver Type) At(x, y int) color.Color {\n\tconst black = 0\n\tconst white = 255\n\n\tif x < minX || maxX < x || y < minY || maxY < y {\n\t\treturn color.Gray{black}\n\t}\n\n\tresult := receiver[y] & (0x01 << byte(x))\n\n\tif 0 == result {\n\t\treturn color.Gray{black}\n\t}\n\n\treturn color.Gray{white}\n}", "func (p *Alpha16) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2\n}", "func imageToRGBA(src image.Image) *image.RGBA {\n\tb := src.Bounds()\n\n\tvar m *image.RGBA\n\tvar width, height int\n\n\twidth = b.Dx()\n\theight = b.Dy()\n\n\tm = image.NewRGBA(image.Rect(0, 0, width, height))\n\tdraw.Draw(m, m.Bounds(), src, b.Min, draw.Src)\n\treturn m\n}", "func Uint64Tag(name interface{}, value uint64) Tag {\n\treturn &tag{\n\t\ttagType: TagUint64,\n\t\tname: name,\n\t\tvalue: value,\n\t}\n}", "func convertToRGBA(src image.Image) *image.RGBA {\n\tb := src.Bounds()\n\tm := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))\n\tdraw.Draw(m, m.Bounds(), src, b.Min, draw.Src)\n\treturn m\n}", "func (b *Bitmap) NRGBA() (*image.NRGBA, error) {\n\tif b.PixelMode() == PixelModeBGRA {\n\t\trows := b.Rows()\n\t\twidth := b.Width()\n\t\tpitch := b.Pitch()\n\t\tsize := rows * width\n\t\theader := reflect.SliceHeader{\n\t\t\tData: uintptr(unsafe.Pointer(b.handle.buffer)),\n\t\t\tLen: size,\n\t\t\tCap: size,\n\t\t}\n\t\tpix := *(*[]byte)(unsafe.Pointer(&header))\n\t\timg := image.NewNRGBA(image.Rect(0, 0, width, rows))\n\n\t\tvar i int\n\t\tpitchX := 4\n\t\tif b.Pitch() < 0 {\n\t\t\ti = size\n\t\t\tpitchX = -4\n\t\t}\n\t\tfor y := 0; y < rows; y++ {\n\t\t\tfor x := 0; x < width; x++ {\n\t\t\t\timg.Set(x, y, color.NRGBA{pix[i+2], pix[i+1], pix[i], pix[i+3]})\n\t\t\t\ti += pitchX\n\t\t\t}\n\t\t\ti += pitch\n\t\t}\n\t\treturn img, nil\n\t}\n\treturn nil, ErrUnsupportedPixelMode\n}", "func DenormalizeRGBA64(v [4]uint16) [4]float32 {\n\treturn [4]float32{\n\t\tlinearize(float32(v[0]) / 65535),\n\t\tlinearize(float32(v[1]) / 65535),\n\t\tlinearize(float32(v[2]) / 65535),\n\t\tfloat32(v[3]) / 65535,\n\t}\n}", "func (A *Matrix) At(i, j int) float64 {\n\treturn A.data[i * A.stride + j]\n}", "func readImage(path string) ([]uint8, int, int){\n reader, err := os.Open(path)\n if err != nil {\n log.Fatal(err)\n }\n defer reader.Close()\n m, err := png.Decode(reader)\n if err != nil {\n log.Fatal(err)\n }\n bounds := m.Bounds()\n var w = bounds.Max.X - bounds.Min.X;\n var h = bounds.Max.Y - bounds.Min.Y;\n var im = make([]uint8, w*h)\n for y := bounds.Min.Y; y < bounds.Max.Y; y++ {\n for x := bounds.Min.X; x < bounds.Max.X; x++ {\n r, _, _, _ := m.At(x, y).RGBA()\n if r >= 32768 {\n im[w*y+x] = 1\n }else{\n im[w*y+x] = 0\n }\n }\n }\n return im,w,h\n}", "func I64P(i int64) *int64 { return &i }", "func (rng *Rng) Uint64() uint64 {\n\trng.State += 0x9E3779B97F4A7C15\n\tz := rng.State\n\tz = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9\n\tz = (z ^ (z >> 27)) * 0x94D049BB133111EB\n\treturn z ^ (z >> 31)\n}", "func imageToRGBA(dst *image.RGBA, src image.Image) {\n\tif dst == nil {\n\t\tpanic(\"dst can't be nil\")\n\t}\n\n\tif srcRGBA, ok := src.(*image.RGBA); ok {\n\t\t*dst = *srcRGBA\n\t\treturn\n\t}\n\n\tbounds := src.Bounds()\n\tdy := bounds.Dy()\n\tdx := bounds.Dx()\n\n\tif len(dst.Pix) < 4*dx*dy {\n\t\tdst.Pix = make([]uint8, 4*dx*dy)\n\t}\n\tdst.Stride = 4 * dx\n\tdst.Rect = bounds\n\n\tif hasCGOConvert {\n\t\tif srcYCbCr, ok := src.(*image.YCbCr); ok &&\n\t\t\tsrcYCbCr.SubsampleRatio == image.YCbCrSubsampleRatio444 {\n\t\t\t// Use CGO version\n\t\t\ti444ToRGBACGO(dst, srcYCbCr)\n\t\t\treturn\n\t\t}\n\t}\n\n\ti := 0\n\tfor yi := 0; yi < dy; yi++ {\n\t\tfor xi := 0; xi < dx; xi++ {\n\t\t\tr, g, b, a := src.At(xi, yi).RGBA()\n\t\t\tdst.Pix[i+0] = uint8(r / 0x100)\n\t\t\tdst.Pix[i+1] = uint8(g / 0x100)\n\t\t\tdst.Pix[i+2] = uint8(b / 0x100)\n\t\t\tdst.Pix[i+3] = uint8(a / 0x100)\n\t\t\ti += 4\n\t\t}\n\t}\n}", "func (k *Kernel) At(x, y int) float64 {\n\treturn k.Matrix[y*k.Width+x]\n}", "func (rng *splitMix64Source) Uint64() uint64 {\n\trng.state += 0x9E3779B97F4A7C15\n\tz := rng.state\n\tz = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9\n\tz = (z ^ (z >> 27)) * 0x94D049BB133111EB\n\treturn z ^ (z >> 31)\n}", "func (d *Decoder) at(i int) byte {\n\tif d.r1+i < len(d.buf) {\n\t\treturn d.buf[d.r1+i]\n\t}\n\treturn 0\n}", "func opUI64ToI64(prgrm *CXProgram) {\n\texpr := prgrm.GetExpr()\n\tfp := prgrm.GetFramePointer()\n\n\toutV0 := int64(ReadUI64(fp, expr.Inputs[0]))\n\tWriteI64(GetFinalOffset(fp, expr.Outputs[0]), outV0)\n}", "func Uint64(input []byte, startBitPos int) (result uint64, resultPtr *uint64, err error) {\n\tif Len(input)-startBitPos < 64 {\n\t\treturn 0, nil, errors.New(\"Input is less than 64 bits\")\n\t}\n\n\ttmpArr, _, err := SubBits(input, startBitPos, 64)\n\tresult = binary.BigEndian.Uint64(tmpArr)\n\n\treturn result, &result, err\n}", "func (i *DeserializerV1) ReadFloat64At(p []byte, begin int) (float64, int, error) {\n\tvar ans uint64\n\tvar idx = begin\n\n\t// b64 b56 b48 b40 b32 b24 b16 b8\n\tans = uint64(p[idx])<<56 + uint64(p[idx+1])<<48 + uint64(p[idx+2])<<40 + uint64(p[idx+3])<<32 + uint64(p[idx+4])<<24 + uint64(p[idx+5])<<16 + uint64(p[idx+6])<<8 + uint64(p[idx+7])\n\n\treturn math.Float64frombits(ans), idx + 7, nil\n}", "func (p *RGBAf) SetRGBA(x, y int, c RGBAFC) {\n\tif !(image.Point{x, y}.In(p.Rect)) {\n\t\treturn\n\t}\n\ti := p.PixOffset(x, y)\n\ts := p.Pix[i : i+4 : i+4] // Small cap improves performance, see https://golang.org/issue/27857\n\ts[0] = float32(c.R)\n\ts[1] = float32(c.G)\n\ts[2] = float32(c.B)\n\ts[3] = float32(c.A)\n}", "func (v *Value) SetUInt64(val uint64) {\n\tC.g_value_set_uint64(v.Native(), C.guint64(val))\n}", "func NewInt64MessageAt(data int64, at int64, withPrecision common.TimePrecision) msgs.Message {\n\tvar msg Int64\n\tmsg.Header = common.NewHeaderAt(at, withPrecision)\n\tmsg.Body.Data = data\n\treturn &msg\n}", "func (d *Dense) At(i, j int) float64 {\n\tidx := i*d.columns + j\n\treturn d.data[idx]\n}", "func getPixVal(c color.Color) float64 {\n\tr, _, _, _ := c.RGBA()\n\treturn float64(r >> 8)\n}", "func (p Point) At(idx int) float64 {\n\treturn p[idx]\n}", "func (p *Gray16) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x - p.Rect.Min.X)\n}", "func (p *Gray16) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*2\n}", "func (cb *codedBuffer) decodeFixed64() (x uint64, err error) {\n\t// x, err already 0\n\ti := cb.index + 8\n\tif i < 0 || i > len(cb.buf) {\n\t\terr = io.ErrUnexpectedEOF\n\t\treturn\n\t}\n\tcb.index = i\n\n\tx = uint64(cb.buf[i-8])\n\tx |= uint64(cb.buf[i-7]) << 8\n\tx |= uint64(cb.buf[i-6]) << 16\n\tx |= uint64(cb.buf[i-5]) << 24\n\tx |= uint64(cb.buf[i-4]) << 32\n\tx |= uint64(cb.buf[i-3]) << 40\n\tx |= uint64(cb.buf[i-2]) << 48\n\tx |= uint64(cb.buf[i-1]) << 56\n\treturn\n}", "func (p *NRGBA) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4\n}", "func (ff *fftag) at(id int) (x, y int) { return id / ff.msize, id % ff.msize }", "func opI64Bitor(expr *CXExpression, fp int) {\n\toutB0 := ReadI64(fp, expr.Inputs[0]) | ReadI64(fp, expr.Inputs[1])\n\tWriteI64(GetOffset_i64(fp, expr.Outputs[0]), outB0)\n}", "func (t *Tensor) ItemAt(pos ...int) *Tensor {\n\tif !t.idx.Validate(pos) {\n\t\tpanic(errorc.New(\"invalid position %v for %v\", pos, t.idx))\n\t}\n\n\treturn &Tensor{\n\t\tidx: t.idx.Scalar(pos),\n\t\tbuf: t.buf,\n\t}\n}", "func (p *Gray16) PixOffset(x, y int) int {\n\treturn (y-p.M.Rect.Min.Y)*p.M.Stride + (x-p.M.Rect.Min.X)*2\n}", "func WriteMemI64(mem []byte, offset int, v int64) {\n\tmem[offset] = byte(v)\n\tmem[offset+1] = byte(v >> 8)\n\tmem[offset+2] = byte(v >> 16)\n\tmem[offset+3] = byte(v >> 24)\n\tmem[offset+4] = byte(v >> 32)\n\tmem[offset+5] = byte(v >> 40)\n\tmem[offset+6] = byte(v >> 48)\n\tmem[offset+7] = byte(v >> 56)\n}", "func (p *RGBAf) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4\n}", "func (p *Alpha) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1\n}", "func (z *Rat) SetUint64(x uint64) *Rat {}", "func (i *DeserializerV1) ReadInt64At(p []byte, begin int) (int64, int, error) {\n\tvar ans int64\n\tvar idx = begin\n\n\t// b64 b56 b48 b40 b32 b24 b16 b8\n\tans = int64(p[idx])<<56 + int64(p[idx+1])<<48 + int64(p[idx+2])<<40 + int64(p[idx+3])<<32 + int64(p[idx+4])<<24 + int64(p[idx+5])<<16 + int64(p[idx+6])<<8 + int64(p[idx+7])\n\n\treturn ans, idx + 7, nil\n}", "func NewRGBA(r Rectangle) *RGBA {\n\treturn &RGBA{\n\t\tPix: make([]uint8, pixelBufferLength(4, r, \"RGBA\")),\n\t\tStride: 4 * r.Dx(),\n\t\tRect: r,\n\t}\n}", "func Uint64(key string, val uint64) Tag {\n\treturn Tag{key: key, tType: uint64Type, integerVal: int64(val)}\n}", "func DrawNewton64(numRealValues, numImagValues int, start, end complex64) *image.RGBA {\n\trealStepValue := (real(end) - real(start)) / float32(numRealValues)\n\timagStepValue := (imag(end) - imag(start)) / float32(numImagValues)\n\n\timg := image.NewRGBA(image.Rect(0, 0, numRealValues, numImagValues))\n\n\tfor x := 0; x < numRealValues; x++ {\n\t\trc := real(start) + realStepValue*float32(x)\n\t\tfor y := 0; y < numImagValues; y++ {\n\t\t\tic := imag(start) + imagStepValue*float32(y)\n\t\t\tcolor := getColor64(complex(rc, ic))\n\t\t\timg.Set(x, y, color)\n\t\t}\n\t}\n\treturn img\n}", "func (c Context) Uint64(key string, i uint64) Context {\n\tc.l.context = appendUint64(c.l.context, key, i)\n\treturn c\n}", "func imgReadAsy(camera int, width int, height int, timeout int) (int, []byte) {\n\tlog.Printf(\"imgReadAsy camera:%d width:%d height:%d timeout:%d\", camera, width, height, timeout)\n\n\tvar buffer = make([]byte, width*height, width*height)\n\tvar f = mod.NewProc(\"img_readAsy\")\n\tret, _, _ := f.Call(uintptr(camera), uintptr(unsafe.Pointer(&buffer[0])), uintptr(width*height), uintptr(timeout))\n\n\timg := image.NewGray(image.Rect(0, 0, width, height))\n\timg.Pix = buffer\n\tvar pngBuffer = new(bytes.Buffer)\n\n\terrEncode := png.Encode(pngBuffer, img)\n\tif nil != errEncode {\n\t\tlog.Printf(\"Error encoding PNG : %v\\n\", errEncode)\n\t}\n\n\treturn int(ret), pngBuffer.Bytes()\n}", "func InsertUint64(slice []uint64, element, position uint64) []uint64 {\n\treturn append(slice[:position], append([]uint64{element}, slice[position:]...)...)\n}", "func (p *RGBA) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*4\n}", "func (c *Config) GetUint64(pattern string, def ...interface{}) uint64 {\n\tif j := c.getJson(); j != nil {\n\t\treturn j.GetUint64(pattern, def...)\n\t}\n\treturn 0\n}", "func (g Grid) GetValueAt(p *Point) float32 {\n\n\tif(p.X<g.Header.Lo1 || p.X>g.Header.Lo2){\n\t\treturn float32(-9999);\n\t}\n\n\tif(p.Y>g.Header.La1 || p.Y<g.Header.La2){\n\t\treturn float32(-9999);\n\t}\n\n\tidxX := int(((p.X - g.Header.Lo1) / g.Width()) * float64(g.Header.Nx-1))\n\tidxY := int(((g.Header.La1 - p.Y) / g.Height()) * float64(g.Header.Ny-1))\n\n\tul := g.GetValueAtIdx(idxX, idxY)\n\tur := g.GetValueAtIdx(idxX+1, idxY)\n\tll := g.GetValueAtIdx(idxX, idxY+1)\n\tlr := g.GetValueAtIdx(idxX+1, idxY+1)\n\n\tv:=BilinearInterpolation(&ll,&ul,&lr,&ur,p)\n\n\treturn float32(v)\n}", "func GridAt(t *time.Time, depth, row, col int) (image.Image, error) {\n\t// Construct the url.\n\tbuf := new(bytes.Buffer)\n\tfmt.Fprintf(buf, imagePath, depth, t.Format(imageFormat), row, col)\n\n\t// Get the image from the url.\n\tres, err := http.Get(buf.String())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer res.Body.Close()\n\n\t// Create an image from the response.\n\timg, _, err := image.Decode(res.Body)\n\treturn img, err\n}", "func CombineRGBA(r, g, b, a *image.Gray) (out *image.RGBA) {\n\tinputs := []*image.Gray{r, g, b, a}\n\tfor i := 1; i < len(inputs); i++ {\n\t\tif inputs[i].Bounds() != inputs[0].Bounds() {\n\t\t\tpanic(\"image bounds do not match\")\n\t\t}\n\t}\n\tout = image.NewRGBA(inputs[0].Bounds())\n\tfor x := out.Bounds().Min.X; x < out.Bounds().Max.X; x++ {\n\t\tfor y := out.Bounds().Min.Y; y < out.Bounds().Max.Y; y++ {\n\t\t\toffset1 := out.PixOffset(x, y)\n\t\t\toffset2 := r.PixOffset(x, y)\n\t\t\tout.Pix[offset1+RED] = r.Pix[offset2]\n\t\t\tout.Pix[offset1+GREEN] = g.Pix[offset2]\n\t\t\tout.Pix[offset1+BLUE] = b.Pix[offset2]\n\t\t\tout.Pix[offset1+ALPHA] = a.Pix[offset2]\n\t\t}\n\t}\n\treturn\n}", "func WriteUInt64(buffer []byte, offset int, value uint64) {\n buffer[offset + 0] = byte(value >> 0)\n buffer[offset + 1] = byte(value >> 8)\n buffer[offset + 2] = byte(value >> 16)\n buffer[offset + 3] = byte(value >> 24)\n buffer[offset + 4] = byte(value >> 32)\n buffer[offset + 5] = byte(value >> 40)\n buffer[offset + 6] = byte(value >> 48)\n buffer[offset + 7] = byte(value >> 56)\n}", "func (h heightmap) at(x, z uint8) uint8 {\n\treturn h[(uint16(x)<<4)|uint16(z)]\n}", "func drawTilePixels(image *image.RGBA, pixel [8][8]color.RGBA, xOffset int, yOffset int) *image.RGBA {\n\tfor x := 0; x < TileWidth; x++ {\n\t\tfor y := 0; y < TileHeight; y++ {\n\t\t\timage.SetRGBA(xOffset*TileWidth+x, yOffset*TileHeight+y, pixel[y][x])\n\t\t}\n\t}\n\treturn image\n}", "func (p *PCG64) Uint64() uint64 {\n\tp.multiply()\n\tp.add()\n\t// XOR high and low 64 bits together and rotate right by high 6 bits of state.\n\treturn bits.RotateLeft64(p.high^p.low, -int(p.high>>58))\n}", "func imageWatermark2(imgOriginPath string, imgWatermarkPath string, imgOutPath string, offsetX int, offsetY int, percent float64) {\n imgOriginFile, _ := os.Open(imgOriginPath)\n imgOrigin, imgOriginType, _ := image.Decode(imgOriginFile)\n fmt.Println(\"imgOrigin image type is:\", imgOriginType)\n defer imgOriginFile.Close()\n\n imgWatermarkFile, _ := os.Open(imgWatermarkPath)\n imgWatermark, imgWatermarkType, _ := image.Decode(imgWatermarkFile)\n fmt.Println(\"imgWatermark image type is:\", imgWatermarkType)\n defer imgWatermarkFile.Close()\n\n originBounds := imgOrigin.Bounds()\n WatermarkBounds := imgOrigin.Bounds()\n dx := originBounds.Dx()\n dy := originBounds.Dy()\n\n if WatermarkBounds.Dx() > dx {\n dx = WatermarkBounds.Dx()\n }\n if WatermarkBounds.Dy() > dy {\n dy = WatermarkBounds.Dy()\n }\n\n newRgba := image.NewRGBA(image.Rect(0, 0, dx, dy))\n for x := offsetX; x < dx; x++ {\n for y := offsetY; y < dy; y++ {\n r, b, g, a := imgWatermark.At(x-offsetX, y-offsetY).RGBA()\n newRgba.Set(x, y, color.RGBA{\n uint8(r >> 8),\n uint8(b >> 8),\n uint8(g >> 8),\n uint8(a >> 8),\n })\n }\n }\n\n result := blend.Opacity(imgOrigin, newRgba, percent)\n\n imgOutFile, _ := os.Create(imgOutPath)\n\n jpeg.Encode(imgOutFile, result, &jpeg.Options{jpeg.DefaultQuality})\n defer imgOutFile.Close()\n switch imgOriginType {\n case \"jpeg\":\n jpeg.Encode(imgOutFile, result, &jpeg.Options{jpeg.DefaultQuality})\n case \"png\":\n png.Encode(imgOutFile, result)\n }\n\n}", "func (p *Gray) PixOffset(x, y int) int {\n\treturn (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*1\n}", "func IndexUint64(s uint64, list []uint64) int {\n\tfor i, b := range list {\n\t\tif b == s {\n\t\t\treturn i\n\t\t}\n\t}\n\treturn -1\n}", "func NewNRGBA(r Rectangle) *NRGBA {\n\treturn &NRGBA{\n\t\tPix: make([]uint8, pixelBufferLength(4, r, \"NRGBA\")),\n\t\tStride: 4 * r.Dx(),\n\t\tRect: r,\n\t}\n}", "func InterleaveUInt64(x, y uint64) uint64 {\n\tx = (x | (x << 16)) & 0x0000FFFF0000FFFF\n\ty = (y | (y << 16)) & 0x0000FFFF0000FFFF\n\n\tx = (x | (x << 8)) & 0x00FF00FF00FF00FF\n\ty = (y | (y << 8)) & 0x00FF00FF00FF00FF\n\n\tx = (x | (x << 4)) & 0x0F0F0F0F0F0F0F0F\n\ty = (y | (y << 4)) & 0x0F0F0F0F0F0F0F0F\n\n\tx = (x | (x << 2)) & 0x3333333333333333\n\ty = (y | (y << 2)) & 0x3333333333333333\n\n\tx = (x | (x << 1)) & 0x5555555555555555\n\ty = (y | (y << 1)) & 0x5555555555555555\n\n\treturn x | (y << 1)\n}", "func FormatUint64(name string) string {\n\treturn formatUintFunction(name, false)\n}", "func (n *Uint256) Uint64() uint64 {\n\treturn n.n[0]\n}", "func FormatUint64(format string, v ...any) uint64 {\n\treturn GetUint64(Format(format, v...))\n}" ]
[ "0.6055202", "0.6033384", "0.5877179", "0.5560294", "0.551937", "0.54981863", "0.5430835", "0.5400374", "0.539645", "0.53652084", "0.5348821", "0.5325234", "0.5296761", "0.5273116", "0.5249208", "0.521503", "0.52067333", "0.5178654", "0.51651424", "0.51577365", "0.51570386", "0.515573", "0.50874895", "0.50837153", "0.50791615", "0.50710946", "0.49884862", "0.4973944", "0.48892456", "0.48356053", "0.47994772", "0.4799051", "0.47535643", "0.47498018", "0.47208163", "0.4718256", "0.46611476", "0.46581984", "0.46466193", "0.46321937", "0.46268293", "0.45948818", "0.4594176", "0.45891157", "0.45829064", "0.45800442", "0.45704773", "0.45590535", "0.45412925", "0.4536835", "0.45332292", "0.45329976", "0.45140556", "0.45028725", "0.4500664", "0.449734", "0.44854504", "0.44815508", "0.44809067", "0.44730502", "0.44711068", "0.44707254", "0.44689766", "0.4464142", "0.44466582", "0.44462013", "0.44437033", "0.44434953", "0.4431314", "0.44304505", "0.44215173", "0.4419097", "0.44189194", "0.4416329", "0.44050592", "0.4391439", "0.43825197", "0.43769893", "0.43729925", "0.4372619", "0.43705803", "0.43439126", "0.43438685", "0.43331382", "0.4330362", "0.43044317", "0.42999926", "0.4294786", "0.4294146", "0.42920083", "0.42827576", "0.42803454", "0.42800224", "0.42758906", "0.42727506", "0.4264712", "0.4259017", "0.4258605", "0.42571115", "0.42560643" ]
0.7612087
0
Unwrap returns the error this one wraps. Will return nil if this error doesn't wrap another
func (e *Error) Unwrap() error { return e.e }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Unwrap(err error) error { return errors.Unwrap(err) }", "func (e Error) Unwrap() error {\n\treturn e.Cause\n}", "func (e Error) Unwrap() error {\n\treturn e.Cause\n}", "func (e VerifyError) Unwrap() error {\n\treturn e.Cause\n}", "func unwrap(err error) error {\n\tif c, ok := err.(interface {\n\t\tCause() error\n\t}); ok {\n\t\treturn c.Cause()\n\t}\n\tif u, ok := err.(interface {\n\t\tUnwrap() error\n\t}); ok {\n\t\treturn u.Unwrap()\n\t}\n\treturn nil\n}", "func (e *Error) Unwrap() error {\n\treturn e.wrapped\n}", "func (e *Error) Unwrap() error { return e.Err }", "func (e *Error) Unwrap() error { return e.Err }", "func UnWrap(err error) (current error, previous error) {\n\tswitch e := err.(type) {\n\tcase *withError:\n\t\treturn e.current, e.previous\n\tdefault:\n\t\treturn e, nil\n\t}\n}", "func (e errWithCause) Unwrap() error {\n\treturn e.cause\n}", "func Unwrap(err error) error {\n\treturn errors.Unwrap(err)\n}", "func unwrap(err error) error {\n\tif connErr, ok := err.(beanstalk.ConnError); ok {\n\t\treturn connErr.Err\n\t} else if nameErr, ok := err.(beanstalk.NameError); ok {\n\t\treturn nameErr.Err\n\t}\n\treturn err\n}", "func (err *Error) Unwrap() error {\n\treturn err.prev\n}", "func (e *Error) Unwrap() error { return e.Inner }", "func (e Error) Unwrap() error {\n\treturn e.err\n}", "func (e Error) Unwrap() error {\n\treturn e.err\n}", "func (e *Error) Unwrap() error {\n\treturn e.err\n}", "func (e *Error) Unwrap() error {\n\treturn e.Err\n}", "func (e *Error) Unwrap() error {\n\treturn e.Err\n}", "func (e *Error) Unwrap() error {\n\treturn e.Err\n}", "func (e *Error) Unwrap() error {\n\treturn e.Err\n}", "func (err *SilenceError) Unwrap() error {\n\treturn err.err\n}", "func (e Error) Unwrap() error { return e.err }", "func (re RemediationError) Unwrap() error {\n\treturn re.Inner\n}", "func (ce ConstraintError) Unwrap() error {\n\treturn ce.Err\n}", "func Unwrap(err error) error {\n\tu, ok := err.(interface {\n\t\tUnwrap() error\n\t})\n\tif !ok {\n\t\treturn nil\n\t}\n\treturn u.Unwrap()\n}", "func (p *PermanentError) Unwrap() error {\n\treturn p.Err\n}", "func (e *errorT) Unwrap() error {\n\treturn e.err\n}", "func (derr *DeepError) Unwrap() error {\n\treturn derr.Err\n}", "func (msg *Error) Unwrap() error {\n\treturn msg.Err\n}", "func Unwrap(err error) error {\n\treturn builtin.Unwrap(err)\n}", "func (e Err) Unwrap() error {\n\treturn e.c\n}", "func (e *NotifyErr) Unwrap() error { return e.Err }", "func (f FatalErr) Unwrap() error {\n\treturn errors.Unwrap(f.err)\n}", "func (je *JettisonError) Unwrap() error {\n\terr := je.Clone() // Don't want to modify the reference\n\n\tfor len(err.Hops) > 0 {\n\t\tif len(err.Hops[0].Errors) == 0 {\n\t\t\terr.Hops = err.Hops[1:]\n\t\t\tcontinue\n\t\t}\n\n\t\terr.Hops[0].Errors = err.Hops[0].Errors[1:]\n\t\tbreak\n\t}\n\n\t// Remove any empty hop layers.\n\tfor len(err.Hops) > 0 {\n\t\th := err.Hops[0]\n\t\tif len(h.Errors) > 0 {\n\t\t\tbreak\n\t\t}\n\n\t\terr.Hops = err.Hops[1:]\n\t}\n\n\tif len(err.Hops) == 0 {\n\t\treturn nil\n\t}\n\n\t// If this was the last unwrap, just return the original error for\n\t// compatibility with golang.org/x/xerrors.Unwrap() if it isn't nil.\n\t//\n\t// NOTE(guy): This can lead to a gotcha where an errors.Is() call works\n\t// locally, but doesn't work over gRPC since original error values can't\n\t// be preserved over the wire.\n\tif len(err.Hops) == 1 &&\n\t\tlen(err.Hops[0].Errors) == 1 &&\n\t\terr.OriginalErr != nil {\n\n\t\treturn err.OriginalErr\n\t}\n\n\tif subJe, ok := je.Err.(*JettisonError); ok {\n\t\terr.Message = subJe.Message\n\t\terr.Binary = subJe.Binary\n\t\terr.StackTrace = subJe.StackTrace\n\t\terr.KV = subJe.KV\n\t\terr.Code = subJe.Code\n\t\terr.Err = subJe.Err\n\t}\n\n\treturn err\n}", "func (u *UnknownError) Unwrap() error {\n\treturn u.cause\n}", "func (e *SlabNotFoundError) Unwrap() error { return e.err }", "func (e *ForbiddenDiffError) Unwrap() error {\n\treturn e.WrappedErr\n}", "func (e *testError) Unwrap() error {\n\treturn e.err\n}", "func Unwrap(err error) error {\n\treturn stderrs.Unwrap(err)\n}", "func (e *StorageError) Unwrap() error { return e.err }", "func (e *ValidateErr) Unwrap() error { return nil }", "func (e RethinkDBError) Unwrap() error {\n\treturn e.err\n}", "func (e HTTPError) Unwrap() error {\n\treturn e.InnerError\n}", "func Unwrap(err error) error {\n\tfor i := 0; err != nil && i < maxUnwrap; i++ {\n\t\tvar nerr error\n\n\t\tswitch e := err.(type) {\n\t\tcase Causer:\n\t\t\tnerr = e.Cause()\n\n\t\tcase interface{ Unwrap() error }:\n\t\t\tnerr = e.Unwrap()\n\n\t\tcase interface{ Ungroup() []error }:\n\t\t\t// consider the first error to be the \"main\" error.\n\t\t\terrs := e.Ungroup()\n\t\t\tif len(errs) > 0 {\n\t\t\t\tnerr = errs[0]\n\t\t\t}\n\t\tcase interface{ Unwrap() []error }:\n\t\t\t// consider the first error to be the \"main\" error.\n\t\t\terrs := e.Unwrap()\n\t\t\tif len(errs) > 0 {\n\t\t\t\tnerr = errs[0]\n\t\t\t}\n\t\t}\n\n\t\tif nerr == nil {\n\t\t\treturn err\n\t\t}\n\t\terr = nerr\n\t}\n\n\treturn err\n}", "func (e *ErrCollector) Unwrap() error {\n\treturn e.Err\n}", "func (e *ErrMySQLInvalidArgumentIdentity) Unwrap() error {\n\treturn e.err\n}", "func (e *MissingRequiredFieldError) Unwrap() error {\n\treturn e.Err\n}", "func (e *ConstraintError) Unwrap() error {\n\treturn e.wrap\n}", "func (b *BuildError) Unwrap() error {\n\treturn b.Err\n}", "func (he HostError) Unwrap() error {\n\treturn he.Err\n}", "func (e *ErrMySQLNotFoundIdentity) Unwrap() error {\n\treturn e.err\n}", "func (ce ConfigError) Unwrap() error {\n\treturn ce.err\n}", "func (e *userError) Unwrap() error {\n\treturn e.wrap\n}", "func (e *HashError) Unwrap() error { return e.err }", "func (err *ErrStackAlreadyExists) Unwrap() error {\n\treturn err.parentErr\n}", "func (de *DecodeError) Unwrap() error {\n\treturn de.wrapped\n}", "func (e *ErrConstraintFailed) Unwrap() error {\n\treturn e.wrap\n}", "func (e *DisconnectError) Unwrap() error { return e.err }", "func (e *S3Error) Unwrap() error {\n\treturn e.err\n}", "func (e *ValidationError) Unwrap() error {\n\treturn e.err\n}", "func (e *E) Unwrap() error {\n\treturn e.err\n}", "func (e *ConfigError) Unwrap() error {\n\treturn e.inner\n}", "func (e *statisticsError) Unwrap() error {\n\treturn e.wrap\n}", "func (e *ErrCannotSetValue) Unwrap() error {\n\treturn e.Err\n}", "func (w *pipeError) Unwrap() error { return w.error }", "func (e ErrAuthFailed) Unwrap() error { return e.Err }", "func (e AuthorizationFailedError) Unwrap() error { return e.error }", "func (e *UnmarshalError) Unwrap() error {\n\treturn e.Err\n}", "func execUnwrap(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := errors.Unwrap(args[0].(error))\n\tp.Ret(1, ret)\n}", "func UnwrapErr(err error) error {\n\tfor {\n\t\tvar u unwrapper\n\t\tif !errors.As(err, &u) {\n\t\t\tbreak\n\t\t}\n\t\tunwrapped := u.Unwrap()\n\t\tvar st stackTracer\n\t\tif !errors.As(unwrapped, &st) {\n\t\t\tbreak\n\t\t}\n\t\terr = unwrapped\n\t}\n\treturn err\n}", "func (e *wrapper) Unwrap() error {\n\treturn e.err\n}", "func (he *HTTPError) Unwrap() error {\n\treturn he.Internal\n}", "func TestUnwrapCompatibility(t *testing.T) {\n\terr1 := errors.New(\"err1\")\n\terr2 := xerrors.Errorf(\"err2: %w\", err1)\n\terr3 := errors.Wrap(err2, \"err3\", errors.WithCode(\"ERR_3\"))\n\terr4 := xerrors.Errorf(\"err4: %w\", err3)\n\terr5 := errors.Wrap(err4, \"err5\")\n\n\t// For testing code equality as well as value equality.\n\terr3Clone := errors.New(\"err3_clone\", errors.WithCode(\"ERR_3\"))\n\n\tassert.True(t, errors.Is(err5, err1))\n\tassert.True(t, errors.Is(err5, err2))\n\tassert.True(t, errors.Is(err5, err3))\n\tassert.True(t, errors.Is(err5, err3Clone))\n\tassert.True(t, errors.Is(err5, err4))\n}", "func (e *multiError) Unwrap() error {\n\tif e.offset == nil {\n\t\te.offset = new(int)\n\t} else {\n\t\t*e.offset++\n\t}\n\tif *e.offset == len(e.loadedErrors) {\n\t\te.offset = nil\n\t\treturn nil // Force errors.Is package to return false.\n\t}\n\treturn e\n}", "func Wrap(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif typed, isTyped := err.(*Ex); isTyped {\n\t\treturn typed\n\t}\n\treturn NewFromErr(err)\n}", "func (e *DecodeError) Unwrap() error {\n\treturn e.Err\n}", "func (err *ErrTemplateNotFound) Unwrap() error {\n\treturn err.parentErr\n}", "func (e AuthorizationDeniedError) Unwrap() error { return e.error }", "func (e *RequestCanceledError) Unwrap() error {\n\treturn e.Err\n}", "func (e *IncompatibleStreamError) Unwrap() error { return e.err }", "func Unwrap(err error) error {\n\treturn Next(err)\n}", "func (e *ErrDaemon) Unwrap() error {\n\treturn e.Parent\n}", "func (e *APIError) Unwrap() error {\n\treturn e.ParseError\n}", "func (e *detailedError) Original() error {\n\tif e.original != nil {\n\t\treturn e.original\n\t}\n\treturn e\n}", "func (e URLValidationError) Unwrap() error {\n\treturn e.Err\n}", "func (e *ErrInvalidParameterValue) Unwrap() error {\n\treturn e.Err\n}", "func Wrap(err error, msg string) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\treturn &Error{msg: msg, prev: err}\n}", "func (e *errorBase) WrappedError() error {\n\treturn e.wrapped\n}", "func Cause(err error) error {\n\tif w, ok := err.(*Wrapped); ok {\n\t\t// if root level error\n\t\tif len(w.Errors) > 0 {\n\t\t\treturn w.Errors[0]\n\t\t}\n\t\t// already extracted error\n\t\treturn w\n\t}\n\treturn err\n}", "func (vr ValidateResult) Unwrap() []error {\n\t// Support for multi-error wrapping is expected in Go 1.20.\n\t// https://github.com/golang/go/issues/53435#issuecomment-1191752789\n\treturn vr.errors\n}", "func Wrap(e error) error {\n\treturn &errors{\n\t\tmsg: e.Error(),\n\t\tfileInfo: getFileInfo(),\n\t}\n}", "func UnwrapWith(err error, note string) {\n\tif err != nil {\n\t\terr := fmt.Errorf(\"%s: %s\", note, err.Error())\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func Wrap(err error) error {\n\treturn &usererr{err}\n}", "func unwrapNotFoundErr(err error) error {\n\tif s, _ := status.FromError(err); s != nil {\n\t\tif s.Message() == spanstore.ErrTraceNotFound.Error() {\n\t\t\treturn spanstore.ErrTraceNotFound\n\t\t}\n\t}\n\treturn err\n}", "func Wrap(previous error, current interface{}) error {\n\tvar currentError error\n\tswitch c := current.(type) {\n\tcase error:\n\t\tcurrentError = c\n\tcase string:\n\t\tcurrentError = new(\"\", c)\n\tdefault:\n\t\tcurrentError = invalidWrap(\"unsupported type, it should be either of type error/string\")\n\t}\n\n\treturn &withError{\n\t\tprevious: previous,\n\t\tcurrent: currentError,\n\t}\n}", "func errWrap(err error, as error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\tif errors.Is(err, as) {\n\t\treturn err\n\t}\n\treturn fmt.Errorf(\"%w: %v\", as, err)\n}", "func (c *CachedMessage) Unwrap() *Message {\n\tuntypedMessage := c.Get()\n\tif untypedMessage == nil {\n\t\treturn nil\n\t}\n\ttypeCastedMessage := untypedMessage.(*Message)\n\tif typeCastedMessage == nil || typeCastedMessage.IsDeleted() {\n\t\treturn nil\n\t}\n\treturn typeCastedMessage\n}", "func Unwrap(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(-1)\n\t}\n}", "func Wrap(err error) error {\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tif typedEx, isException := err.(*Ex); isException {\n\t\treturn typedEx\n\t}\n\n\treturn &Ex{\n\t\tinner: err,\n\t\tclass: err.Error(),\n\t\tstack: callers(),\n\t}\n}" ]
[ "0.7593746", "0.75380284", "0.75380284", "0.75104475", "0.7408872", "0.72992533", "0.7293403", "0.7293403", "0.728387", "0.7265658", "0.72645473", "0.7241748", "0.72370875", "0.7218023", "0.72011036", "0.72011036", "0.71888554", "0.71825606", "0.71825606", "0.71825606", "0.71825606", "0.71778435", "0.71724033", "0.7161512", "0.7148368", "0.71244115", "0.7119806", "0.71117455", "0.70966893", "0.70359766", "0.6988841", "0.6978629", "0.6968945", "0.6947115", "0.68727875", "0.68602204", "0.6831567", "0.6831343", "0.68311614", "0.68220955", "0.6794576", "0.67846507", "0.6777886", "0.6771362", "0.67681164", "0.6764682", "0.6725211", "0.6701579", "0.6653853", "0.6633476", "0.66316825", "0.66215205", "0.6620081", "0.6595907", "0.65728074", "0.6572097", "0.653511", "0.6534964", "0.6528537", "0.651166", "0.6499366", "0.647681", "0.64591485", "0.6454691", "0.6443252", "0.6417325", "0.64078474", "0.6379649", "0.63714325", "0.6358087", "0.6352805", "0.63306004", "0.63203806", "0.63126576", "0.629315", "0.62324697", "0.62239397", "0.61493963", "0.61176884", "0.6112427", "0.60783136", "0.6058368", "0.6045569", "0.6040416", "0.5980692", "0.5954802", "0.5943439", "0.5912704", "0.590244", "0.5888345", "0.5785852", "0.57394165", "0.57390374", "0.57105905", "0.5692617", "0.5667821", "0.56496054", "0.56155616", "0.5552745", "0.55412084" ]
0.721719
14
Is returns true if the target is an instance of the supplied error
func (e *Error) Is(target error) bool { _, ok := target.(*Error) return ok }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Is(err, target error) bool { return errors.Is(err, target) }", "func Is(err, target error) bool {\n\tif target == nil {\n\t\treturn err == target\n\t}\n\n\tisComparable := reflect.TypeOf(target).Comparable()\n\tfor {\n\t\tif isComparable && err == target {\n\t\t\treturn true\n\t\t}\n\t\tif x, ok := err.(interface{ Is(error) bool }); ok && x.Is(target) {\n\t\t\treturn true\n\t\t}\n\t\tif err = Unwrap(err); err == nil {\n\t\t\treturn false\n\t\t}\n\t}\n}", "func Is(err error, target error) bool {\n\treturn errors.Is(err, target)\n}", "func (e *Error) Is(target error) bool {\n\terr := e.Err\n\n\tswitch target {\n\tcase e:\n\t\treturn true\n\tcase nil:\n\t\treturn err == nil\n\t}\n\tfor {\n\t\tswitch err {\n\t\tcase nil:\n\t\t\treturn false\n\t\tcase target:\n\t\t\treturn true\n\t\t}\n\t\tx, ok := err.(interface{ Unwrap() error })\n\t\tif !ok {\n\t\t\t// Some stdlibs haven't have error unwrapper yet.\n\t\t\t// Check err.Err field if exposed.\n\t\t\tif reflect.TypeOf(err).Kind() == reflect.Ptr {\n\t\t\t\te := reflect.ValueOf(err).Elem().FieldByName(\"Err\")\n\t\t\t\tif e.IsValid() {\n\t\t\t\t\te2, ok := e.Interface().(error)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn false\n\t\t\t\t\t}\n\t\t\t\t\terr = e2\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t}\n\t\terr = x.Unwrap()\n\t}\n}", "func Is(err error, target error) bool {\n\treturn goerrors.Is(err, target)\n}", "func Is(err, target error) bool { return stderrs.Is(err, target) }", "func Is(err, target error) bool {\n\treturn errors.Is(err, target)\n}", "func Is(err, target error) bool {\n\treturn builtin.Is(err, target)\n}", "func Is(err, target error) bool {\n\tif e, ok := err.(iIs); ok {\n\t\treturn e.Is(target)\n\t}\n\treturn false\n}", "func (e *NotifyErr) Is(target error) bool {\n\tt, ok := target.(*NotifyErr)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn e.Type == t.Type\n}", "func (e Error) Is(target error) bool {\n\tif target == nil {\n\t\treturn false\n\t}\n\n\terr, ok := target.(Error)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn (err.StatusCode == e.StatusCode || e.StatusCode == 0) &&\n\t\t(err.Message == e.Message || e.Message == \"\")\n}", "func (a *errorClassAnnotation) Is(target error) bool {\n\treturn errors.Is(a.wrapped, target)\n}", "func (f *CommandError) Is(target error) bool {\n\tif target == f {\n\t\treturn true\n\t}\n\tvar t *CommandError\n\tif !errors.As(target, &t) {\n\t\treturn false\n\t}\n\treturn f.ID == t.ID &&\n\t\tf.Index == t.Index &&\n\t\tf.Command == t.Command &&\n\t\tf.Message == t.Message\n}", "func (e *Error) Is(target error) bool {\n\tif e == target {\n\t\treturn true\n\t}\n\tif e != nil {\n\t\tif errors.Is(e.Err, target) {\n\t\t\treturn true\n\t\t}\n\t\tif errors.Is(e.Cause, target) {\n\t\t\treturn true\n\t\t}\n\t\tcause := Cause(target)\n\t\tif cause != nil && cause != target && errors.Is(e, cause) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (e Error) Is(target error) bool {\n\tfor _, err := range e.errs {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (e *Error) Is(target error) bool {\n\tif errors.Is(target, ErrNotFound) {\n\t\treturn e.Status == http.StatusNotFound && e.ErrorCode == errorCodeNotFound\n\t}\n\tif errors.Is(target, ErrVersionBeingDeactivated) {\n\t\treturn e.ErrorCode == errorCodeVersionIsBeingDeactivated\n\t}\n\tif errors.Is(target, ErrVersionAlreadyDeactivated) {\n\t\treturn e.ErrorCode == errorCodeVersionAlreadyDeactivated\n\t}\n\n\tvar t *Error\n\tif !errors.As(target, &t) {\n\t\treturn false\n\t}\n\n\tif e == t {\n\t\treturn true\n\t}\n\n\tif e.Status != t.Status {\n\t\treturn false\n\t}\n\n\treturn e.Error() == t.Error()\n}", "func (e *errorT) Is(err error) bool {\n\tcmc, ok := err.(*classMembershipChecker)\n\treturn ok && e.class == (*Class)(cmc)\n}", "func (be Batch) Is(target error) bool {\n\tfor _, err := range be.errors {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (agg aggregate) Is(target error) bool {\n\treturn agg.visit(func(err error) bool {\n\t\treturn errors.Is(err, target)\n\t})\n}", "func Is(err error, class Class) bool {\n\tif err == nil || class == nil {\n\t\treturn false\n\t}\n\tif e, ok := err.(interface{ Class() Class }); ok {\n\t\tif e.Class() == class {\n\t\t\treturn true\n\t\t}\n\t}\n\tif e, ok := err.(interface{ Cause() error }); ok {\n\t\tif cause := e.Cause(); cause != nil {\n\t\t\treturn Is(cause, class)\n\t\t}\n\t}\n\tif errs, ok := err.(MultiError); ok {\n\t\tfor _, e := range errs {\n\t\t\tif Is(e, class) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (f FatalErr) Is(target error) bool {\n\tswitch target.(type) {\n\tcase FatalErr, *FatalErr:\n\t\treturn true\n\t}\n\treturn false\n}", "func (e *multiErr) Is(target error) bool {\n\tfor _, err := range e.errs {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (je *JettisonError) Is(target error) bool {\n\tif je == nil || target == nil {\n\t\treturn false\n\t}\n\n\ttargetJErr, ok := target.(*JettisonError)\n\tif !ok {\n\t\treturn false\n\t}\n\n\tif je == targetJErr {\n\t\treturn true\n\t}\n\n\ttargetErr, ok := targetJErr.LatestError()\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// If target doesn't have an error code, then there's nothing to check.\n\tif targetErr.Code == \"\" {\n\t\treturn false\n\t}\n\n\tfor je != nil {\n\t\tjerr, ok := je.LatestError()\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\n\t\tif targetErr.Code == jerr.Code {\n\t\t\treturn true\n\t\t}\n\n\t\tje = unwrap(je)\n\t}\n\n\treturn false\n}", "func (e *NotFoundError) Is(tgt error) bool {\n\t_, ok := tgt.(*NotFoundError)\n\treturn ok\n}", "func (e *Result) Is(target error) bool {\n\tif o, ok := target.(*Result); ok {\n\t\treturn e.StatusCode == o.StatusCode\n\t}\n\n\t// Special case for nil == ACK\n\tif o, ok := target.(*protocol.Receipt); ok {\n\t\tif e == nil && o.ACK {\n\t\t\treturn true\n\t\t}\n\t}\n\n\t// Allow for wrapped errors.\n\tif e != nil {\n\t\terr := fmt.Errorf(e.Format, e.Args...)\n\t\treturn errors.Is(err, target)\n\t}\n\treturn false\n}", "func (e *NotCraftError) Is(tgt error) bool {\n\t_, ok := tgt.(*NotCraftError)\n\treturn ok\n}", "func (err ErrAggregate) Is(target error) bool {\n\tfor _, err := range err.errs {\n\t\tif errors.Is(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func As(err error, target interface{}) bool { return errors.As(err, target) }", "func (e *ErrUnknownProvider) Is(target error) bool {\n\t_, ok := target.(*ErrUnknownProvider)\n\treturn ok\n}", "func (err *ErrStackSetOutOfDate) Is(target error) bool {\n\tt, ok := target.(*ErrStackSetOutOfDate)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn err.projectName == t.projectName\n}", "func (e *Error) Is(err error) bool {\n\tif k, ok := err.(Kind); ok {\n\t\treturn k&e.Kind == e.Kind\n\t}\n\treturn false\n}", "func (r TPMRC) Is(target error) bool {\n\ttargetTPMRC, ok := target.(TPMRC)\n\tif !ok {\n\t\treturn false\n\t}\n\tif isFmt1, fmt1 := r.isFmt1Error(); isFmt1 {\n\t\treturn fmt1.canonical == targetTPMRC\n\t}\n\treturn r == targetTPMRC\n}", "func Is(err error) bool {\n\tif _, typedOk := err.(*Ex); typedOk {\n\t\treturn true\n\t}\n\treturn false\n}", "func Is(err error) bool {\n\tif _, typedOk := err.(*Ex); typedOk {\n\t\treturn true\n\t}\n\treturn false\n}", "func IsOfType(terr, err error) bool {\n\tif errt, ok := err.(TypedError); ok {\n\t\treturn errt.IsOfType(terr)\n\t}\n\n\tif serr, ok := status.FromError(err); ok {\n\t\treturn serr.Message() == terr.Error()\n\t}\n\n\treturn err.Error() == terr.Error()\n}", "func As(err error, target interface{}) bool {\n\treturn goerrors.As(err, target)\n}", "func As(err error, target interface{}) bool {\n\treturn errors.As(err, target)\n}", "func (RetryableError) Is(target error) bool {\n\treturn target == ErrRetryable\n}", "func (err *ErrTemplateNotFound) Is(target error) bool {\n\tt, ok := target.(*ErrTemplateNotFound)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn (err.templateLocation == t.templateLocation) &&\n\t\t(errors.Is(err.parentErr, t.parentErr))\n}", "func (e *ValidateErr) Is(target error) bool {\n\tt, ok := target.(*ValidateErr)\n\tif !ok {\n\t\treturn false\n\t}\n\n\t// check for interface Value separately\n\tif e.Value != nil && t.Value != nil &&\n\t\t(!reflect.ValueOf(e.Value).IsValid() && !reflect.ValueOf(t.Value).IsValid()) {\n\t\treturn false\n\t}\n\t// not supporting non-comparable values for now\n\tif e.Value != nil && t.Value != nil &&\n\t\t!(reflect.TypeOf(e.Value).Comparable() && reflect.TypeOf(t.Value).Comparable()) {\n\t\treturn false\n\t}\n\treturn (e.Type == t.Type || t.Type == \"\") &&\n\t\t(e.Target == t.Target || t.Target == \"\") &&\n\t\t(e.Value == t.Value || t.Value == nil || reflect.ValueOf(t.Value).IsZero()) &&\n\t\t(e.LHS == t.LHS || t.LHS == \"\") &&\n\t\t(e.RHS == t.RHS || t.RHS == \"\")\n}", "func (e *multiErr) As(target interface{}) bool {\n\tfor _, err := range e.errs {\n\t\tif errors.As(err, target) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (ec *QueryErrorCollector) As(target interface{}) bool {\n\tif target == nil {\n\t\tlog.Errorf(\"ErrorCollection.As() target cannot be nil\")\n\t\treturn false\n\t}\n\n\tval := reflect.ValueOf(target)\n\ttyp := val.Type()\n\tif typ.Kind() != reflect.Ptr || val.IsNil() {\n\t\tlog.Errorf(\"ErrorCollection.As() target must be a non-nil pointer\")\n\t\treturn false\n\t}\n\tif e := typ.Elem(); e.Kind() != reflect.Interface && !e.Implements(errorType) {\n\t\tlog.Errorf(\"ErrorCollection.As() *target must be interface or implement error\")\n\t\treturn false\n\t}\n\n\ttargetType := typ.Elem()\n\tfor _, err := range AllErrorsFor(ec) {\n\t\tif reflect.TypeOf(err).AssignableTo(targetType) {\n\t\t\tval.Elem().Set(reflect.ValueOf(err))\n\t\t\treturn true\n\t\t}\n\t\tif x, ok := err.(interface{ As(interface{}) bool }); ok && x.As(target) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}", "func Is(err error, is *errors.Error) bool {\n\terrorFound := errors.Find(err, func(e error) bool {\n\t\tnormalizedErr, ok := e.(*errors.Error)\n\t\treturn ok && normalizedErr.ID() == is.ID()\n\t})\n\treturn errorFound != nil\n}", "func (e *GraphQLErrors) Is(target error) bool {\n\tif target == ErrGraphQLNotFound {\n\t\treturn len(e.errors) == 1 && e.HasType(gitHubGraphQLNotFoundType)\n\t}\n\treturn false\n}", "func (e Error) As(target interface{}) bool {\n\tswitch targetT := target.(type) {\n\tcase *resp.ErrDiscarded:\n\t\ttargetT.Err = e\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func (e Error) As(target interface{}) bool {\n\tfor _, err := range e.errs {\n\t\tif ok := errors.As(err, target); ok {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (t *typedError) IsOfType(terr error) bool {\n\tif t.terr.Error() == terr.Error() {\n\t\treturn true\n\t}\n\n\tif cterr, ok := t.ctxErr.(TypedError); ok {\n\t\treturn cterr.IsOfType(terr)\n\t}\n\n\treturn t.ctxErr.Error() == terr.Error()\n}", "func (e *userError) Is(Resource error) bool {\n\tt, ok := Resource.(*userError)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn t.resource == e.resource && t.error == e.error\n}", "func As(err error, target interface{}) bool {\n\treturn builtin.As(err, target)\n}", "func (e *ErrInvalidPipelineManifestVersion) Is(target error) bool {\n\tt, ok := target.(*ErrInvalidPipelineManifestVersion)\n\treturn ok && t.invalidVersion == e.invalidVersion\n}", "func IsDuplicate(err error) bool {\r\n\tvar t Duplicate\r\n\treturn errors.As(err, &t)\r\n}", "func (me TitemIconStateEnumType) IsError() bool { return me == \"error\" }", "func IsError(t Term) bool {\n\treturn t.Type() == ErrorType\n}", "func (err1 Error) Is(err2 error) bool {\n\tif err2, ok := err2.(Error); ok {\n\t\treturn err1.Equals(err2)\n\t}\n\treturn false\n}", "func (e *TypeError) Is() bool {\n\treturn e.Obj != nil\n}", "func iserr(t reflect.Type) bool {\n\tif t.Kind() == reflect.Interface {\n\t\treturn t.Implements(reflect.TypeOf((*error)(nil)).Elem())\n\t}\n\treturn false\n}", "func (e *statisticsError) Is(Resource error) bool {\n\tt, ok := Resource.(*statisticsError)\n\tif !ok {\n\t\treturn false\n\t}\n\n\treturn t.resource == e.resource && t.error == e.error\n}", "func (e errWithCause) Is(err error) bool {\n\treturn errors.Is(err, e.error) || errors.Is(err, e.cause)\n}", "func (e Event) IsError() bool {\n\treturn e.Error != nil\n}", "func (s Status) Is(err error) bool {\n\tvar status Status\n\tif !errors.As(err, &status) {\n\t\treturn false\n\t}\n\treturn status.Code() == s.Code()\n}", "func (e *Err) As(err interface{}) bool {\n\tswitch x := err.(type) {\n\tcase **Err:\n\t\t*x = e\n\tcase *Err:\n\t\t*x = *e\n\tdefault:\n\t\treturn false\n\t}\n\treturn true\n}", "func (e Sentinel) Is(err error) bool {\n\tsentinel, ok := err.(Sentinel)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn sentinel == e\n}", "func (e *err) Is(code any) bool {\n\treturn e.code == code\n}", "func (m AoS) IsErr() bool {\n\treturn m.just == nil || m.err != nil\n}", "func (ps PartialSuccess) Is(err error) bool {\n\t_, ok := err.(PartialSuccess)\n\treturn ok\n}", "func (s *SignUpRequired) Is(err error) bool {\n\t_, ok := err.(*SignUpRequired)\n\treturn ok\n}", "func isFail(err error) bool {\n\t_, ok := err.(failError)\n\treturn ok\n}", "func IsErrNewIssueInsert(err error) bool {\n\t_, ok := err.(ErrNewIssueInsert)\n\treturn ok\n}", "func IsErrCircularDependency(err error) bool {\n\t_, ok := err.(ErrCircularDependency)\n\treturn ok\n}", "func isError(err error) bool {\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn true\n\t}\n\treturn false\n}", "func (msg *Message) IsError() bool {\n\treturn msg.Type == \"err\"\n}", "func sameError(e1, e2 error) bool {\n\treturn reflect.DeepEqual(e1, e2)\n}", "func IsUnsupportedDiff(err error) bool {\n\tvar uderr *UnsupportedDiffError\n\treturn errors.As(err, &uderr)\n}", "func IsErr(err, errType error) bool {\n\tif w, ok := err.(*Wrapped); ok {\n\t\t// if root level error\n\t\tif len(w.Errors) > 0 {\n\t\t\treturn w.Errors[0].Err == errType\n\t\t}\n\t\t// already extracted error\n\t\treturn w.Err == errType\n\t}\n\treturn err == errType\n}", "func (ec *QueryErrorCollector) IsError() bool {\n\tec.m.RLock()\n\tdefer ec.m.RUnlock()\n\n\treturn len(ec.errors) > 0\n}", "func IsExpected(err error) bool {\n\tte, ok := err.(ExpectedError)\n\treturn ok && te.Expected()\n}", "func (e *Error) As(x interface{}) bool {\n\tswitch t := x.(type) {\n\tcase *failure.Code:\n\t\t*t = e.Code\n\t\treturn true\n\tcase failure.Tracer:\n\t\tt.Push(e.Code)\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func IsErr(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n}", "func (e *EncodingError) Is(err error) bool {\n\tencErr, ok := err.(*EncodingError)\n\tif !ok {\n\t\treturn false\n\t}\n\treturn encErr.column == e.column\n}", "func (c Class) Contains(err error) bool {\n\tif e, ok := err.(classer); ok {\n\t\treturn e.Class().Is(c)\n\t}\n\tif e, ok := err.(causer); ok {\n\t\treturn c.Contains(e.Cause())\n\t}\n\treturn false\n}", "func (c *Class) Has(err error) bool {\n\treturn IsFunc(err, func(err error) bool {\n\t\terrt, ok := err.(*errorT)\n\t\treturn ok && errt.class == c\n\t})\n}", "func IsTimeout(err error) bool", "func IsTimeout(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tif t, ok := errs.Cause(err).(timeout); ok {\n\t\treturn t.Timeout()\n\t}\n\treturn false\n}", "func Is(err error, codes ...Code) bool {\n\tif len(codes) == 0 {\n\t\treturn false\n\t}\n\n\tc := CodeOf(err)\n\tif c == nil {\n\t\treturn false\n\t}\n\n\tfor i := range codes {\n\t\tif c == codes[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func IsFailure(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\tswitch err.(type) {\n\tcase *Failure:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}", "func IsError(err error, ctx *gin.Context) bool {\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tctx.JSON(405, Response{err.Error(), err})\n\t\treturn true\n\t}\n\treturn false\n}", "func IsErrIssueLabelTemplateLoad(err error) bool {\n\t_, ok := err.(ErrIssueLabelTemplateLoad)\n\treturn ok\n}", "func IsTypeErr(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\n\treturn strings.HasPrefix(err.Error(), \"Expected type\")\n}", "func (e *ErrorSet) Member(err error) bool {\n\terr2, ok := err.(*Error)\n\n\tif !ok {\n\t\treturn false\n\t}\n\n\te.l.RLock()\n\tdefer e.l.RUnlock()\n\n\treturn e.errs[err2.Code()] == err2\n}", "func Is(err error, codes ...Code) bool {\n\tif len(codes) == 0 {\n\t\treturn false\n\t}\n\n\tc, ok := CodeOf(err)\n\tif !ok {\n\t\t// continue process (don't return) to accept the case Is(err, nil).\n\t\tc = nil\n\t}\n\n\tfor i := range codes {\n\t\tif c == codes[i] {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (obj *testInstruction) IsInstruction() bool {\n\treturn obj.ins != nil\n}", "func (*TimeoutError) IsTimeout() bool {\n\treturn true\n}", "func IsTempFail(err error) bool {\n\t_, ok := err.(tempFailError)\n\treturn ok\n}", "func IsTimeout(err error) bool {\n\tfor err != nil {\n\t\tif bterr, ok := err.(isTimeouter); ok {\n\t\t\treturn bterr.IsTimeout()\n\t\t}\n\n\t\tif cerr, ok := err.(causer); ok {\n\t\t\terr = cerr.Cause()\n\t\t}\n\t}\n\treturn false\n}", "func typeIs(target string, src interface{}) bool {\n\treturn target == typeOf(src)\n}", "func (c *core) Is(ec ErrorCode) bool {\n\treturn (c.code == ec)\n}", "func IsTimeout(err error) bool {\n\ttype timeouter interface {\n\t\tTimeout() bool\n\t}\n\treturn isErrorPredicate(err, func(err error) bool {\n\t\te, ok := err.(timeouter)\n\t\treturn ok && e.Timeout()\n\t})\n}", "func (be Batch) As(v interface{}) bool {\n\tif target, ok := v.(*Batch); ok {\n\t\t*target = be\n\t\treturn true\n\t}\n\tif target, ok := v.(**Batch); ok {\n\t\t*target = &be\n\t\treturn true\n\t}\n\tfor _, err := range be.errors {\n\t\tif errors.As(err, v) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (SinkType) Is(typ string) bool { return boolResult }", "func IsOpen(err error) bool {\n\tfor err != nil {\n\t\tif bserr, ok := err.(stater); ok {\n\t\t\treturn bserr.State() == Open\n\t\t}\n\n\t\tif cerr, ok := err.(causer); ok {\n\t\t\terr = cerr.Cause()\n\t\t}\n\t}\n\treturn false\n}" ]
[ "0.8182926", "0.780322", "0.77321935", "0.7703872", "0.76903725", "0.76835155", "0.765193", "0.7572768", "0.75197583", "0.75171906", "0.748898", "0.73875564", "0.73700005", "0.7328921", "0.7307654", "0.72117954", "0.7171244", "0.7170923", "0.7167885", "0.7134693", "0.7086476", "0.705087", "0.704262", "0.6987196", "0.6972697", "0.6966939", "0.69259334", "0.6920692", "0.680554", "0.6776333", "0.67326385", "0.67313385", "0.6718268", "0.6718268", "0.67020595", "0.6677848", "0.6674693", "0.6647206", "0.6639044", "0.6636955", "0.65380687", "0.6531421", "0.6521423", "0.649969", "0.6495234", "0.6490842", "0.6439107", "0.6361297", "0.6295476", "0.6227652", "0.6190525", "0.6154092", "0.6121636", "0.61155283", "0.6081434", "0.6075774", "0.60635835", "0.5995355", "0.59935606", "0.5984707", "0.5963442", "0.59555894", "0.59252685", "0.58935714", "0.58911943", "0.58811736", "0.5878241", "0.5818256", "0.5802664", "0.5790886", "0.576337", "0.5709599", "0.56680804", "0.5646969", "0.55559033", "0.5548036", "0.5535854", "0.55238193", "0.5510535", "0.5499081", "0.54958254", "0.54839826", "0.5482439", "0.5477396", "0.54770756", "0.5469473", "0.54657906", "0.5442686", "0.543936", "0.5434092", "0.54318887", "0.54245585", "0.5393689", "0.53864574", "0.5354299", "0.5348872", "0.5336487", "0.5335918", "0.53311986", "0.53311205" ]
0.7800804
2
Type returns the error code
func (e *Error) Type() int { return e.code }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (err myError) Type() errorType {\n\treturn err.errType\n}", "func (e *Error) Type() ObjectType { return ERROR_OBJ }", "func (*SpeechRecognitionResultError) TypeID() uint32 {\n\treturn SpeechRecognitionResultErrorTypeID\n}", "func (ledgerError *Error) Type() ErrorType {\n\treturn ledgerError.errType\n}", "func (e *Error) Code() int { return e.code }", "func GetType(err error) ErrorType {\n\tif mpErr, ok := err.(Error); ok {\n\t\treturn mpErr.errType\n\t}\n\treturn InternalError\n}", "func (err gourdError) Code() int {\n\treturn err.code\n}", "func (e *Error) Type() Type {\n\treturn ERROR_OBJ\n}", "func (e *Error) Type() ObjectType {\n\treturn ERROR\n}", "func (se StatusError) Code() int {\n\treturn int(se)\n}", "func Code(err error) int {\n\tif err == nil {\n\t\treturn CodeOK\n\t}\n\n\te, ok := err.(*Err)\n\tif !ok {\n\t\treturn CodeUnknown\n\t}\n\n\tif e == nil {\n\t\treturn CodeOK\n\t}\n\n\treturn e.Code\n}", "func GetType(err error) ErrorType {\n\tif customErr, ok := err.(customError); ok {\n\t\treturn customErr.errorType\n\t}\n\n\treturn Unknown\n}", "func getCodedError() (int, error){\n\treturn 0, errors.New(\"Something Went Whrong\")\n}", "func GetType(err error) ErrorType {\n\tif customErr, ok := err.(customError); ok {\n\t\treturn customErr.errorType\n\t}\n\n\treturn NoType\n}", "func (oe *OraErr) Code() int { return oe.code }", "func (e err) Code() int {\n\treturn e.code\n}", "func (*StatsGraphError) TypeID() uint32 {\n\treturn StatsGraphErrorTypeID\n}", "func (*SecureValueError) TypeID() uint32 {\n\treturn SecureValueErrorTypeID\n}", "func (re *RetError) Code() int {\n\treturn re.code\n}", "func (obj *errorStruct) Code() uint {\n\treturn obj.code\n}", "func getCode(err error) int {\n\terr = errors.Cause(err)\n\n\tif err == nil {\n\t\treturn 200\n\t}\n\n\tvar code = 500\n\n\tif c, ok := err.(coded); ok {\n\t\tcode = c.Code()\n\t}\n\n\treturn code\n}", "func (*SecureValueErrorData) TypeID() uint32 {\n\treturn SecureValueErrorDataTypeID\n}", "func (e Error) Code() safehttp.StatusCode {\n\treturn e.StatusCode\n}", "func (err StandardError) Code() uint {\n\treturn err.FCode\n}", "func ErrMadNetType() **errMadNet {\n\tvar e *errMadNet\n\treturn &e\n}", "func (e *Error) Type() string {\n\treturn e.t\n}", "func (e *Error) Code() int {\n\treturn e.code\n}", "func (e DError) Code() int {\n\treturn e.code\n}", "func ValueFrom(err error) int32 {\n\tif err != nil {\n\t\tfor err != nil {\n\t\t\t//from grpc status\n\t\t\tif st, ok := status.FromError(err); ok {\n\t\t\t\treturn int32(st.Code())\n\t\t\t}\n\t\t\t//from error coder implement\n\t\t\tif cd, ok := err.(coder); ok {\n\t\t\t\treturn cd.Value()\n\t\t\t}\n\t\t\terr = errors.Unwrap(err)\n\t\t}\n\t\treturn -1\n\t}\n\treturn 0\n}", "func (err *gooseError) code() Code {\n\tif err.errcode != UnspecifiedError {\n\t\treturn err.errcode\n\t}\n\tif e, ok := err.cause.(*gooseError); ok {\n\t\treturn e.code()\n\t}\n\treturn UnspecifiedError\n}", "func (e *APIError) Code() int {\n\treturn e.code\n}", "func (e RespError) Code() int {\n\treturn e.code\n}", "func (*SecureValueErrorFile) TypeID() uint32 {\n\treturn SecureValueErrorFileTypeID\n}", "func (ErrorEvent) Type() EventType {\n\treturn EventError\n}", "func (fe *ErrorException) Type() reflect.Type {\n\treturn fe.typ\n}", "func (e *ArgsError) Code() int {\n\treturn e.errorCode\n}", "func (o *GetRuleTypesNotFound) Code() int {\n\treturn 404\n}", "func (e SMTAlignmentError) Type() string {\n\treturn ErrorSMTAlignment\n}", "func Code(err error) codes.Code {\n\tif err == nil {\n\t\treturn codes.OK\n\t}\n\n\tif code, ok := lookupCode(err); ok {\n\t\treturn code\n\t}\n\n\tvar grpcErr GRPCStatuser\n\n\tswitch {\n\tcase errors.As(err, &grpcErr):\n\t\treturn grpcErr.GRPCStatus().Code()\n\tcase errors.Is(err, context.DeadlineExceeded):\n\t\treturn codes.DeadlineExceeded\n\tcase errors.Is(err, context.Canceled):\n\t\treturn codes.Canceled\n\tdefault:\n\t\treturn CodeFromHTTPStatus(merry.HTTPCode(err))\n\t}\n}", "func (o *GetRuleTypesOK) Code() int {\n\treturn 200\n}", "func (*SecureValueErrorSelfie) TypeID() uint32 {\n\treturn SecureValueErrorSelfieTypeID\n}", "func (*SecureValueError) TypeName() string {\n\treturn \"secureValueError\"\n}", "func (err *BatchError) Code() string {\n\treturn err.code\n}", "func codeFrom(err error) int {\n\tswitch err {\n\tcase ErrNotFound:\n\t\treturn http.StatusNotFound\n\tcase ErrAlreadyExists:\n\t\treturn http.StatusConflict\n\tcase ErrUnauthorized:\n\t\treturn http.StatusUnauthorized\n\tdefault:\n\t\treturn http.StatusInternalServerError\n\t}\n}", "func (oe *OraErr) Code() int {\n\tif oe == nil {\n\t\treturn 0\n\t}\n\treturn oe.code\n}", "func (o *UpdateMTOPostCounselingInformationPreconditionFailed) Code() int {\n\treturn 412\n}", "func (e Errorcode) Code() codes.Code {\n\treturn e.code\n}", "func Code(err error) ErrorCode {\n\tif err == nil {\n\t\treturn \"\"\n\t}\n\te, ok := err.(*Error)\n\tif ok && e.code != \"\" {\n\t\treturn e.code\n\t}\n\tif ok && e.err != nil {\n\t\treturn Code(e.err)\n\t}\n\treturn InternalCode\n}", "func (s *SecureValueErrorFile) GetType() (value SecureValueTypeClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Type\n}", "func (*SpeechRecognitionResultError) TypeName() string {\n\treturn \"speechRecognitionResultError\"\n}", "func (b baseError) Code() string {\n\treturn b.code\n}", "func (c *CompositeError) Code() int32 {\n\treturn c.code\n}", "func code(err error) int {\n\tswitch errors.Unwrap(err) {\n\tcase custom.ErrBadRequest:\n\t\treturn 400\n\tcase custom.ErrUnauthorized:\n\t\treturn 401\n\tcase custom.ErrNotFound:\n\t\treturn 404\n\tcase custom.ErrConflict:\n\t\treturn 409\n\tcase custom.ErrInternalServer:\n\t}\n\n\treturn 500\n}", "func (s *SecureValueError) GetType() (value SecureValueTypeClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Type\n}", "func (s *SecureValueErrorSelfie) GetType() (value SecureValueTypeClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Type\n}", "func Code(err error) codes.Code {\n\t// Don't use FromError to avoid allocation of OK status.\n\tif err == nil {\n\t\treturn codes.OK\n\t}\n\tif se, ok := err.(interface {\n\t\tGRPCStatus() *Status\n\t}); ok {\n\t\treturn se.GRPCStatus().Code()\n\t}\n\treturn codes.Unknown\n}", "func (b *baseError) Code() ErrorCode {\n\treturn b.code\n}", "func (fe *ErrorException) GetCode() int64 {\n\treturn fe.Code\n}", "func (*SecureValueErrorFrontSide) TypeID() uint32 {\n\treturn SecureValueErrorFrontSideTypeID\n}", "func (w *withCode) Error() string { return w.cause.Error() }", "func (e *CommandError) Code() int {\n\treturn e.code\n}", "func (s *PolicyTypeAlreadyEnabledException) Code() string {\n\treturn \"PolicyTypeAlreadyEnabledException\"\n}", "func (e ConnError) Code() Errno {\n\treturn e.code\n}", "func (s *SecureValueErrorData) GetType() (value SecureValueTypeClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Type\n}", "func StatusCodeOf(err error) int {\n\terr = errors.Cause(err)\n\tswitch v := err.(type) {\n\tcase interface {\n\t\tCode() int\n\t}:\n\t\treturn v.Code()\n\tcase *runtime.APIError:\n\t\treturn v.Code\n\tcase interface {\n\t\tGetPayload() *agentModels.ErrorResponse\n\t}:\n\t\tp := v.GetPayload()\n\t\tif p != nil {\n\t\t\treturn int(p.Status)\n\t\t}\n\tcase interface {\n\t\tGetPayload() *scylla2Models.ErrorModel\n\t}:\n\t\tp := v.GetPayload()\n\t\tif p != nil {\n\t\t\treturn int(p.Code)\n\t\t}\n\t}\n\treturn 0\n}", "func errorCode(err error) codes.Code {\n\tswitch errors.Unwrap(err) {\n\tcase context.DeadlineExceeded:\n\t\treturn codes.DeadlineExceeded\n\n\tcase context.Canceled:\n\t\treturn codes.Canceled\n\n\tdefault:\n\t\treturn grpc.Code(err)\n\t}\n}", "func (c *ConstraintError) Code() int {\n\treturn c.httpCode\n}", "func StatusCode(err error) int {\n\tif err == nil {\n\t\treturn 0\n\t}\n\tif code, ok := LookupStatusCoder(err); ok {\n\t\treturn code\n\t}\n\treturn 1\n}", "func (s *InvalidResourceTypeException) Code() string {\n\treturn \"InvalidResourceTypeException\"\n}", "func (s *PolicyTypeNotEnabledException) Code() string {\n\treturn \"PolicyTypeNotEnabledException\"\n}", "func (e *ErrorImpl) Code() int {\n\treturn e.ErrorCode\n}", "func (*SecureValueErrorTranslationFile) TypeID() uint32 {\n\treturn SecureValueErrorTranslationFileTypeID\n}", "func Code(err error) string {\n\tif err == nil {\n\t\treturn \"\"\n\t}\n\n\tif e, ok := err.(*Error); ok && e.Code != \"\" {\n\t\treturn e.Code\n\t} else if ok && e.Err != nil {\n\t\treturn Code(e.Err)\n\t}\n\n\treturn EINTERNAL\n}", "func (s *AuthorizationErrorException) Code() string {\n\treturn \"AuthorizationErrorException\"\n}", "func (s *MaximumResultReturnedException) Code() string {\n\treturn \"MaximumResultReturnedException\"\n}", "func (e *GalaxyBaseError) GetCode() int {\n\treturn e.Code\n}", "func (e *MediatorError) GetType() ErrorType {\n\treturn e.Type\n}", "func (s *ConnectorFailureException) Code() string {\n\treturn \"ConnectorFailureException\"\n}", "func (*StatsGraphError) TypeName() string {\n\treturn \"statsGraphError\"\n}", "func (e *AuthError) Code() int {\n\treturn e.httpCode\n}", "func err2code(err error) int {\n\tswitch err {\n\n\t}\n\treturn http.StatusInternalServerError\n}", "func (s *InternalErrorException) Code() string {\n\treturn \"WAFInternalErrorException\"\n}", "func (s *ServiceLinkedRoleErrorException) Code() string {\n\treturn \"WAFServiceLinkedRoleErrorException\"\n}", "func (s *ConflictErrorException) Code() string {\n\treturn \"ConflictErrorException\"\n}", "func (s *SecureValueErrorFiles) GetType() (value SecureValueTypeClass) {\n\tif s == nil {\n\t\treturn\n\t}\n\treturn s.Type\n}", "func (s *codedError) Code() ErrorCode {\n\treturn s.code\n}", "func _error(ptr uint32, size uint32)", "func (e *Error) GetCode() int {\n\treturn e.Code\n}", "func (se StatusError) Status() int {\n\treturn se.Code\n}", "func (se StatusError) Status() int {\n\treturn se.Code\n}", "func (se StatusError) Status() int {\n\treturn se.Code\n}", "func (e *NotFoundError) GetCode() int { return e.Code }", "func createError(errorType int, errorMsg string) Uint32_t {\n\tmsg := C.CString(errorMsg)\n\terr := C.create_error(C.jerry_error_t(errorType), msg)\n\tdefer C.free(unsafe.Pointer(msg))\n\treturn jerry_value_t_To_uint32_t(err)\n}", "func (r requestError) StatusCode() int {\n\treturn r.statusCode\n}", "func (ec ErrCode) Int() int { return int(ec.code) }", "func err2code(err error) int {\n\treturn http1.StatusInternalServerError\n}", "func err2code(err error) int {\n\treturn http1.StatusInternalServerError\n}", "func err2code(err error) int {\n\treturn http1.StatusInternalServerError\n}", "func (s *PolicyTypeNotAvailableForOrganizationException) Code() string {\n\treturn \"PolicyTypeNotAvailableForOrganizationException\"\n}", "func (o *ModelError) GetType() string {\n\tif o == nil || IsNil(o.Type) {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Type\n}" ]
[ "0.7239215", "0.69355285", "0.6790697", "0.6769979", "0.6738479", "0.6703321", "0.65883523", "0.65482336", "0.65214795", "0.65111333", "0.65009737", "0.64951015", "0.6492665", "0.6491025", "0.6486064", "0.64840394", "0.6480053", "0.6464054", "0.6399251", "0.6354011", "0.63447046", "0.6340882", "0.63379663", "0.6334004", "0.62990505", "0.6249056", "0.62156326", "0.6212627", "0.6212395", "0.6209576", "0.6187388", "0.61396694", "0.6136642", "0.6131861", "0.61138433", "0.60905284", "0.6088291", "0.6059474", "0.60573775", "0.60554004", "0.6053348", "0.60412914", "0.6023979", "0.60223126", "0.6019718", "0.601551", "0.59973997", "0.59866524", "0.5985", "0.59800243", "0.5975483", "0.5972744", "0.5966255", "0.59640944", "0.59580016", "0.59507823", "0.59420496", "0.5938509", "0.59333485", "0.5927712", "0.59137833", "0.5910654", "0.59010535", "0.589945", "0.5897102", "0.58968073", "0.5893658", "0.58707714", "0.58702976", "0.5869198", "0.58650094", "0.5863571", "0.5853359", "0.5846628", "0.58444935", "0.5844025", "0.5839908", "0.5836579", "0.5829435", "0.58223355", "0.58193386", "0.5818769", "0.5816188", "0.5812304", "0.5809999", "0.5799668", "0.5792243", "0.57828283", "0.5781062", "0.5781062", "0.5781062", "0.5778982", "0.5769702", "0.57678235", "0.576547", "0.576026", "0.576026", "0.576026", "0.5759846", "0.5757036" ]
0.7796923
0
Exists determines if the ComponentOrderProcess exists in the database.
func (cop *ComponentOrderProcess) Exists() bool { //component_order_process return cop._exists }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (od *OrderDetail) Exists() bool {\n\treturn od._exists\n}", "func (og *OrderGood) Exists() bool { //order_goods\n\treturn og._exists\n}", "func (yom *YhOrderMaster) Exists() bool {\n\treturn yom._exists\n}", "func (q vendorQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if vendors exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (s *SystemService) Exists() bool {\n\t_, err := runScCommand(\"queryex\", fmt.Sprintf(\"\\\"%s\\\"\", s.Command.Name))\n\n\tif err != nil {\n\t\tlogger.Log(\"exists service error: \", err)\n\t\t// Service does not exist\n\t\t// if strings.Contains(err.Error(), \"FAILED 1060\") {\n\t\t// return false\n\t\t// }\n\t\treturn false\n\t}\n\n\treturn true\n}", "func (cq *CartQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := cq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn cq.sqlExist(ctx)\n}", "func (r *ModuleStore) Exists(ctx context.Context, module, vsn string) bool {\n\tresult := models.Module{}\n\tquery := r.conn.Where(\"module = ?\", module).Where(\"version = ?\", vsn)\n\tcount, err := query.Count(&result)\n\n\treturn err == nil && count > 0\n}", "func (xpcgi *XPriCompGroupItem) Exists() bool {\n\treturn xpcgi._exists\n}", "func (q paymentObjectQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if payment_objects exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q cmfPaidprogramCommentQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_paidprogram_comment exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (epdq *EquipmentPortDefinitionQuery) Exist(ctx context.Context) (bool, error) {\n\treturn epdq.sqlExist(ctx)\n}", "func (q instrumentClassQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func ProcessExists(pid int) bool {\n\treturn nil == syscall.Kill(pid, 0)\n}", "func VendorExists(ctx context.Context, exec boil.ContextExecutor, iD int) (bool, error) {\n\tvar exists bool\n\tsql := \"select exists(select 1 from `vendors` where `id`=? limit 1)\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, iD)\n\t}\n\n\trow := exec.QueryRowContext(ctx, sql, iD)\n\n\terr := row.Scan(&exists)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: unable to check if vendors exists\")\n\t}\n\n\treturn exists, nil\n}", "func (mvq *ModuleVersionQuery) Exist(ctx context.Context) (bool, error) {\n\treturn mvq.sqlExist(ctx)\n}", "func (p *Payment) Exists() bool {\n\treturn p._exists\n}", "func Exists(client *occlient.Client, componentName, applicationName, projectName string) (bool, error) {\n\tcomponentList, err := List(client, applicationName, projectName)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"unable to get the component list\")\n\t}\n\tfor _, component := range componentList {\n\t\tif component.Name == componentName {\n\t\t\treturn true, nil\n\t\t}\n\t}\n\treturn false, nil\n}", "func (ecpq *EntityContactPointQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := ecpq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn ecpq.sqlExist(ctx)\n}", "func (q stockQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (pq *PrizeQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := pq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn pq.sqlExist(ctx)\n}", "func (q vspQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if vsp exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q instrumentClassQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if instrument_class exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q organismQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (hq *HarborQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := hq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn hq.sqlExist(ctx)\n}", "func (gou *GroupOrderdUser) Exists() bool {\n\treturn gou._exists\n}", "func (vq *VehicleQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := vq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn vq.sqlExist(ctx)\n}", "func (q phenotypepropQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"chado: failed to check if phenotypeprop exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (fdq *FurnitureDetailQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := fdq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn fdq.sqlExist(ctx)\n}", "func (q inventoryQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q stockCvtermQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func ComponentExists(client kclient.ClientInterface, name string, app string) (bool, error) {\n\tdeployment, err := client.GetOneDeployment(name, app)\n\tif _, ok := err.(*kclient.DeploymentNotFoundError); ok {\n\t\tklog.V(2).Infof(\"Deployment %s not found for belonging to the %s app \", name, app)\n\t\treturn false, nil\n\t}\n\treturn deployment != nil, err\n}", "func (q transactionQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q transactionQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func PaymentObjectExists(ctx context.Context, exec boil.ContextExecutor, iD int) (bool, error) {\n\tvar exists bool\n\tsql := \"select exists(select 1 from `payment_objects` where `id`=? limit 1)\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, iD)\n\t}\n\trow := exec.QueryRowContext(ctx, sql, iD)\n\n\terr := row.Scan(&exists)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: unable to check if payment_objects exists\")\n\t}\n\n\treturn exists, nil\n}", "func (q organismQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"chado: failed to check if organism exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q assetQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (bcq *BaselineClassQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := bcq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn bcq.sqlExist(ctx)\n}", "func (sq *ShopQuery) Exist(ctx context.Context) (bool, error) {\n\treturn sq.sqlExist(ctx)\n}", "func OrganismExists(exec boil.Executor, organismID int) (bool, error) {\n\tvar exists bool\n\n\tsql := \"select exists(select 1 from \\\"organism\\\" where \\\"organism_id\\\"=$1 limit 1)\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, organismID)\n\t}\n\n\trow := exec.QueryRow(sql, organismID)\n\n\terr := row.Scan(&exists)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"chado: unable to check if organism exists\")\n\t}\n\n\treturn exists, nil\n}", "func (q shelfQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q jobQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if jobs exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (biq *BankItemQuery) Exist(ctx context.Context) (bool, error) {\n\treturn biq.sqlExist(ctx)\n}", "func StockExistsP(exec boil.Executor, stockID int) bool {\n\te, err := StockExists(exec, stockID)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q assetRevisionQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (liq *LineItemQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := liq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn liq.sqlExist(ctx)\n}", "func (q currencyQuery) Exists(exec boil.Executor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if currency exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (dcc *DoorCompiledContent) Exists() bool {\n\treturn dcc._exists\n}", "func (irq *InstanceRuntimeQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := irq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn irq.sqlExist(ctx)\n}", "func (q jetQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func Exists(home string) bool {\n\tpidPath := filepath.Join(home, syncthingPidFile)\n\tpid, err := getPID(pidPath)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\tprocess, err := ps.FindProcess(pid)\n\tif process == nil && err == nil {\n\t\treturn false\n\t}\n\n\tif err != nil {\n\t\tlog.Infof(\"error when looking up the process: %s\", err)\n\t\treturn true\n\t}\n\n\tlog.Debugf(\"found %s pid-%d ppid-%d\", process.Executable(), process.Pid(), process.PPid())\n\n\tif process.Executable() == binaryName {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func TestIsProcessExists(t *testing.T) {\n\tcmd := exec.Command(\"cmd\", \"timeout\", \"5\")\n\terr := cmd.Start()\n\tassert.NoError(t, err)\n\tpid := cmd.Process.Pid\n\tppid := os.Getpid()\n\n\tprocesses, err := getProcess()\n\tfound := false\n\tfor _, process := range processes {\n\t\tif process.Pid == pid && process.PPid == ppid {\n\t\t\tfound = true\n\t\t}\n\t}\n\n\tassert.True(t, found)\n}", "func (gq *GoodsQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := gq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn gq.gremlinExist(ctx)\n}", "func (eq *EntityQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := eq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn eq.sqlExist(ctx)\n}", "func (q cmfFamiliesPolicyQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_families_policies exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q boardsSectionsPositionQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"rdb: failed to check if boards_sections_positions exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (c *Commentmetum) Exists() bool {\n\treturn c._exists\n}", "func (q phenotypepropQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q featureCvtermDbxrefQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q mempoolBinQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if mempool_bin exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q projectQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if project exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (fs *FactorySale) Exists() bool { //factory_sale\n\treturn fs._exists\n}", "func (ouq *OrgUnitQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := ouq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn ouq.sqlExist(ctx)\n}", "func (rq *ReceiptQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := rq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn rq.sqlExist(ctx)\n}", "func (q cmfSlideItemQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_slide_item exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (s *Database) Exists() bool {\n\t_, err := os.Stat(s.dbFile)\n\treturn err == nil\n}", "func (q storeQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if stores exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func OrganismExistsP(exec boil.Executor, organismID int) bool {\n\te, err := OrganismExists(exec, organismID)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (p Plugin) Exists(ctx context.Context, module string, version string) (bool, error) {\n\tresp, err := p.c.Exists(ctx, &stpb.ExistsRequest{Module: module, Version: version})\n\tif err != nil {\n\t\treturn false, err\n\t}\n\treturn resp.GetExists(), nil\n}", "func (mfgcsc *MidFactoryGoodsCategoryServiceCharge) Exists() bool { //mid_factory_goods_category_service_charge\n\treturn mfgcsc._exists\n}", "func (oupq *OrgUnitPositionQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := oupq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn oupq.sqlExist(ctx)\n}", "func (q cmfBalanceChargeAdminQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_balance_charge_admin exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q stockQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if stock exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (s *SpendJournalPruner) DependencyExists(blockHash *chainhash.Hash) bool {\n\ts.dependentsMtx.RLock()\n\tdefer s.dependentsMtx.RUnlock()\n\n\t_, ok := s.dependents[*blockHash]\n\treturn ok\n}", "func (m *Manager) Exists(globalID string) bool {\n\tcount, _ := m.collection.Find(bson.M{\"globalid\": globalID}).Count()\n\n\treturn count == 1\n}", "func (xpss *XPipelineSalesStage) Exists() bool {\n\treturn xpss._exists\n}", "func (ust *UsersShopTrace) Exists() bool { //users_shop_trace\n\treturn ust._exists\n}", "func (ds *DjangoSession) Exists() bool {\n\treturn ds._exists\n}", "func (cop *ComponentOrderProcess) Save(ctx context.Context) error {\n\tif cop.Exists() {\n\t\treturn cop.Update(ctx)\n\t}\n\n\treturn cop.Insert(ctx)\n}", "func (q skinQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q sourceQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q dMessageEmbedQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func StockExists(exec boil.Executor, stockID int) (bool, error) {\n\tvar exists bool\n\tsql := \"select exists(select 1 from `stock` where `stock_id`=? limit 1)\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, stockID)\n\t}\n\n\trow := exec.QueryRow(sql, stockID)\n\n\terr := row.Scan(&exists)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: unable to check if stock exists\")\n\t}\n\n\treturn exists, nil\n}", "func (q featureRelationshipQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (s *Store) Exists(key string) bool {\n\n\tif _, ok := s.objects.Load(key); ok {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (c *Customer) Exists() bool {\n\treturn c._exists\n}", "func (q cmfAdminMenuQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_admin_menu exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q cmfTurntableQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if cmf_turntable exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (o *SmsTracking) HasProcessKey() bool {\n\tif o != nil && o.ProcessKey != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (q inventoryQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if inventory exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (orderTree *OrderTree) OrderExist(key []byte, price *big.Int) bool {\n\torderList := orderTree.PriceList(price)\n\tif orderList == nil {\n\t\treturn false\n\t}\n\n\treturn orderList.OrderExist(key)\n}", "func (q buildingQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"record: failed to check if buildings exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q contentUnitDerivationQuery) Exists(exec boil.Executor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"mdbmodels: failed to check if content_unit_derivations exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q channelQuery) Exists(ctx context.Context, exec boil.ContextExecutor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRowContext(ctx, exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if channels exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q shelfQuery) Exists() (bool, error) {\n\tvar count int64\n\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow().Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if shelf exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (q commentQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q authorQuery) ExistsP() bool {\n\te, err := q.Exists()\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n\n\treturn e\n}", "func (q exchangeCurrencyQuery) Exists(exec boil.Executor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"models: failed to check if exchange_currency exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (cq *ConfirmationQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := cq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn cq.sqlExist(ctx)\n}", "func (q stockKeepingUnitContentQuery) Exists(exec boil.Executor) (bool, error) {\n\tvar count int64\n\n\tqueries.SetSelect(q.Query, nil)\n\tqueries.SetCount(q.Query)\n\tqueries.SetLimit(q.Query, 1)\n\n\terr := q.Query.QueryRow(exec).Scan(&count)\n\tif err != nil {\n\t\treturn false, errors.Wrap(err, \"db: failed to check if stock_keeping_unit_content exists\")\n\t}\n\n\treturn count > 0, nil\n}", "func (siq *SubItemQuery) Exist(ctx context.Context) (bool, error) {\n\tif err := siq.prepareQuery(ctx); err != nil {\n\t\treturn false, err\n\t}\n\treturn siq.sqlExist(ctx)\n}" ]
[ "0.6815277", "0.6516544", "0.6382645", "0.62470025", "0.6148121", "0.61335903", "0.61218596", "0.61119384", "0.60942966", "0.60522586", "0.6022795", "0.599859", "0.59836733", "0.59516937", "0.5940085", "0.5937331", "0.5904707", "0.59022367", "0.5879054", "0.58729804", "0.58585316", "0.58455235", "0.58455217", "0.5844208", "0.58114886", "0.5781195", "0.57770115", "0.5766517", "0.5759248", "0.57578504", "0.5756759", "0.57402354", "0.57402354", "0.57385", "0.5737482", "0.57360184", "0.57257926", "0.5722283", "0.5717579", "0.5704108", "0.5701671", "0.5696991", "0.5693212", "0.5688571", "0.56884605", "0.5682528", "0.5676891", "0.5676554", "0.56722087", "0.5671375", "0.5666547", "0.5661518", "0.56573313", "0.56500185", "0.56458795", "0.5644053", "0.5642902", "0.56371784", "0.5629979", "0.56248134", "0.56202054", "0.5619649", "0.56049097", "0.56038207", "0.5600504", "0.5598217", "0.55950785", "0.55932623", "0.55889946", "0.5584994", "0.5584183", "0.5583138", "0.5581495", "0.55775124", "0.55749464", "0.5568478", "0.55667037", "0.55660707", "0.5565575", "0.5563967", "0.55637366", "0.5562908", "0.5558987", "0.55586207", "0.55575806", "0.55565804", "0.55504817", "0.55482817", "0.5547959", "0.55457", "0.5540451", "0.55350274", "0.553438", "0.5527767", "0.5519719", "0.55161536", "0.5510386", "0.5506766", "0.5504945", "0.55047095" ]
0.81453544
0
Deleted provides information if the ComponentOrderProcess has been deleted from the database.
func (cop *ComponentOrderProcess) Deleted() bool { return cop._deleted }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (od *OrderDetail) Deleted() bool {\n\treturn od._deleted\n}", "func (og *OrderGood) Deleted() bool {\n\treturn og._deleted\n}", "func (xpcgi *XPriCompGroupItem) Deleted() bool {\n\treturn xpcgi._deleted\n}", "func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tcop._deleted = true\n\n\treturn nil\n}", "func (yom *YhOrderMaster) Deleted() bool {\n\treturn yom._deleted\n}", "func (mfgcsc *MidFactoryGoodsCategoryServiceCharge) Deleted() bool {\n\treturn mfgcsc._deleted\n}", "func (p *Payment) Deleted() bool {\n\treturn p._deleted\n}", "func (obj *InstallPhase) IsDeleted() bool {\n\treturn obj.GetDeletionTimestamp() != nil\n}", "func (xsml *XfileServiceMetricLog) Deleted() bool {\n\treturn xsml._deleted\n}", "func (dtm *DirectToMessage) Deleted() bool {\n\treturn dtm._deleted\n}", "func (n *Notify) Deleted() bool {\n\treturn n._deleted\n}", "func (e *ExternalService) IsDeleted() bool { return !e.DeletedAt.IsZero() }", "func (xpd *XPriDim) Deleted() bool {\n\treturn xpd._deleted\n}", "func (o *CartaoProduto) HasDeleted() bool {\n\tif o != nil && o.Deleted != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (dcc *DoorCompiledContent) Deleted() bool {\n\treturn dcc._deleted\n}", "func (b *base) Deleted() bool { return b.Deletedx }", "func (c *Customer) Deleted() bool {\n\treturn c._deleted\n}", "func (fr *FetchResult) Deleted() bool {\n\treturn fr._deleted\n}", "func (gou *GroupOrderdUser) Deleted() bool {\n\treturn gou._deleted\n}", "func (ust *UsersShopTrace) Deleted() bool {\n\treturn ust._deleted\n}", "func (ds *DjangoSession) Deleted() bool {\n\treturn ds._deleted\n}", "func (gc *GoodsCategory) Deleted() bool {\n\treturn gc._deleted\n}", "func (o *Order) Delete() error {\n\tif o.State != Empty && o.State != Ongoing {\n\t\treturn fmt.Errorf(\"order in wrong state\")\n\t}\n\to.TrackChange(o, &Deleted{})\n\treturn nil\n}", "func (c *Cliente) Deleted() bool {\n\treturn c._deleted\n}", "func (em *EndingMessage) Deleted() bool {\n\treturn em._deleted\n}", "func (ag *AgentGroup) Deleted() bool {\n\treturn ag._deleted\n}", "func (a *Activity) Deleted() bool {\n\treturn a._deleted\n}", "func (xpss *XPipelineSalesStage) Deleted() bool {\n\treturn xpss._deleted\n}", "func (dag *DdgAdminGroup) Deleted() bool {\n\treturn dag._deleted\n}", "func (r Record) Deleted() bool {\n\treturn r.deleted\n}", "func (obj *DeletePhase) IsDeleted() bool {\n\treturn obj.GetDeletionTimestamp() != nil\n}", "func (o *CartaoProduto) GetDeleted() int32 {\n\tif o == nil || o.Deleted == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Deleted\n}", "func (c *Comment) Deleted() bool {\n\treturn c._deleted\n}", "func (o *CartaoProduto) GetDeletedOk() (*int32, bool) {\n\tif o == nil || o.Deleted == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Deleted, true\n}", "func (obj *ECDSCluster) IsDeleted() bool {\n\treturn obj.GetDeletionTimestamp() != nil\n}", "func (t *Testzzz) Deleted() bool {\n\treturn t._deleted\n}", "func (a *Actor) Deleted() bool {\n\treturn a._deleted\n}", "func (o *CompartimentoHistorico) HasDeleted() bool {\n\tif o != nil && o.Deleted != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func WasDeleted(o metav1.Object) bool {\n\treturn !o.GetDeletionTimestamp().IsZero()\n}", "func (dct *DjangoContentType) Deleted() bool {\n\treturn dct._deleted\n}", "func (c *ClusterInstallation) IsDeleted() bool {\n\treturn c.DeleteAt != 0\n}", "func (b *Book) Deleted() bool {\n\treturn b._deleted\n}", "func (xetd *XEmailTemplateDtl) Deleted() bool {\n\treturn xetd._deleted\n}", "func (s *Syslog) Deleted() bool {\n\treturn s._deleted\n}", "func (m *Meme) Deleted() bool {\n\treturn m._deleted\n}", "func (qc *QueueConfig) Deleted() bool {\n\treturn qc._deleted\n}", "func (s *State) Deleted() bool {\n\treturn s._deleted\n}", "func (od *OrderDetail) Delete(ctx context.Context, db DB) error {\n\tswitch {\n\tcase !od._exists: // doesn't exist\n\t\treturn nil\n\tcase od._deleted: // deleted\n\t\treturn nil\n\t}\n\t// delete with composite primary key\n\tconst sqlstr = `DELETE FROM northwind.order_details ` +\n\t\t`WHERE order_id = ? AND product_id = ?`\n\t// run\n\tlogf(sqlstr, od.OrderID, od.ProductID)\n\tif _, err := db.ExecContext(ctx, sqlstr, od.OrderID, od.ProductID); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set deleted\n\tod._deleted = true\n\treturn nil\n}", "func (fs *FactorySale) Deleted() bool {\n\treturn fs._deleted\n}", "func (lm *LeaveMessage) Deleted() bool {\n\treturn lm._deleted\n}", "func Deleted(c *routing.Context, msg string, service string) error {\n\tResponse(c, `{\"error\": false, \"msg\": \"`+msg+`\"}`, 200, service, \"application/json\")\n\treturn nil\n}", "func (r *Repo) IsDeleted() bool { return !r.DeletedAt.IsZero() }", "func (hr *HelpRequest) Deleted() bool {\n\treturn hr._deleted\n}", "func (ag *AuthGroup) Deleted() bool {\n\treturn ag._deleted\n}", "func (wj *WsubJob) Deleted() bool {\n\treturn wj._deleted\n}", "func (oee *OtxEpubEpub) Deleted() bool {\n\treturn oee._deleted\n}", "func (xcu *XCatalogUser) Deleted() bool {\n\treturn xcu._deleted\n}", "func (i *MockDataItem) IsDeleted() bool {\n\treturn i.Deleted\n}", "func (sc *ScCategory) Deleted() bool {\n\treturn sc._deleted\n}", "func (m *TestModel) IsDeleted() bool {\n\treturn m.Deleted\n}", "func (o *CompartimentoHistorico) GetDeleted() int32 {\n\tif o == nil || o.Deleted == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Deleted\n}", "func (h *Handler) ObjectDeleted(obj interface{}) (bool, string) {\n\treturn true, \"\"\n}", "func (og *OrderGood) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif og._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetOrderGoodTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE order_gid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, og.OrderGid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, og.OrderGid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, og.OrderGid)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tog._deleted = true\n\n\treturn nil\n}", "func (st *SetTranslation) Deleted() bool {\n\treturn st._deleted\n}", "func (bb *BooktestBook) Deleted() bool {\n\treturn bb._deleted\n}", "func (p *ProcessDefinition) Delete(by QueryProcessDefinitionBy, query map[string]string) error {\n\terr := p.client.doDelete(\"/process-definition/\"+by.String(), query)\n\treturn err\n}", "func (o *CompartimentoHistorico) GetDeletedOk() (*int32, bool) {\n\tif o == nil || o.Deleted == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Deleted, true\n}", "func (tttp *TriageTimeTableProvider) Deleted() bool {\n\treturn tttp._deleted\n}", "func (a API) Deleted(data interface{}) (int, model.MessageResponse) {\n\treturn http.StatusOK, model.MessageResponse{\n\t\tData: data,\n\t\tMessages: model.Responses{{Code: RecordDeleted, Message: \"¡listo!\"}},\n\t}\n}", "func (i *MockOtherDataItem) IsDeleted() bool {\n\treturn i.Deleted\n}", "func (hd *HelpDoc) Deleted() bool {\n\treturn hd._deleted\n}", "func (o DeprecationStatusOutput) Deleted() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v DeprecationStatus) *string { return v.Deleted }).(pulumi.StringPtrOutput)\n}", "func (e *Entry) IsDeleted() bool {\n\treturn e.Latest().GetTombstone()\n}", "func (process *Process) Delete() {\n\tsql := \"DELETE FROM `process` WHERE id=?\"\n\tquery, err := database.Connection.Prepare(sql)\n\tif err != nil {\n\t\tfmt.Println(\"Delete #1 error for process:\")\n\t\tfmt.Println(err)\n\t}\n\tquery.Exec(process.Action.ID)\n}", "func (o *Permissao) HasDeleted() bool {\n\tif o != nil && o.Deleted != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func (owwb *OtxWeblinkWeblinkBasket) Deleted() bool {\n\treturn owwb._deleted\n}", "func (m *CommunicationsDAO) Delete(communication Communication) error {\n\terr := db.C(COLLECTION).Remove(&communication)\n\treturn err\n}", "func (level DepthOfMarketLevel) IsDeleted() bool {\n\treturn level.GetQty() == 0\n}", "func (r *Room) Deleted() bool {\n\treturn r._deleted\n}", "func (wu *WsubUpdate) Deleted() bool {\n\treturn wu._deleted\n}", "func (domainCertificate *SSLDomainCertificate) IsDeleted() bool {\n\treturn domainCertificate == nil\n}", "func (xpcgi *XPriCompGroupItem) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpcgi._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif xpcgi._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM x_showroom.x_pri_comp_group_item WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.ID)\n\t_, err = db.Exec(sqlstr, xpcgi.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\txpcgi._deleted = true\n\n\treturn nil\n}", "func (at *AuthtokenToken) Deleted() bool {\n\treturn at._deleted\n}", "func (e Elem) Deleted() bool {\n\t_, ok := e.Peer.(*tg.InputPeerEmpty)\n\treturn ok\n}", "func (s *Set) Deleted() bool {\n\treturn s._deleted\n}", "func (o *Permissao) GetDeleted() int32 {\n\tif o == nil || o.Deleted == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Deleted\n}", "func (m *Metadata) IsDeleted() bool {\n\treturn (strings.ToLower(m.Tag) == MetadataTypeDeleted)\n}", "func (d *Deletable) IsDeleted() bool {\n\treturn d.Deleted\n}", "func (t *Territory) Deleted() bool {\n\treturn t._deleted\n}", "func (s *Subtitle) IsDeleted() bool {\n\treturn s.Num == -1\n}", "func (o *Notification) Delete(exec boil.Executor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Notification provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), notificationPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"notification\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\tresult, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from notification\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for notification\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (pde ProcessDeactivatedEvent) AsServiceDeletedEvent() (*ServiceDeletedEvent, bool) {\n\treturn nil, false\n}", "func (p *Process) deleteProcess() error {\n\tif p.command == nil || p.command.Process == nil {\n\t\treturn nil\n\t}\n\n\t// Close the process watcher\n\tif p.cancelChan != nil {\n\t\tclose(p.cancelChan)\n\t}\n\n\tp.log.Debugf(\"Process %s deleted\", p.name)\n\treturn nil\n}", "func (o *PaymentObject) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no PaymentObject provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), paymentObjectPrimaryKeyMapping)\n\tsql := \"DELETE FROM `payment_objects` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from payment_objects\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for payment_objects\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (o DeprecationStatusResponseOutput) Deleted() pulumi.StringOutput {\n\treturn o.ApplyT(func(v DeprecationStatusResponse) string { return v.Deleted }).(pulumi.StringOutput)\n}", "func (program Program) GetDeleteStatus() bool {\n\tvar params int32\n\tgl.GetProgramiv(uint32(program), gl.DELETE_STATUS, &params)\n\treturn params == gl.TRUE\n}", "func (dau *DdgAdminUser) Deleted() bool {\n\treturn dau._deleted\n}", "func (l *Notifier) Deleted(c *config.KdnConfig, msg string) error {\n\tc.Logger.Infof(\"Deleted: %s\", msg)\n\treturn nil\n}", "func (c *Commentmetum) Deled() bool {\n\treturn c._deleted\n}", "func (o *Permissao) GetDeletedOk() (*int32, bool) {\n\tif o == nil || o.Deleted == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Deleted, true\n}" ]
[ "0.6923346", "0.6851326", "0.6707838", "0.6576038", "0.65400237", "0.6410486", "0.6311445", "0.62597555", "0.6230671", "0.6225509", "0.6225233", "0.620538", "0.6162343", "0.6124854", "0.60879046", "0.60598934", "0.6035882", "0.60238445", "0.59948397", "0.59944844", "0.5989773", "0.59592396", "0.5944415", "0.5923339", "0.5915106", "0.5912548", "0.59029555", "0.58733237", "0.5869529", "0.5848666", "0.58363014", "0.58323216", "0.58162254", "0.57865196", "0.57668245", "0.57453233", "0.5740861", "0.5732936", "0.571685", "0.57150656", "0.56947523", "0.5694558", "0.56833655", "0.5672821", "0.5671952", "0.56670254", "0.5661371", "0.56444126", "0.5642303", "0.5636739", "0.5633862", "0.56260127", "0.56244266", "0.56210524", "0.56134", "0.5609319", "0.5592785", "0.5554632", "0.5536858", "0.5535629", "0.55289936", "0.55211884", "0.5504416", "0.55016315", "0.5494106", "0.5482336", "0.5470585", "0.5433852", "0.54329056", "0.5427962", "0.54210585", "0.5406296", "0.5404744", "0.54046655", "0.540206", "0.5388443", "0.5386734", "0.5377954", "0.53709507", "0.5366667", "0.5361885", "0.5360865", "0.53567153", "0.53526413", "0.5351106", "0.5349841", "0.5341024", "0.5338601", "0.5325703", "0.53233653", "0.53106356", "0.5309413", "0.53072333", "0.5300977", "0.5300807", "0.5271693", "0.526751", "0.525556", "0.5253536", "0.52427816" ]
0.786496
0
Insert inserts the ComponentOrderProcess to the database.
func (cop *ComponentOrderProcess) Insert(ctx context.Context, key ...interface{}) error { var err error var dbConn *sql.DB var res sql.Result // if already exist, bail if cop._exists { return errors.New("insert failed: already exists") } tx, err := components.M.GetConnFromCtx(ctx) if err != nil { dbConn, err = components.M.GetMasterConn() if err != nil { return err } } tableName, err := GetComponentOrderProcessTableName(key...) if err != nil { return err } // sql insert query, primary key provided by autoincrement sqlstr := `INSERT INTO ` + tableName + ` (` + `orderid, event, do_status, access_url, remark, created_at, updated_at` + `) VALUES (` + `?, ?, ?, ?, ?, ?, ?` + `)` // run query utils.GetTraceLog(ctx).Debug("DB", zap.String("SQL", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt))) if err != nil { return err } if tx != nil { res, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt) } else { res, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt) } if err != nil { return err } // retrieve id id, err := res.LastInsertId() if err != nil { return err } // set primary key and existence cop.ID = uint(id) cop._exists = true return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (r *Repository) InsertOrder(data *Order) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func (r *Repository) InsertOrderItem(data *OrderItem) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func (od *OrderDetail) Insert(ctx context.Context, db DB) error {\n\tswitch {\n\tcase od._exists: // already exists\n\t\treturn logerror(&ErrInsertFailed{ErrAlreadyExists})\n\tcase od._deleted: // deleted\n\t\treturn logerror(&ErrInsertFailed{ErrMarkedForDeletion})\n\t}\n\t// insert (manual)\n\tconst sqlstr = `INSERT INTO northwind.order_details (` +\n\t\t`order_id, product_id, unit_price, quantity, discount` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?` +\n\t\t`)`\n\t// run\n\tlogf(sqlstr, od.OrderID, od.ProductID, od.UnitPrice, od.Quantity, od.Discount)\n\tif _, err := db.ExecContext(ctx, sqlstr, od.OrderID, od.ProductID, od.UnitPrice, od.Quantity, od.Discount); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set exists\n\tod._exists = true\n\treturn nil\n}", "func (pm *ProductModel) Insert(product Product) error {\n\tif _, err := pm.DB.Exec(INSERT_PRODUCT_STMT, product.ProductName, product.Price, product.ShortDescription); err != nil {\n\t\tlog.Printf(\"error occured on inserting product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (cop *ComponentOrderProcess) Save(ctx context.Context) error {\n\tif cop.Exists() {\n\t\treturn cop.Update(ctx)\n\t}\n\n\treturn cop.Insert(ctx)\n}", "func (pkg *Package) Insert(ctx context.Context, db *sqlx.DB) error {\n\tnow := helper.CurrentUTC()\n\tpkg.CreatedAt = now\n\tpkg.UpdatedAt = now\n\tquery := `\nINSERT INTO packages(domain_id, private, path, vcs, root, docs, description, homepage, license, created_at, updated_at)\nVALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n`\n\tres, err := db.ExecContext(ctx, query, pkg.DomainID, pkg.Private, pkg.Path, pkg.VCS, pkg.Root, pkg.Docs, pkg.Description, pkg.Homepage, pkg.License, now, now)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpkg.ID, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *CommunicationsDAO) Insert(communication Communication) error {\n\terr := db.C(COLLECTION).Insert(&communication)\n\treturn err\n}", "func (p *Project) Insert(session *xorm.Session) (int, error) {\n\taffected, err := session.Insert(p)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn 0, err\n\t}\n\treturn int(affected), nil\n}", "func (og *OrderGood) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif og._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetOrderGoodTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, pid, gid, title, allprice, prepay_price, price, number, shipping, goods_updated, comment, uid, refund_nums, next, note_user, stock_id, shareid, from_uid, activity_id, goods_origin_fee, real_settlement_fee, refund_fee` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tog.OrderGid = int(id)\n\tog._exists = true\n\n\treturn nil\n}", "func (b *Build) Insert() error {\n\treturn db.Insert(Collection, b)\n}", "func (o *Order) Insert() (code int, err error) {\n mConn := mymongo.Conn()\n defer mConn.Close()\n\n c := mConn.DB(\"\").C(DBTableOrder)\n\n err = c.Insert(o)\n if err != nil {\n if mgo.IsDup(err) {\n code = ErrDupRows\n } else {\n code = ErrDatabase\n }\n } else {\n code = 0\n }\n\n return\n}", "func (xpcgi *XPriCompGroupItem) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif xpcgi._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO x_showroom.x_pri_comp_group_item (` +\n\t\t`name, display_name, type_cd, primary_flag, seq_num, x_pri_comp_group_id, created_by, updated_by, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt)\n\tres, err := db.Exec(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\txpcgi.ID = uint(id)\n\txpcgi._exists = true\n\n\treturn nil\n}", "func (orderTree *OrderTree) InsertOrder(quote map[string]string) error {\n\n\t// orderID := ToBigInt(quote[\"order_id\"])\n\t// key := GetKeyFromBig(orderID)\n\n\t// if orderTree.OrderExist(key) {\n\t// \t// orderTree.RemoveOrderByID(key)\n\t// \tfmt.Println(\"Order already exsited, do nothing or should remove it?\")\n\t// \treturn\n\t// }\n\n\tprice := ToBigInt(quote[\"price\"])\n\n\tvar orderList *OrderList\n\n\tif !orderTree.PriceExist(price) {\n\t\t// create and save\n\t\tfmt.Println(\"CREATE price list\", price.String())\n\t\torderList = orderTree.CreatePrice(price)\n\t} else {\n\t\torderList = orderTree.PriceList(price)\n\t}\n\n\t// order will be insert if there is a follow orderList key\n\tif orderList != nil {\n\n\t\torder := NewOrder(quote, orderList.Key)\n\n\t\tif orderList.OrderExist(order.Key) {\n\t\t\t// orderTree.RemoveOrderByID(key)\n\t\t\torderTree.RemoveOrder(order)\n\t\t\t// fmt.Println(\"Order already exsited, do nothing or should remove it?\")\n\t\t\t// return nil\n\t\t}\n\n\t\torderList.AppendOrder(order)\n\t\t// orderTree.OrderMap[order.OrderID] = order\n\t\torderList.Save()\n\t\torderList.SaveOrder(order)\n\t\torderTree.Item.Volume = Add(orderTree.Item.Volume, order.Item.Quantity)\n\n\t\t// increase num of orders, should be big.Int ?\n\t\torderTree.Item.NumOrders++\n\t\t// fmt.Println(\"Num order\", orderTree.Item.NumOrders)\n\t\t// update\n\t\t// should use batch to optimize the performance\n\t\treturn orderTree.Save()\n\t}\n\n\treturn nil\n}", "func (so *SQLOrderItemStore) Insert(oi *model.OrderItem) (*model.OrderItem, error) {\n\toi.OrderItemID = uuid.NewV4().String()\n\toi.CreatedAt = time.Now().UnixNano()\n\toi.UpdatedAt = oi.CreatedAt\n\terr := so.SQLStore.Tx.Insert(oi)\n\treturn oi, err\n}", "func (c *Company) Insert() error {\n\tresult := initdb.DbInstance.Create(c)\n\tlog.Println(\"Created -> \", result)\n\treturn result.Error\n}", "func (yom *YhOrderMaster) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif yom._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO devdb.yh_order_master (` +\n\t\t`id, order_time, seller_id, image_id, item_id, is_hidden_page` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, yom.ID, yom.OrderTime, yom.SellerID, yom.ImageID, yom.ItemID, yom.IsHiddenPage)\n\t_, err = db.Exec(sqlstr, yom.ID, yom.OrderTime, yom.SellerID, yom.ImageID, yom.ItemID, yom.IsHiddenPage)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tyom._exists = true\n\n\treturn nil\n}", "func (gou *GroupOrderdUser) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif gou._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO sun_chat.group_orderd_user (` +\n\t\t`OrderId, GroupId, UserId` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLog(sqlstr, gou.OrderId, gou.GroupId, gou.UserId)\n\t}\n\t_, err = db.Exec(sqlstr, gou.OrderId, gou.GroupId, gou.UserId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tgou._exists = true\n\n\tOnGroupOrderdUser_AfterInsert(gou)\n\n\treturn nil\n}", "func Insert(db *sql.DB, order Order, orderTable, itemTable string, items []Item, closedIntercal int) (uint32, error) {\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer func() {\n\t\tif err != nil {\n\t\t\terr = tx.Rollback()\n\t\t} else {\n\t\t\terr = tx.Commit()\n\t\t}\n\t}()\n\n\torder.Closed = order.Created.Add(time.Duration(closedIntercal * int(time.Hour)))\n\n\tsql := fmt.Sprintf(orderSQLString[orderInsert], orderTable)\n\n\tresult, err := db.Exec(sql, order.OrderCode, order.UserID, order.AddressID, order.TotalPrice, order.Promotion, order.Freight, order.Closed)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif affected, _ := result.RowsAffected(); affected == 0 {\n\t\treturn 0, errOrderInsert\n\t}\n\n\tID, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\torder.ID = uint32(ID)\n\n\tfor _, x := range items {\n\t\tsql := fmt.Sprintf(orderSQLString[itemInsert], itemTable)\n\n\t\tresult, err := db.Exec(sql, x.ProductID, order.ID, x.Count, x.Price, x.Discount)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif affected, _ := result.RowsAffected(); affected == 0 {\n\t\t\treturn 0, errItemInsert\n\t\t}\n\t}\n\n\treturn order.ID, nil\n}", "func (c *MySQLClient) Insert(p *purchase.Purchase) error {\n\tif p.ID != 0 {\n\t\treturn fmt.Errorf(\"purchase cannot have a preexisting ID\")\n\t}\n\n\tvar err error\n\tvar buyBytes, sellBytes []byte\n\tif p.BuyOrder != nil {\n\t\tbuyBytes, err = json.Marshal(p.BuyOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal buy order: %v\", err)\n\t\t}\n\t}\n\tif p.SellOrder != nil {\n\t\tsellBytes, err = json.Marshal(p.SellOrder)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"unable to marshal sell order: %v\", err)\n\t\t}\n\t}\n\n\tquery := `INSERT INTO trader_one(buy_order, sell_order) VALUES (?, ?)`\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFunc()\n\tstmt, err := c.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to prepare SQL statement: %v\", err)\n\t}\n\tdefer stmt.Close()\n\n\tres, err := stmt.ExecContext(ctx, jsonString(buyBytes), jsonString(sellBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to insert row: %v\", err)\n\t}\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to find new ID: %v\", err)\n\t}\n\tp.ID = id\n\treturn nil\n}", "func (r *TaskRepository) Insert(db db.DB, Task *entities.Task) error {\n\t_, err := db.NamedExec(`\n\tINSERT INTO tasks (uuid,title,user_id,status,created_at,updated_at)\n\tVALUES (:uuid, :title, :user_id, :status, now(), now())`, Task)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error inserting task to db: %w\", err)\n\t}\n\n\treturn nil\n}", "func (p *Payment) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif p._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO public.payment (` +\n\t\t`payment_id, customer_id, staff_id, rental_id, amount, payment_date` +\n\t\t`) VALUES (` +\n\t\t`$1, $2, $3, $4, $5, $6` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, p.PaymentID, p.CustomerID, p.StaffID, p.RentalID, p.Amount, p.PaymentDate)\n\terr = db.QueryRow(sqlstr, p.PaymentID, p.CustomerID, p.StaffID, p.RentalID, p.Amount, p.PaymentDate).Scan(&p.PaymentID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tp._exists = true\n\n\treturn nil\n}", "func (pc *TransformedPRCountRepository) Insert(pullRequestCount *entities.TransformedPullRequestCount) error {\n\tvar err error\n\n\tquery := \"INSERT INTO \" + transformedPullRequestCountTbl + \" (total, open, closed, date) VALUES (:total,:open,:closed,:date)\"\n\n\tif _, err = pc.Db.NamedExec(query, pullRequestCount); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (ag *AgentGroup) Insert(db XODB) error {\n\tvar err error\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO custmchat.agent_group (` +\n\t\t`id, ent_id, name, description` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, ag.ID, ag.EntID, ag.Name, ag.Description)\n\t_, err = db.Exec(sqlstr, ag.ID, ag.EntID, ag.Name, ag.Description)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *Transaction) InsertByProduct(\n\tproduct *db.Product,\n\ttrackAction *db.TrackAction,\n\tuser *db.User,\n\tcreatedByName string,\n\toptTransaction *db.Transaction,\n\ttxes ...*sqlx.Tx,\n) (*db.Transaction, error) {\n\t// sanity check\n\tif product == nil {\n\t\treturn nil, terror.New(terror.ErrInvalidInput, \"product is nil\")\n\t}\n\tif trackAction == nil {\n\t\treturn nil, terror.New(terror.ErrInvalidInput, \"tractAction is nil\")\n\t}\n\t// just incase want to be anonymous\n\tif createdByName == \"\" {\n\t\tcreatedByName = \"Anonymous\"\n\t}\n\n\tconn := prepConn(s.Conn, txes...)\n\n\t// pick time, use if provided or use now\n\ttm := time.Now()\n\tif optTransaction != nil && optTransaction.ScannedAt.Valid {\n\t\ttm = optTransaction.ScannedAt.Time\n\t}\n\n\t// init data\n\tvar t *db.Transaction\n\tif optTransaction != nil {\n\t\t// use optional transaction if provided\n\t\tt = optTransaction\n\t} else {\n\t\t// start blank transaction\n\t\tt = &db.Transaction{}\n\t}\n\n\t// fill in data (for admin use)\n\tt.ProductID = null.StringFrom(product.ID)\n\tt.TrackActionID = trackAction.ID\n\tt.CreatedByName = createdByName\n\tif user != nil && user.ID != \"\" {\n\t\tt.CreatedByID = null.StringFrom(user.ID)\n\t}\n\n\t// manifest json, to be published publicly\n\tmj := ManifestLineJSON{\n\t\tTime: &tm,\n\t\tProductID: &product.ID,\n\t\tProductCode: &product.Code,\n\t\tTractActionName: &trackAction.Name,\n\t\tEntityName: &createdByName,\n\t}\n\t// fill in data for manifest\n\t// make gps coord more private\n\tif t.LocationGeohash.Valid && len(t.LocationGeohash.String) > 0 {\n\t\tmjcord := helpers.LimitCoordinate(t.LocationGeohash.String)\n\t\tmj.Location = &mjcord\n\t}\n\t// build string\n\tmjs, err := json.Marshal(mj)\n\tif err != nil {\n\t\treturn nil, terror.New(err, \"json marshal fail\")\n\t}\n\t// copy into transaction\n\tt.ManifestLineJSON = null.StringFrom(string(mjs))\n\n\t// insert\n\terr = t.Insert(conn, boil.Infer())\n\tif err != nil {\n\t\treturn nil, terror.New(err, \"failed to insert\")\n\t}\n\n\treturn t, nil\n}", "func (c *CoursesDAO) Insert(course models.Course) error {\n\terr := db.C(COLLECTION).Insert(&course)\n\treturn err\n}", "func (m *ProductModel) ProductInsert(user Product) error {\n\terr := db.C(PRODUCT).Insert(&user)\n\treturn err\n}", "func (oms *OMS) Insert(o *order.Order) error {\n\tvar dxCash utils.Amount\n\n\tswitch o.Buy {\n\tcase true:\n\t\tdxCash = -o.Ask * o.Volume(0)\n\n\tcase false:\n\t\tdxCash = o.Bid * o.Volume(0)\n\t}\n\tif err := oms.open.Insert(o); err != nil {\n\t\treturn err\n\t}\n\toms.updateCash(dxCash)\n\treturn Port.Insert(\n\t\tinstrument.NewHolding(o.Instrument, &utils.DatedMetric{o.Ask, o.Timestamp}),\n\t\to.Quote)\n}", "func Insert(db gorp.SqlExecutor, i interface{}) error {\n\treturn Mapper.Insert(db, i)\n}", "func (c *Comment) Insert() error {\n\t_, err := orm.NewOrm().Insert(c)\n\treturn err\n}", "func (c *Conn) Insert(ctx context.Context, i Item) (err error) {\n\t_, err = c.db.Exec(ctx, \"INSERT INTO jobs (url) VALUES ($1)\", i.URL)\n\treturn\n}", "func (m *InventoryServiceModel) Insert(ids []string, location, kind, title, techname, domain, value, placement, team, resp, reg, method, port, description string) error {\n\tstmt := `INSERT INTO inventory_services (host_id, location, type, title, techname, domain, value, placement, team, resp, reg_to_consul, method_check_consul, port, description)\n\tVALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`\n\n\tfor _, v := range ids {\n\n\t\t_, err := m.DB.Exec(stmt, v, location, kind, title, techname, domain, value, placement, team, resp, reg, method, port, description)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (m *TicketDAO) Insert(ticket Ticket) error {\n\terr := db.C(COLLECTION).Insert(&ticket)\n\treturn err\n}", "func (nos *NewOrderServiceImpl) ProcessTransaction(req *models.NewOrder) (*models.NewOrderOutput, error) {\n\tlog.Printf(\"Starting the New Order Transaction for row: c=%d w=%d d=%d n=%d\", req.CustomerID, req.WarehouseID, req.DistrictID, req.UniqueItems)\n\n\tresult, err := nos.execute(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error occured while executing the new order transaction. Err: %v\", err)\n\t}\n\n\tlog.Printf(\"Completed the New Order Transaction for row: c=%d w=%d d=%d n=%d\", req.CustomerID, req.WarehouseID, req.DistrictID, req.UniqueItems)\n\treturn result, nil\n}", "func (fsm *FSM) Insert(ctx context.Context, dbc *sql.DB, inserter Inserter) (int64, error) {\n\ttx, err := dbc.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer tx.Rollback()\n\n\tid, notify, err := fsm.InsertTx(ctx, tx, inserter)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer notify()\n\n\treturn id, tx.Commit()\n}", "func InsertInstallment(c *gin.Context) {\n\trequestBody, _ := ioutil.ReadAll(c.Request.Body)\n\tvar requestObj Installment\n\tjson.Unmarshal(requestBody, &requestObj)\n\n\trequestPoint := &requestObj\n\n\tappEngine := appengine.NewContext(c.Request)\n\tkey := datastore.NewIncompleteKey(appEngine, InstallmentKey, SandboxPromotionsKey(appEngine, InstallmentKey))\n\tif _, err := datastore.Put(appEngine, key, requestPoint); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\n\t\t\t\"status_code\": http.StatusBadRequest,\n\t\t\t\"status_message\": err.Error(),\n\t\t})\n\t} else {\n\t\tc.JSON(http.StatusCreated, gin.H{\n\t\t\t\"status_code\": http.StatusCreated,\n\t\t\t\"status_message\": \"Installment created.\",\n\t\t})\n\t}\n}", "func (t *Transaction) Insert(list ...interface{}) error {\n\treturn insert(t.dbmap, t, list...)\n}", "func (dao AccountPUCDAOPsql) Insert(obj *models.AccountPUC) error {\n\tquery := \"SELECT * FROM fn_accounts_puc_insert($1, $2)\"\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\trow := stmt.QueryRow(obj.Account, obj.AccountName)\n\treturn dao.rowToObject(row, obj)\n}", "func (m ComicsModel) Insert(comics *Comics) error {\n\tquery := `INSERT INTO comics (title, year, pages)\n\t\t\tVALUES ($1, $2, $3)\n\t\t\tRETURNING id, created_at, version`\n\n\targs := []interface{}{comics.Title, comics.Year, comics.Pages}\n\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\treturn m.DB.QueryRowContext(ctx, query, args...).Scan(&comics.ID, &comics.CreatedAt, &comics.Version)\n}", "func (mfgcsc *MidFactoryGoodsCategoryServiceCharge) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif mfgcsc._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetMidFactoryGoodsCategoryServiceChargeTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`factory_id, goods_category_id, service_charge, mid_admin_id, mid_admin_name, status, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, mfgcsc.FactoryID, mfgcsc.GoodsCategoryID, mfgcsc.ServiceCharge, mfgcsc.MidAdminID, mfgcsc.MidAdminName, mfgcsc.Status, mfgcsc.CreatedAt, mfgcsc.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tmfgcsc.ID = uint(id)\n\tmfgcsc._exists = true\n\n\treturn nil\n}", "func (em *EndingMessage) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif em._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO custmchat.ending_message (` +\n\t\t`ent_id, platform, agent, system, status, prompt` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, em.EntID, em.Platform, em.Agent, em.System, em.Status, em.Prompt)\n\t_, err = db.Exec(sqlstr, em.EntID, em.Platform, em.Agent, em.System, em.Status, em.Prompt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tem._exists = true\n\n\treturn nil\n}", "func (p *Patch) Insert() error {\n\treturn db.Insert(Collection, p)\n}", "func (p *Patch) Insert() error {\n\treturn db.Insert(Collection, p)\n}", "func (r *PlacementStrategiesService) Insert(profileId int64, placementstrategy *PlacementStrategy) *PlacementStrategiesInsertCall {\n\tc := &PlacementStrategiesInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.placementstrategy = placementstrategy\n\treturn c\n}", "func (o *Transaction) InsertP(exec boil.Executor, whitelist ...string) {\n\tif err := o.Insert(exec, whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) InsertP(exec boil.Executor, whitelist ...string) {\n\tif err := o.Insert(exec, whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (c *Commentmetum) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif c._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tvar sqlstr = `INSERT INTO ` + GetTableName(\"commentmeta\") + ` (` +\n\t\t`comment_id, meta_key, meta_value` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, c.CommentID, c.MetaKey, c.MetaValue)\n\tres, err := db.Exec(sqlstr, c.CommentID, c.MetaKey, c.MetaValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tc.MetaID = uint64(id)\n\tc._exists = true\n\n\treturn nil\n}", "func (o *PaymentObject) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no payment_objects provided for insertion\")\n\t}\n\n\tvar err error\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(paymentObjectColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tpaymentObjectInsertCacheMut.RLock()\n\tcache, cached := paymentObjectInsertCache[key]\n\tpaymentObjectInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tpaymentObjectAllColumns,\n\t\t\tpaymentObjectColumnsWithDefault,\n\t\t\tpaymentObjectColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(paymentObjectType, paymentObjectMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(paymentObjectType, paymentObjectMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `payment_objects` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `payment_objects` () VALUES ()%s%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `payment_objects` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, paymentObjectPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into payment_objects\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == paymentObjectMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for payment_objects\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tpaymentObjectInsertCacheMut.Lock()\n\t\tpaymentObjectInsertCache[key] = cache\n\t\tpaymentObjectInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func (m MariaDB) Insert(ctx context.Context, document entity.PersonalData) (entity.PersonalData, error) {\n\tp := receive(document)\n\tsqlQuery := \"INSERT INTO person (id, name, last_name, phone, email, year_od_birth ) VALUES (?,?,?,?,?,?)\"\n\t_, err := m.Person.ExecContext(ctx, sqlQuery, p.ID, p.Name, p.LastName, p.Phone, p.Email, p.YearOfBirth)\n\tif err != nil {\n\t\treturn entity.PersonalData{}, errors.Wrap(err, \"could not exec query statement\")\n\t}\n\treturn document, nil\n}", "func (commit ObjectCommit) Insert(db common.DB) (ObjectCommit, error) {\n\tvar newCommit ObjectCommit\n\n\tif err := commit.Validate(); err != nil {\n\t\treturn newCommit, err\n\t}\n\n\tif commit.ID != 0 {\n\t\treturn newCommit, fmt.Errorf(errNoInsertHasPrimaryKey, \"ObjectCommit\")\n\t}\n\n\tstmt, err := db.Prepare(sqlInsertObjectCommit)\n\tif err != nil {\n\t\treturn newCommit, err\n\t}\n\n\tvar id int64\n\tvar formID int64\n\tvar shadowID int64\n\tvar createdAt time.Time\n\n\trow := stmt.QueryRow(commit.FormID, commit.ShadowID)\n\tif err := row.Scan(&id, &formID, &shadowID, &createdAt); err != nil {\n\t\treturn newCommit, err\n\t}\n\n\treturn ObjectCommit{\n\t\tID: id,\n\t\tFormID: formID,\n\t\tShadowID: shadowID,\n\t\tCreatedAt: createdAt,\n\t}, nil\n}", "func (sm Semester) InsertToDB() {\n\ts, c, err := mongo.GetSemester(sm.Semester)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer s.Close()\n\n\tfor _, cr := range sm.CourseList {\n\t\t_, err := c.UpsertId(cr.CallNumber, cr)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t}\n}", "func (repo *OrderRepository) Create(order *models.Order) (id int64, err error) {\n\tstatement := \"insert into `order` (vendorId, customerId, orderDetails, status) values (?, ?, ?, ?)\"\n\tstmt, err := Db.Prepare(statement)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\tresult, err := stmt.Exec(order.VendorId, order.CustomerId, order.OrderDetails, order.Status)\n\tif err != nil {\n\t\tcommon.Error.Println(\"Order could not be created \", err)\n\t\treturn\n\t}\n\treturn result.LastInsertId()\n\n}", "func InsertPipelineBuildJob(db gorp.SqlExecutor, pbJob *sdk.PipelineBuildJob) error {\n\tdbmodel := PipelineBuildJob(*pbJob)\n\tif err := db.Insert(&dbmodel); err != nil {\n\t\treturn err\n\t}\n\t*pbJob = sdk.PipelineBuildJob(dbmodel)\n\treturn nil\n}", "func (p *ProviderDAO) Insert(provider models.Provider) error {\n\terr := db.C(COLLECTION).Insert(&provider)\n\treturn err\n}", "func (o *CMFPaidprogramComment) Insert(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no cmf_paidprogram_comment provided for insertion\")\n\t}\n\n\tvar err error\n\n\tif err := o.doBeforeInsertHooks(ctx, exec); err != nil {\n\t\treturn err\n\t}\n\n\tnzDefaults := queries.NonZeroDefaultSet(cmfPaidprogramCommentColumnsWithDefault, o)\n\n\tkey := makeCacheKey(columns, nzDefaults)\n\tcmfPaidprogramCommentInsertCacheMut.RLock()\n\tcache, cached := cmfPaidprogramCommentInsertCache[key]\n\tcmfPaidprogramCommentInsertCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl, returnColumns := columns.InsertColumnSet(\n\t\t\tcmfPaidprogramCommentAllColumns,\n\t\t\tcmfPaidprogramCommentColumnsWithDefault,\n\t\t\tcmfPaidprogramCommentColumnsWithoutDefault,\n\t\t\tnzDefaults,\n\t\t)\n\n\t\tcache.valueMapping, err = queries.BindMapping(cmfPaidprogramCommentType, cmfPaidprogramCommentMapping, wl)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tcache.retMapping, err = queries.BindMapping(cmfPaidprogramCommentType, cmfPaidprogramCommentMapping, returnColumns)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif len(wl) != 0 {\n\t\t\tcache.query = fmt.Sprintf(\"INSERT INTO `cmf_paidprogram_comment` (`%s`) %%sVALUES (%s)%%s\", strings.Join(wl, \"`,`\"), strmangle.Placeholders(dialect.UseIndexPlaceholders, len(wl), 1, 1))\n\t\t} else {\n\t\t\tcache.query = \"INSERT INTO `cmf_paidprogram_comment` () VALUES ()%s%s\"\n\t\t}\n\n\t\tvar queryOutput, queryReturning string\n\n\t\tif len(cache.retMapping) != 0 {\n\t\t\tcache.retQuery = fmt.Sprintf(\"SELECT `%s` FROM `cmf_paidprogram_comment` WHERE %s\", strings.Join(returnColumns, \"`,`\"), strmangle.WhereClause(\"`\", \"`\", 0, cmfPaidprogramCommentPrimaryKeyColumns))\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(cache.query, queryOutput, queryReturning)\n\t}\n\n\tvalue := reflect.Indirect(reflect.ValueOf(o))\n\tvals := queries.ValuesFromMapping(value, cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, vals)\n\t}\n\tresult, err := exec.ExecContext(ctx, cache.query, vals...)\n\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to insert into cmf_paidprogram_comment\")\n\t}\n\n\tvar lastID int64\n\tvar identifierCols []interface{}\n\n\tif len(cache.retMapping) == 0 {\n\t\tgoto CacheNoHooks\n\t}\n\n\tlastID, err = result.LastInsertId()\n\tif err != nil {\n\t\treturn ErrSyncFail\n\t}\n\n\to.ID = int64(lastID)\n\tif lastID != 0 && len(cache.retMapping) == 1 && cache.retMapping[0] == cmfPaidprogramCommentMapping[\"id\"] {\n\t\tgoto CacheNoHooks\n\t}\n\n\tidentifierCols = []interface{}{\n\t\to.ID,\n\t}\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.retQuery)\n\t\tfmt.Fprintln(writer, identifierCols...)\n\t}\n\terr = exec.QueryRowContext(ctx, cache.retQuery, identifierCols...).Scan(queries.PtrsFromMapping(value, cache.retMapping)...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to populate default values for cmf_paidprogram_comment\")\n\t}\n\nCacheNoHooks:\n\tif !cached {\n\t\tcmfPaidprogramCommentInsertCacheMut.Lock()\n\t\tcmfPaidprogramCommentInsertCache[key] = cache\n\t\tcmfPaidprogramCommentInsertCacheMut.Unlock()\n\t}\n\n\treturn o.doAfterInsertHooks(ctx, exec)\n}", "func (m *CDatabase) Insert(cluster Cluster) error {\n\terr := db.C(COLLECTION).Insert(&cluster)\n\treturn err\n}", "func (c *Command) Insert(data interface{}) (interface{}, error) {\n\tclient := c.set.gom.GetClient()\n\n\tcollection := client.Database(c.set.gom.GetDatabase()).Collection(c.set.tableName)\n\n\tdataM, err := c.set.buildData(data, true)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, cancelFunc := c.set.GetContext()\n\tdefer cancelFunc()\n\n\tres, err := collection.InsertOne(ctx, dataM)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tid := res.InsertedID\n\n\treturn id, nil\n}", "func (s *orderRepo) CreateOrder(order entity.Order) (int64, *resterrors.RestErr) {\n\n\tquery := `\n\t\tINSERT INTO tab_order (\n\t\t\tuser_id,company_id,accept_tip\n\t\t) VALUES (?,?,?);\n\t\t`\n\n\tstmt, err := s.db.Prepare(query)\n\tif err != nil {\n\t\terrorCode := \"Error 0006: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to prepare the query statement in the Create a order\", errorCode), err)\n\t\treturn 0, resterrors.NewInternalServerError(fmt.Sprintf(\"%sDatabase error\", errorCode))\n\t}\n\tdefer stmt.Close()\n\n\tinsertResult, err := stmt.Exec(\n\t\torder.UserID,\n\t\torder.CompanyID,\n\t\torder.AcceptTip)\n\tif err != nil {\n\t\terrorCode := \"Error 0007: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to execute Query in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\torderID, err := insertResult.LastInsertId()\n\tif err != nil {\n\t\terrorCode := \"Error 0008: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to get LastInsertId in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\treturn orderID, nil\n}", "func InsertProduct(product entity.Product) int64 {\n\tdb := CreateConnection()\n\tdefer db.Close()\n\n\tsqlStatement := `\n\tinsert into products (id, code, name, description, \n\t\tprice, quantity_stock, status, category) \n\tVALUES ($1, $2, $3, $4, $5, $6, $7, $8) \n\treturning id`\n\n\tvar id int64\n\n\tctx := context.Background()\n\ttx, err := db.BeginTx(ctx, nil)\n\tif nil != err {\n\t\tlog.Fatal(\"erro ao iniciar a transação, \", err)\n\t}\n\n\t// _, err = tx.ExecContext(ctx, sqlStatement, product.ID, product.Code,\n\t// \tproduct.Name, product.Description, product.Price,\n\t// \tproduct.QuantityStock, product.Status, product.Category)\n\t// if nil != err {\n\t// \ttx.Rollback()\n\t// \tlog.Fatal(err)\n\t// }\n\n\trow := tx.QueryRowContext(ctx, sqlStatement, product.ID, product.Code,\n\t\tproduct.Name, product.Description, product.Price,\n\t\tproduct.QuantityStock, product.Status, product.Category)\n\n\tif nil != row {\n\t\ttx.Rollback()\n\t\tlog.Fatal(\"Erro ao realizar a transação, \")\n\t}\n\terr = tx.Commit()\n\tif nil != err {\n\t\tlog.Fatal(\"erro ao realizar o commit, \", err)\n\t}\n\n\t//retornando id invalido\n\treturn id\n}", "func (dtm *DirectToMessage) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif dtm._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key must be provided\n\tconst sqlstr = `INSERT INTO ms.direct_to_message (` +\n\t\t`Id, ChatKey, MessageId, SourceEnumId` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, dtm.Id, dtm.ChatKey, dtm.MessageId, dtm.SourceEnumId)\n\t_, err = db.Exec(sqlstr, dtm.Id, dtm.ChatKey, dtm.MessageId, dtm.SourceEnumId)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tdtm._exists = true\n\n\tOnDirectToMessage_AfterInsert(dtm)\n\n\treturn nil\n}", "func (o *<%= classedName %>) Insert() error {\n\tif _, err := orm.NewOrm().Insert(o); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c Client) Insert(entity interface{}, ptrResult interface{}) error {\n\treturn c.InsertInto(entity, ptrResult, reflect.TypeOf(entity).Name())\n}", "func (c *Conn) Insert(cmd string, args ...interface{}) (rowid int64, err error) {\n\tn, err := c.ExecDml(cmd, args...)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\tif n == 0 { // No change => no insert...\n\t\treturn -1, nil\n\t}\n\treturn c.LastInsertRowid(), nil\n}", "func (d *DeliveryCity) Insert() (code int, err error) {\n mConn := mymongo.Conn()\n defer mConn.Close()\n\n c := mConn.DB(\"\").C(DBTableDeliveryCity)\n d.ID = bson.NewObjectId()\n\n err = c.Insert(d)\n if err != nil {\n if mgo.IsDup(err) {\n code = ErrDupRows\n } else {\n code = ErrDatabase\n }\n } else {\n code = 0\n }\n\n return\n}", "func (s *Service) InsertTransaction(transaction *entity.Transaction) error {\n\tif transaction.OperationID == 0 {\n\t\ttransaction.OperationID = 4\n\t}\n\t_, err := govalidator.ValidateStruct(transaction)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn s.repo.InsertTransaction(transaction)\n}", "func (g *GameDBModel) Insert(game Game) error {\n\tgame.ID = bson.NewObjectId()\n\terr := database.C(COLLECTION).Insert(&game)\n\n\treturn err\n}", "func InsertProgress(p *models.Progress, g *models.Goal) error {\n\t// prepare statement\n\tstmt, err := db.Prepare(\"INSERT INTO progress (goal_id, value, date, note) values (?,?,?,?)\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// exec statement\n\tres, err := stmt.Exec(g.ID, p.Value, p.Date, p.Note)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// update progress id\n\tp.ID, err = res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Insert(session *mgo.Session, dbName string, collectionName string, query interface{}) error {\n\n\tc := openCollection(session, dbName, collectionName)\n\terr := c.Insert(query)\n\treturn err\n}", "func (t TaskInstanceRepoCassandra) Insert(ctx context.Context, taskInstance TaskInstance) (err error) {\n\terr = t.insertTaskInstance(ctx, taskInstance)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = t.insertTaskInstanceStartedAt(ctx, taskInstance)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn t.insertInstancesByID(ctx, taskInstance)\n}", "func (r *RoomDAO) Insert(room RoomDTO) error {\n\terr := r.db.C(r.collection).Insert(&room)\n\treturn err\n}", "func Insert(Items Item) error {\n\terr := db.C(\"unit\").Insert(&Items)\n\treturn err\n}", "func (session *Session) Insert(beans ...interface{}) (int64, error) {\n\treturn HookInsert(func() (int64, error) {\n\t\treturn session.Session.Insert(beans...)\n\t})\n}", "func (dcc *DoorCompiledContent) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif dcc._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by sequence\n\tconst sqlstr = `INSERT INTO public.door_compiled_content (` +\n\t\t`door_id, patches, unprotected_full, protected_full, created_at, created_by, activated, needs_approval, approved_by` +\n\t\t`) VALUES (` +\n\t\t`$1, $2, $3, $4, $5, $6, $7, $8, $9` +\n\t\t`) RETURNING id`\n\n\t// run query\n\tXOLog(sqlstr, dcc.DoorID, dcc.Patches, dcc.UnprotectedFull, dcc.ProtectedFull, dcc.CreatedAt, dcc.CreatedBy, dcc.Activated, dcc.NeedsApproval, dcc.ApprovedBy)\n\terr = db.QueryRow(sqlstr, dcc.DoorID, dcc.Patches, dcc.UnprotectedFull, dcc.ProtectedFull, dcc.CreatedAt, dcc.CreatedBy, dcc.Activated, dcc.NeedsApproval, dcc.ApprovedBy).Scan(&dcc.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set existence\n\tdcc._exists = true\n\n\treturn nil\n}", "func InsertIntoDB(p EventCacheParameters) error {\n\tdb, err := getDatabase()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer db.Close()\n\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tstmt, err := tx.Prepare(`insert into events(id, event, json, from_user, to_user, transport, timestamp) values(?, ?, ?, ?, ?, ?, ?)`)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(p.ID, p.Event, p.JSON, p.FromUser, p.ToUser, p.Transport, p.Timestamp)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttx.Commit()\n\n\treturn nil\n}", "func (xpss *XPipelineSalesStage) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif xpss._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO x_showroom.x_pipeline_sales_stages (` +\n\t\t`name, probability, seq_num, active_flag, sales_method_id, created_by, updated_by, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt)\n\tres, err := db.Exec(sqlstr, xpss.Name, xpss.Probability, xpss.SeqNum, xpss.ActiveFlag, xpss.SalesMethodID, xpss.CreatedBy, xpss.UpdatedBy, xpss.CreatedAt, xpss.UpdatedAt)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\txpss.ID = uint(id)\n\txpss._exists = true\n\n\treturn nil\n}", "func (sc *ScCategory) Insert(db XODB) error {\n\tvar err error\n\n\t// if already exist, bail\n\tif sc._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tconst sqlstr = `INSERT INTO emind_software_center.sc_category (` +\n\t\t`category_name` +\n\t\t`) VALUES (` +\n\t\t`?` +\n\t\t`)`\n\n\t// run query\n\tXOLog(sqlstr, sc.CategoryName)\n\tres, err := db.Exec(sqlstr, sc.CategoryName)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tsc.ID = uint(id)\n\tsc._exists = true\n\n\treturn nil\n}", "func (m *BookingModel) Insert(booking models.Booking) (*mongo.InsertOneResult, error) {\n\treturn m.C.InsertOne(context.TODO(), booking)\n}", "func (db Database) InsertPlacement() Placement {\n\tresult := Placement{ID: db.nextID()}\n\tdb.insert(result)\n\treturn result\n}", "func (m *MySQL) Insert(todo *schema.Todo) (int, error) {\n\t//Insert Title and Complete, ID is auto-populated\n\tres, err := m.DB.Exec(`INSERT INTO Todo (Title, Complete) VALUES (?,?)`, todo.Title, todo.Complete)\n\n\tif err != nil {\n\t\tprintln(\"Exec err:\", err.Error())\n\t\treturn -1, err\n\t}\n\n\t//Use MySQL LastInsertId to get ID of newly added Todo object\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\tprintln(\"Error:\", err.Error())\n\t\treturn -1, err\n\t}\n\n\tprintln(\"LastInsertId:\", id)\n\treturn int(id), nil\n}", "func (messageService *MessageService) Insert(senderID uint, receiverID uint, content string) (uint, error) {\n\tmsg := pojo.Message{\n\t\tSenderID: senderID,\n\t\tReceiverID: receiverID,\n\t\tContent: content,\n\t\tSendTime: time.Now(),\n\t}\n\n\t// If no sender id\n\tif msg.SenderID == 0 {\n\t\treturn 0, errors.New(\"Can't insert message with SenderID(0)\")\n\t}\n\n\t// Execute insert\n\tif err := messageService.db.Table(\"messages\").Create(&msg).Error; err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn msg.ID, nil\n}", "func (m *PersonDAO) Insert(person Person) error {\n\terr := db.C(COLLECTION).Insert(&person)\n\treturn err\n}", "func (m *PacientesModel) Insert(dni, nombres, apellidos, direccion, email, password string) error {\n\t// Create a bcrypt hash of the plain-text password. nahuel1234\n\thashPassword, err := bcrypt.GenerateFromPassword([]byte(password), 6)\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt := \"INSERT INTO Pacientes (dni,nombres, apellidos,direccion, email, Password) VALUES(?,?,?,?,?,?)\"\n\n\t_, err = m.DB.Exec(stmt, dni, nombres, apellidos, direccion, email, string(hashPassword))\n\tif err != nil {\n\t\tif mysqlErr, ok := err.(*mysql.MySQLError); ok {\n\t\t\tif mysqlErr.Number == 1062 && strings.Contains(mysqlErr.Message, \"users_uc_email\") {\n\t\t\t\treturn models.ErrDuplicateEmail\n\t\t\t}\n\t\t}\n\t}\n\treturn err\n}", "func (d *Dosen) Insert(db *sql.DB) error {\n\tif d.ID == \"\" {\n\t\treturn fmt.Errorf(\"id tidak bolehh kosong\")\n\t}\n\tquery := \"INSERT INTO dosen Values($1, $2)\"\n\t_, err := db.Exec(query, &d.ID, &d.NamaDosen)\n\treturn err\n}", "func NewOrder(order map[string]interface{}) (err error) {\r\n\tmaster := \"\"\r\n\tdetail := \"\"\r\n\tpayment := \"\"\r\n\tinventory := \"\"\r\n\r\n\t// Get a new reference to the ordered items and remove it from the map.\r\n\tpayments := order[\"payments\"]\r\n\titemsOrdered := order[\"items\"]\r\n\tdelete(order, \"items\")\r\n\tdelete(order, \"payments\")\r\n\r\n\t// Get the master insert query\r\n\tif master, err = MaptoInsert(order, \"orders\"); err != nil {\r\n\t\tCheckError(\"Error Mapping the Order to SQL.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\tmaster += \"SET @last_id := (SELECT LAST_INSERT_ID());\"\r\n\r\n\t// Get the details insert query\r\n\tfor _, _value := range itemsOrdered.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"ordereditems\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Ordered Items to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tinventory += fmt.Sprintf(`UPDATE products SET onhand = onhand - %v, serialnumbers = replace(serialnumbers, '%s', '') WHERE itemcode = \"%s\";`, _value.(map[string]interface{})[\"quantity\"], _value.(map[string]interface{})[\"serialnumber\"], _value.(map[string]interface{})[\"itemcode\"])\r\n\t\tmaster += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t\tmaster = strings.Replace(master, `\"null\"`, `\"\"`, -1)\r\n\t}\r\n\r\n\t// Get the payments insert query\r\n\tfor _, _value := range payments.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"payments\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Payments to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tpayment += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t}\r\n\r\n\t// Save the Order and Reduce inventory\r\n\tif err = Modify(master + payment + inventory); err != nil {\r\n\t\tCheckError(\"Error creating the Order.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn\r\n}", "func Insert (w http.ResponseWriter, r *http.Request){\n\tif r.Method == \"POST\"{ // se a requisição for do metodo POST, criar um novo produto\n\t\t//buscando os dados\n\t\tnome:= r.FormValue(\"nome\")\n\t\tdescricao := r.FormValue(\"descricao\")\n\t\tpreco := r.FormValue(\"preco\")\n\t\tquantidade := r.FormValue(\"quantidade\")\n\n\n\t//convertendo os valores necessarios(os valores que vem pra nós sao do tipo string) temos q converter;\n\t\t//convertendo string para float64\n\t\tprecoConvertidoParaFloat, err := strconv.ParseFloat(preco, 64)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do preço:\", err)\n\t\t}\n\t\t//convertendo string par int\n\t\tquantidadeConvertidaParaInt, err := strconv.Atoi(quantidade)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Erro na conversão do quantidade:\", err)\n\t\t}\n\n\t\t//Pegar os valores e criar (funcao do models)\n\t\tmodels.CriaNovoProduto(nome, descricao, precoConvertidoParaFloat, quantidadeConvertidaParaInt)\n\t}\n\t//depois de passar os dados redirecionar para a pagina inicial\n\thttp.Redirect(w, r, \"/\", 301)\n\treturn\n}", "func (r Item) Insert() error {\n\tr.ID = bson.NewObjectId()\n\terr := db.C(\"item\").Insert(&r)\n\treturn err\n}", "func (b *Book) Insert(session db.Session) error {\n\tif session == nil {\n\t\treturn errors.New(\"session is nil\")\n\t}\n\n\tif err := b.SimpleValidate(); err != nil {\n\t\treturn errors.New(\"insert validation failed: \" + err.Error())\n\t}\n\n\tbooks := session.Collection(\"book\")\n\terr := books.InsertReturning(b)\n\tif err != nil {\n\t\treturn errors.New(\"insertion failed: \" + err.Error())\n\t}\n\n\treturn nil\n}", "func (l *ChannelLog) Insert(nc *Channel, dryRun bool) error {\n\n\tconst qry = \"INSERT INTO channel (channel_id, nonce, sender, recipient, amount, open_time, close_time) VALUES ($1,$2,$3,$4,$5,$6,$7);\"\n\n\tif !dryRun {\n\t\t_, err := l.DB.Exec(qry, nc.ChannelId.Int64(), nc.Nonce.Int64(), nc.Sender.String(), nc.Recipient.String(), nc.ClaimAmount.Int64(), nc.OpenTime, nc.CloseTime)\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfmt.Printf(\"INSERT INTO channel (channel_id, nonce, sender, recipient, amount, open_time, close_time) VALUES (%s,%s,%s,%s,%s,%v,%v);\\n\",\n\t\tnc.ChannelId, nc.Nonce, nc.Sender.String(), nc.Recipient.String(), nc.ClaimAmount, nc.OpenTime, nc.CloseTime)\n\n\treturn nil\n\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (r *Entity) Insert() (result sql.Result, err error) {\n\treturn Model.Data(r).Insert()\n}", "func (o *Transaction) InsertGP(whitelist ...string) {\n\tif err := o.Insert(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) InsertGP(whitelist ...string) {\n\tif err := o.Insert(boil.GetDB(), whitelist...); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (db *queueDatabase) insert(m *persistence.QueueMessage) {\n\tm.Envelope = cloneEnvelope(m.Envelope)\n\tm.Revision++\n\n\t// Add the new message to the queue.\n\tif db.messages == nil {\n\t\tdb.messages = map[string]*persistence.QueueMessage{}\n\t}\n\tdb.messages[m.ID()] = m\n\n\tdb.addToOrderIndex(m)\n\tdb.addToTimeoutIndex(m)\n}", "func (i *Batch) Insert(data TaskArgs) (err error) {\n\tif i.isRun {\n\t\ti.insertChan <- data\n\t} else {\n\t\terr = errors.New(\"failed to insert, batch already stopped\")\n\t}\n\treturn\n}", "func (db *DB) Insert(table string, data ...map[string]interface{}) (int64, error) {\n\treturn db.doExec(\"INSERT\", table, data...)\n}", "func (data *DatabaseConnection) InsertChannel(ch *Channel){\n\tpStatement, _ := data.Database.Prepare(\"INSERT INTO channels VALUES(?, ?)\")\n\tdefer pStatement.Close()\n\n\tpStatement.Exec(ch.Name, ch.Active)\n}", "func (r *PlacementGroupsService) Insert(profileId int64, placementgroup *PlacementGroup) *PlacementGroupsInsertCall {\n\tc := &PlacementGroupsInsertCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.profileId = profileId\n\tc.placementgroup = placementgroup\n\treturn c\n}" ]
[ "0.6477957", "0.6144995", "0.61286396", "0.6077907", "0.6053965", "0.5990704", "0.59056485", "0.5825269", "0.5776499", "0.577628", "0.57529056", "0.5702776", "0.56661534", "0.56255245", "0.5602256", "0.5585142", "0.5507388", "0.54996574", "0.5496346", "0.54231274", "0.5408538", "0.5408443", "0.5406753", "0.5404357", "0.5402115", "0.5373183", "0.5354725", "0.5304153", "0.5274146", "0.5265445", "0.52628714", "0.5261077", "0.5259739", "0.52596706", "0.5234947", "0.5224544", "0.5207654", "0.5202694", "0.5196059", "0.5194879", "0.5182154", "0.5182154", "0.5177947", "0.5169699", "0.5169699", "0.51692367", "0.5168879", "0.51633203", "0.5162314", "0.51571745", "0.5154411", "0.51488024", "0.51460165", "0.5143728", "0.5140546", "0.5140101", "0.5128262", "0.51060647", "0.5103287", "0.5101197", "0.5095363", "0.5089928", "0.5086708", "0.5085838", "0.5082908", "0.5075234", "0.5074209", "0.50727415", "0.5068972", "0.50641763", "0.5054018", "0.50481486", "0.5047449", "0.5042755", "0.5042287", "0.50412226", "0.50349545", "0.50278884", "0.50139034", "0.5013531", "0.50127393", "0.5007454", "0.5004667", "0.5000797", "0.49919432", "0.49916968", "0.4987926", "0.49838316", "0.49838316", "0.49838316", "0.49838316", "0.49838316", "0.49838316", "0.4980264", "0.4980264", "0.49605846", "0.49557987", "0.49427938", "0.4936407", "0.493621" ]
0.77431
0
Update updates the ComponentOrderProcess in the database.
func (cop *ComponentOrderProcess) Update(ctx context.Context, key ...interface{}) error { var err error var dbConn *sql.DB // if deleted, bail if cop._deleted { return errors.New("update failed: marked for deletion") } tx, err := components.M.GetConnFromCtx(ctx) if err != nil { dbConn, err = components.M.GetMasterConn() if err != nil { return err } } tableName, err := GetComponentOrderProcessTableName(key...) if err != nil { return err } // sql query sqlstr := `UPDATE ` + tableName + ` SET ` + `orderid = ?, event = ?, do_status = ?, access_url = ?, remark = ?, created_at = ?, updated_at = ?` + ` WHERE id = ?` // run query utils.GetTraceLog(ctx).Debug("DB", zap.String("SQL", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID))) if tx != nil { _, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID) } else { _, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID) } return err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *ProcessClient) Update(ctx context.Context, guid string, r *resource.ProcessUpdate) (*resource.Process, error) {\n\tvar process resource.Process\n\t_, err := c.client.patch(ctx, path.Format(\"/v3/processes/%s\", guid), r, &process)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &process, nil\n}", "func (context Context) UpdateProcess(id bson.ObjectId, updates map[string]interface{}) (result types.Process, err error) {\n\n\t// This action is only permitted for the root user.\n\tif context.User.IsRoot() == false {\n\t\terr = types.ErrUnauthorized\n\t\treturn\n\t}\n\n\t// Build the update document. Validate values.\n\tvalueUpdates := bson.M{}\n\tfor k, v := range updates {\n\t\tswitch k {\n\t\tcase \"status\":\n\t\t\tstatus := v.(string)\n\n\t\t\tif status != types.ProcIdle && status != types.ProcWorking && status != types.ProcTerminated {\n\t\t\t\terr = errors.Wrapf(ErrBadInput,\n\t\t\t\t\t\"value of status can be \\\"%s\\\", \\\"%s\\\" or \\\"%s\\\", but found \\\"%s\\\"\",\n\t\t\t\t\ttypes.ProcIdle, types.ProcWorking, types.ProcTerminated, status)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tvalueUpdates[\"status\"] = status\n\t\tcase \"last-keepalive\":\n\t\t\tvalueUpdates[\"last-keepalive\"] = v.(time.Time)\n\t\tdefault:\n\t\t\terr = errors.Wrap(ErrBadInput, \"invalid value of parameter updates\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// If there were no updates, then we can skip this step.\n\tif len(valueUpdates) > 0 {\n\t\tc := context.Session.DB(context.DBName).C(\"processes\")\n\t\terr = c.Update(bson.M{\"_id\": id}, bson.M{\"$set\": valueUpdates})\n\t\tif err != nil {\n\t\t\terr = errors.Wrap(err, \"mongo update failed\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// Get the updated process and update cache if needed.\n\tresult, err = context.GetProcessByID(id)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"process get by ID failed\")\n\t\treturn\n\t}\n\n\treturn\n\n}", "func (od *OrderDetail) Update(ctx context.Context, db DB) error {\n\tswitch {\n\tcase !od._exists: // doesn't exist\n\t\treturn logerror(&ErrUpdateFailed{ErrDoesNotExist})\n\tcase od._deleted: // deleted\n\t\treturn logerror(&ErrUpdateFailed{ErrMarkedForDeletion})\n\t}\n\t// update with primary key\n\tconst sqlstr = `UPDATE northwind.order_details SET ` +\n\t\t`unit_price = ?, quantity = ?, discount = ? ` +\n\t\t`WHERE order_id = ? AND product_id = ?`\n\t// run\n\tlogf(sqlstr, od.UnitPrice, od.Quantity, od.Discount, od.OrderID, od.ProductID)\n\tif _, err := db.ExecContext(ctx, sqlstr, od.UnitPrice, od.Quantity, od.Discount, od.OrderID, od.ProductID); err != nil {\n\t\treturn logerror(err)\n\t}\n\treturn nil\n}", "func (s *Server) UpdateOrder(ctx context.Context, in *orderPb.UpdateOrderRequest) (*orderPb.Null, error) {\n\tt := time.Now()\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"UpdateOrderTotal\"}).Inc()\n\n\t// Check input params.\n\tfileHash := in.GetFileHash()\n\tsessionId := in.GetSessionId()\n\tnodeIp := in.GetNodeIp()\n\torderId := in.GetOrderId()\n\tif fileHash == \"\" || sessionId == \"\" || nodeIp == \"\" || orderId == 0 {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"UpdateOrderFailed\"}).Inc()\n\t\treturn nil, errorm.RequestParamEmpty\n\t}\n\n\tdefer func(t time.Time) {\n\t\tdefer rpcRequestDuration.With(prometheus.Labels{\"method\": \"UpdateOrder\"}).Observe(float64(time.Since(t).Microseconds()) / 1000)\n\t}(t)\n\n\t// Update order by fileHash, sessionId, nodeIp and orderId.\n\terr := s.UpdateOrderController(fileHash, sessionId, nodeIp, orderId)\n\tif err != nil {\n\t\trpcRequestCount.With(prometheus.Labels{\"method\": \"UpdateOrderError\"}).Inc()\n\t\treturn nil, err\n\t}\n\n\trpcRequestCount.With(prometheus.Labels{\"method\": \"UpdateOrderSuccess\"}).Inc()\n\treturn &orderPb.Null{}, nil\n}", "func (a *App) UpdateOrder(id int64, o *model.Order) (*model.Order, *model.AppErr) {\n\treturn a.Srv().Store.Order().Update(id, o)\n}", "func (s *orderRepo) UpdateOrder(orderID int64, order entity.Order) *resterrors.RestErr {\n\n\tquery := `\n\t\tUPDATE tab_order\n\t\t\tSET\ttotal_tip \t\t= ?,\n\t\t\t\t\ttotal_price\t\t= ?\n\t\t\t\n\t\tWHERE id\t= ?;\n\t`\n\n\tstmt, err := s.db.Prepare(query)\n\tif err != nil {\n\t\terrorCode := \"Error 0009: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to prepare the query statement in the Update a order\", errorCode), err)\n\t\treturn resterrors.NewInternalServerError(fmt.Sprintf(\"%sDatabase error\", errorCode))\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(\n\t\torder.TotalTip,\n\t\torder.TotalPrice,\n\t\torderID)\n\tif err != nil {\n\t\terrorCode := \"Error 0010: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to execute Query in the Update order\", errorCode), err)\n\t\treturn mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\treturn nil\n}", "func (dao *OrderDao) Update(order Order, id string) (*Order, error) {\n\tquery := `\n\t\tUPDATE orders SET status=$2, customerid=$3, productid=$4\n\t\tWHERE id=$1 \n\t`\n\tstmt, err := dao.DB.Prepare(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t_, err = stmt.Exec(order.ID, order.Status, order.CustomerID, order.ProductID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n}", "func (s *RunbookProcessService) Update(runbook *RunbookProcess) (*RunbookProcess, error) {\n\tif runbook == nil {\n\t\treturn nil, internal.CreateInvalidParameterError(constants.OperationUpdate, constants.ParameterRunbook)\n\t}\n\n\tpath, err := services.GetUpdatePath(s, runbook)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := services.ApiUpdate(s.GetClient(), runbook, new(RunbookProcess), path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*RunbookProcess), nil\n}", "func (yom *YhOrderMaster) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !yom._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif yom._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE devdb.yh_order_master SET ` +\n\t\t`order_time = ?, seller_id = ?, image_id = ?, item_id = ?, is_hidden_page = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, yom.OrderTime, yom.SellerID, yom.ImageID, yom.ItemID, yom.IsHiddenPage, yom.ID)\n\t_, err = db.Exec(sqlstr, yom.OrderTime, yom.SellerID, yom.ImageID, yom.ItemID, yom.IsHiddenPage, yom.ID)\n\treturn err\n}", "func (s *Service) UpdateOrder(w http.ResponseWriter, r *http.Request) {\n\t// Get the order ID\n\tvars := mux.Vars(r)\n\tentry := order.Order{ID: vars[\"id\"]}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(&entry); err != nil {\n\t\tlog.Errorf(\"UpdateOrder: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusBadRequest, \"Invalid resquest payload\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\t// Update the order in the storage\n\tif err := usecases.UpdateOrder(s.storage, &entry); err != nil {\n\t\tlog.Errorf(\"UpdateOrder usecase: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tutils.ResponseWithJSON(w, http.StatusOK, entry)\n}", "func (og *OrderGood) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif og._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetOrderGoodTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`orderid = ?, pid = ?, gid = ?, title = ?, allprice = ?, prepay_price = ?, price = ?, number = ?, shipping = ?, goods_updated = ?, comment = ?, uid = ?, refund_nums = ?, next = ?, note_user = ?, stock_id = ?, shareid = ?, from_uid = ?, activity_id = ?, goods_origin_fee = ?, real_settlement_fee = ?, refund_fee = ?` +\n\t\t` WHERE order_gid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee, og.OrderGid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee, og.OrderGid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, og.Orderid, og.Pid, og.Gid, og.Title, og.Allprice, og.PrepayPrice, og.Price, og.Number, og.Shipping, og.GoodsUpdated, og.Comment, og.UID, og.RefundNums, og.Next, og.NoteUser, og.StockID, og.Shareid, og.FromUID, og.ActivityID, og.GoodsOriginFee, og.RealSettlementFee, og.RefundFee, og.OrderGid)\n\t}\n\treturn err\n}", "func (cop *ComponentOrderProcess) Save(ctx context.Context) error {\n\tif cop.Exists() {\n\t\treturn cop.Update(ctx)\n\t}\n\n\treturn cop.Insert(ctx)\n}", "func (s *Store) UpdateOrder(order *objects.Order) error {\n\t_, err := s.engine.Update(order, objects.Order{ID: order.ID})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not update order %s: %s\", order.ID, err)\n\t}\n\treturn nil\n}", "func (a *TopologySmartscapeProcessGroupApiService) UpdateProcessGroup(ctx _context.Context, meIdentifier string) ApiUpdateProcessGroupRequest {\n\treturn ApiUpdateProcessGroupRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tmeIdentifier: meIdentifier,\n\t}\n}", "func UpdateOrder(order map[string]interface{}) (id int, err error) {\r\n\tif result, err := MaptoUpdate(order, \"orders\", \"id\"); err == nil {\r\n\t\tif err = Modify(result); err != nil {\r\n\t\t\tCheckError(\"Error updating the Order.\", err, false)\r\n\t\t}\r\n\t}\r\n\r\n\treturn\r\n}", "func (r *mutationResolver) UpdateOrder(ctx context.Context, id string, input *models.UpdateOrderInput) (*order.Order, error) {\n\tpanic(\"not implemented\")\n}", "func (s *OrderItemService) Update(ctx context.Context, id string, uoi entity.UpdateOrderItem) error {\n\treturn s.repo.Update(ctx, id, uoi)\n}", "func (c *MySQLClient) Update(p *purchase.Purchase) error {\n\tif p.ID == 0 {\n\t\treturn fmt.Errorf(\"purchase must have a preexisting ID\")\n\t}\n\n\tbuyBytes, err := json.Marshal(p.BuyOrder)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshal buy order: %v\", err)\n\t}\n\n\tsellBytes, err := json.Marshal(p.SellOrder)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to marshal sell order: %v\", err)\n\t}\n\n\tquery := `UPDATE trader_one\n SET\n buy_order = ?,\n sell_order = ?,\n updated_at = NOW()\n WHERE\n id = ?`\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 5*time.Second)\n\tdefer cancelFunc()\n\tstmt, err := c.db.PrepareContext(ctx, query)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to prepare SQL statement: %v\", err)\n\t}\n\tdefer stmt.Close()\n\n\t_, err = stmt.ExecContext(ctx, jsonString(buyBytes), jsonString(sellBytes), p.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to update row: %v\", err)\n\t}\n\treturn nil\n}", "func (c *Client) Update(ctx context.Context, id string, params *razorpay.OrderParams) (*razorpay.Order, error) {\n\torder := &razorpay.Order{}\n\terr := c.Call(ctx, http.MethodPatch, \"/orders/\"+id, params, order)\n\treturn order, err\n}", "func (m *MockProcessRepository) UpdateProcess(arg0 models.Process) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateProcess\", arg0)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o *Order) Update() *OrderUpdateOne {\n\treturn (&OrderClient{config: o.config}).UpdateOne(o)\n}", "func (cop *ComponentOrderProcess) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif cop._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, event, do_status, access_url, remark, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tcop.ID = uint(id)\n\tcop._exists = true\n\n\treturn nil\n}", "func UpdateOrderDetails(order *Order, id string) (err error) {\n\tfmt.Println(order)\n\tConfig.DB.Save(order)\n\treturn nil\n}", "func (tsl *TrailingStopLoss) UpdateOrder(newPrice float64) {\n\tif tsl.Order != (cbp.Order{}) {\n\t\ttsl.CancelOrder()\n\t}\n\ttsl.ChangeSellPrice(newPrice)\n\ttsl.CreateOrder()\n}", "func (orderTree *OrderTree) UpdateOrder(quote map[string]string) error {\n\t// order := orderTree.OrderMap[quote[\"order_id\"]]\n\n\tprice := ToBigInt(quote[\"price\"])\n\torderList := orderTree.PriceList(price)\n\n\tif orderList == nil {\n\t\t// create a price list for this price\n\t\torderList = orderTree.CreatePrice(price)\n\t}\n\n\torderID := ToBigInt(quote[\"order_id\"])\n\tkey := GetKeyFromBig(orderID)\n\t// order := orderTree.GetOrder(key)\n\n\torder := orderList.GetOrder(key)\n\n\toriginalQuantity := CloneBigInt(order.Item.Quantity)\n\n\tif !IsEqual(price, order.Item.Price) {\n\t\t// Price changed. Remove order and update tree.\n\t\t// orderList := orderTree.PriceMap[order.Price.String()]\n\t\torderList.RemoveOrder(order)\n\t\tif orderList.Item.Length == 0 {\n\t\t\torderTree.RemovePrice(price)\n\t\t}\n\t\torderTree.InsertOrder(quote)\n\t\t// orderList.Save()\n\t} else {\n\t\tquantity := ToBigInt(quote[\"quantity\"])\n\t\ttimestamp, _ := strconv.ParseUint(quote[\"timestamp\"], 10, 64)\n\t\torder.UpdateQuantity(orderList, quantity, timestamp)\n\t}\n\n\t// fmt.Println(\"QUANTITY\", order.Item.Quantity.String())\n\n\torderTree.Item.Volume = Add(orderTree.Item.Volume, Sub(order.Item.Quantity, originalQuantity))\n\n\t// should use batch to optimize the performance\n\treturn orderTree.Save()\n}", "func (a *TopologySmartscapeProcessGroupApiService) UpdateProcessGroupExecute(r ApiUpdateProcessGroupRequest) (*_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPost\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"TopologySmartscapeProcessGroupApiService.UpdateProcessGroup\")\n\tif err != nil {\n\t\treturn nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/entity/infrastructure/process-groups/{meIdentifier}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"meIdentifier\"+\"}\", _neturl.PathEscape(parameterToString(r.meIdentifier, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json; charset=utf-8\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json; charset=utf-8\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.updateEntity\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Api-Token\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v ErrorEnvelope\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarHTTPResponse, nil\n}", "func (d *Db) UpdateOrder(idOrder int, idRestaurants int) int {\n\tvar query = \"UPDATE orders SET idRestaurants = ? WHERE idOrder = ?\"\n\tstmt, err := d.Prepare(query)\n\tif err != nil {\n\t\tfmt.Println(\"UpdateOrder Preperation Err: \", err)\n\t}\n\t// Make query with our stmt, passing in name argument\n\tres, err := stmt.Exec(idRestaurants, idOrder)\n\tif err != nil {\n\t\tfmt.Println(\"UpdateOrder Query Err: \", err)\n\t}\n\n\trowsAffected, _ := res.RowsAffected()\n\n\treturn int(rowsAffected)\n}", "func (o *CMFPaidprogramComment) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tcmfPaidprogramCommentUpdateCacheMut.RLock()\n\tcache, cached := cmfPaidprogramCommentUpdateCache[key]\n\tcmfPaidprogramCommentUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tcmfPaidprogramCommentAllColumns,\n\t\t\tcmfPaidprogramCommentPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update cmf_paidprogram_comment, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE `cmf_paidprogram_comment` SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, cmfPaidprogramCommentPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(cmfPaidprogramCommentType, cmfPaidprogramCommentMapping, append(wl, cmfPaidprogramCommentPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update cmf_paidprogram_comment row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for cmf_paidprogram_comment\")\n\t}\n\n\tif !cached {\n\t\tcmfPaidprogramCommentUpdateCacheMut.Lock()\n\t\tcmfPaidprogramCommentUpdateCache[key] = cache\n\t\tcmfPaidprogramCommentUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (this *DataStore) UpdateWithPid(uuid string, pid int, cmd *exec.Cmd) error {\n\tthis.Lock()\n\tdefer func() {\n\t\tthis.Unlock()\n\t}()\n\n\tthis.ProcessTable[uuid].pid = pid\n\tthis.ProcessTable[uuid].isRunning = true\n\tthis.ProcessTable[uuid].cmd = cmd\n\n\tif _, ok := this.ProcessTable[uuid]; !ok {\n\t\treturn fmt.Errorf(\"Unable to Find ProcessInfo for %v\\n\", uuid)\n\t}\n\treturn nil\n\n}", "func (wo *WorkOrder) Update() *WorkOrderUpdateOne {\n\treturn (&WorkOrderClient{wo.config}).UpdateOne(wo)\n}", "func (me *OrderService) UpdateOrder(ctx context.Context, request *OrderUpdateRequest) (*Order, error) {\n\texistingOrder, err := me.orderRepository.GetByID(ctx, request.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif existingOrder == nil {\n\t\treturn nil, ErrOrderNotFound\n\t}\n\n\tupdatedDate := &time.Time{}\n\t*updatedDate = time.Now()\n\n\texistingOrder.OrderNumber = request.OrderNumber\n\texistingOrder.OrderDate = request.OrderDate\n\texistingOrder.Total = request.Total\n\texistingOrder.UpdatedAt = updatedDate\n\n\treturn me.orderRepository.Update(ctx, existingOrder)\n}", "func (pm *ProductModel) Update(product Product) error {\n\tif _, err := pm.DB.Query(UPDATE_PRODUCT_STMT, product.ProductName, product.Price, product.ShortDescription, product.ID); err != nil {\n\t\tlog.Printf(\"error occurred on updating a specific product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (postgres *Postgres) UpdateOne(order *proto.Order) (*proto.Order, error) {\n\tquery := fmt.Sprintf(\"UPDATE orders SET product_id = %d, user_id = %d, status = '%s'\"+\n\t\t\" WHERE id = %d\", order.ProductId, order.UserId, order.Status, order.Id)\n\tres, err := postgres.DB.Exec(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcount, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif count <= 0 {\n\t\treturn nil, errors.New(\"sql: no rows found\")\n\t}\n\n\treturn order, err\n}", "func (o *Order) updateOrder(db *sql.DB) error {\n\n\tstatement := `SELECT item_id FROM order_items WHERE order_id=?`\n\trows, err := db.Query(statement, o.ID)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tvar existing []int\n\tvar eid int\n\n\tif rows.Next() {\n\t\terr = rows.Scan(&eid)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\n\t\texisting = append(existing, eid)\n\t\tfor rows.Next() {\n\t\t\terr = rows.Scan(&eid)\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\texisting = append(existing, eid)\n\t\t}\n\n\t} else {\n\t\te := errors.New(\"Order not found.\")\n\t\tlog.Error(e)\n\t\treturn e\n\t}\n\n\tdesired := o.getItemIDs()\n\n\tdels := compare(existing, desired)\n\tadds := compare(desired, existing)\n\n\tstatement = `INSERT INTO order_items(order_id, item_id) VALUES($1, $2)`\n\tfor _, addID := range adds {\n\t\t_, err = db.Exec(statement, o.ID, addID)\n\t\tif err != nil {\n\t\t\tlog.Error(\"inserting to order_items failed.\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatement = `DELETE FROM order_items WHERE order_id=? AND item_id=?;`\n\tfor _, delID := range dels {\n\t\t_, err = db.Exec(statement, o.ID, delID)\n\t\tif err != nil {\n\t\t\tlog.Error(\"deleting from order_items failed.\")\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Verify the results\n\tstatement = `SELECT COUNT(item_id) FROM order_items WHERE order_id=?`\n\trows, err = db.Query(statement, o.ID)\n\tif err != nil {\n\t\tlog.Error(err)\n\t\treturn err\n\t}\n\tdefer rows.Close()\n\n\tvar count int\n\tfor rows.Next() {\n\t\terr = rows.Scan(&count)\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif count != len(desired) {\n\t\te := errors.New(\"Incorrect updates on order_items.\")\n\t\tlog.Info(e)\n\t\treturn e\n\t}\n\n\treturn nil\n}", "func (c *OrderClient) Update() *OrderUpdate {\n\tmutation := newOrderMutation(c.config, OpUpdate)\n\treturn &OrderUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (p *Placement) Update(db *sql.DB) error {\n\t_, err := db.Exec(`UPDATE placement SET comment=$1 WHERE id=$2`, p.Comment, p.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"update %v\", err)\n\t}\n\tif err = db.QueryRow(`SELECT p.iris_code,p.count,p.contract_year,\n\t\tMIN(c.creation_date),c.value,b.code,b.name,ba.code,ba.name,bs.name\n\tFROM placement p\n\tLEFT OUTER JOIN commitment c ON p.iris_code=c.iris_code\n\tJOIN budget_action ba ON c.action_id=ba.id\n\tJOIN budget_sector bs ON ba.sector_id=bs.id\n\tJOIN beneficiary b ON c.beneficiary_id=b.id\n\tWHERE p.id=$1\n\tGROUP BY 1,2,3,5,6,7,8,9,10`, p.ID).\n\t\tScan(&p.IrisCode, &p.Count, &p.ContractYear, &p.CreationDate, &p.CommitmentValue,\n\t\t\t&p.BeneficiaryCode, &p.BeneficiaryName, &p.ActionCode, &p.ActionName, &p.Sector); err != nil {\n\t\treturn fmt.Errorf(\"select %v\", err)\n\t}\n\treturn nil\n}", "func (s *stepsrvc) Update(ctx context.Context, p *step.StoredListOfSteps) (err error) {\n\ts.logger.Print(\"step.update\")\n\n\terr = s.db.UpdateOneStep(*p)\n\n\treturn err\n}", "func (pmt *Payment) Update(db *bolt.DB) error {\n\treturn pmt.Create(db)\n}", "func Update(ctx context.Context, id string, params *razorpay.OrderParams) (*razorpay.Order, error) {\n\treturn getDefaultClient().Update(ctx, id, params)\n}", "func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tcop._deleted = true\n\n\treturn nil\n}", "func (xpcgi *XPriCompGroupItem) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpcgi._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif xpcgi._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE x_showroom.x_pri_comp_group_item SET ` +\n\t\t`name = ?, display_name = ?, type_cd = ?, primary_flag = ?, seq_num = ?, x_pri_comp_group_id = ?, created_by = ?, updated_by = ?, created_at = ?, updated_at = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt, xpcgi.ID)\n\t_, err = db.Exec(sqlstr, xpcgi.Name, xpcgi.DisplayName, xpcgi.TypeCd, xpcgi.PrimaryFlag, xpcgi.SeqNum, xpcgi.XPriCompGroupID, xpcgi.CreatedBy, xpcgi.UpdatedBy, xpcgi.CreatedAt, xpcgi.UpdatedAt, xpcgi.ID)\n\treturn err\n}", "func (so *SQLOrderItemStore) Update(oi *model.OrderItem) (*model.OrderItem, error) {\n\toi.UpdatedAt = time.Now().UnixNano()\n\t_, err := so.SQLStore.Tx.Update(oi)\n\treturn oi, err\n}", "func (client *ClientImpl) EditProcess(ctx context.Context, args EditProcessArgs) (*ProcessInfo, error) {\n\tif args.UpdateRequest == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.UpdateRequest\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.ProcessTypeId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessTypeId\"}\n\t}\n\trouteValues[\"processTypeId\"] = (*args.ProcessTypeId).String()\n\n\tbody, marshalErr := json.Marshal(*args.UpdateRequest)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"02cc6a73-5cfb-427d-8c8e-b49fb086e8af\")\n\tresp, err := client.Client.Send(ctx, http.MethodPatch, locationId, \"6.0-preview.2\", routeValues, nil, bytes.NewReader(body), \"application/json\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue ProcessInfo\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (em *EndingMessage) Update(db XODB) error {\n\tvar err error\n\n\t// sql query with composite primary key\n\tconst sqlstr = `UPDATE custmchat.ending_message SET ` +\n\t\t`agent = ?, system = ?, status = ?, prompt = ?` +\n\t\t` WHERE ent_id = ? AND platform = ?`\n\n\t// run query\n\tXOLog(sqlstr, em.Agent, em.System, em.Status, em.Prompt, em.EntID, em.Platform)\n\t_, err = db.Exec(sqlstr, em.Agent, em.System, em.Status, em.Prompt, em.EntID, em.Platform)\n\treturn err\n}", "func ComponentOrderProcessByID(ctx context.Context, id uint, key ...interface{}) (*ComponentOrderProcess, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, orderid, event, do_status, access_url, remark, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, id)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcop := ComponentOrderProcess{\n\t\t_exists: true,\n\t}\n\n\tif tx != nil {\n\t\terr = tx.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\terr = dbConn.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &cop, nil\n}", "func (m *Mongo) UpdateOrderItem(dbname string, id string, item *proto.OrderRecord_Item) error {\n\tc := m.session.DB(dbname).C(orderItemsCollectionName)\n\tselector := bson.ObjectIdHex(id)\n\tupdataData := bson.M{\"$set\": bson.M{\n\t\t\"quantity\": item.Quantity,\n\t\t// \"unitPrice\": item.UnitPrice,\n\t\t\"updated_at\": time.Now()}}\n\n\treturn c.UpdateId(selector, updataData)\n}", "func (client *ClientImpl) UpdateProcessBehavior(ctx context.Context, args UpdateProcessBehaviorArgs) (*ProcessBehavior, error) {\n\tif args.BehaviorData == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.BehaviorData\"}\n\t}\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\tif args.BehaviorRefName == nil || *args.BehaviorRefName == \"\" {\n\t\treturn nil, &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.BehaviorRefName\"}\n\t}\n\trouteValues[\"behaviorRefName\"] = *args.BehaviorRefName\n\n\tbody, marshalErr := json.Marshal(*args.BehaviorData)\n\tif marshalErr != nil {\n\t\treturn nil, marshalErr\n\t}\n\tlocationId, _ := uuid.Parse(\"d1800200-f184-4e75-a5f2-ad0b04b4373e\")\n\tresp, err := client.Client.Send(ctx, http.MethodPut, locationId, \"6.0-preview.2\", routeValues, nil, bytes.NewReader(body), \"application/json\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue ProcessBehavior\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (d *DB) UpdateOrder(o Order) bool {\n\tfor i, oo := range d.Orders {\n\t\tif oo.ID == o.ID {\n\t\t\td.Orders[i] = o\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}", "func (ou *OrderUpdate) Exec(ctx context.Context) error {\n\t_, err := ou.Save(ctx)\n\treturn err\n}", "func (c *Client) UpdateOrder(orderID string, orderItems []OrderItem) (*Order, error) {\n\trb, err := json.Marshal(orderItems)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq, err := http.NewRequest(\"PUT\", fmt.Sprintf(\"%s/orders/%s\", c.HostURL, orderID), strings.NewReader(string(rb)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbody, err := c.doRequest(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\torder := Order{}\n\terr = json.Unmarshal(body, &order)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &order, nil\n}", "func (svc *svc) UpdateOrders(ctx context.Context, query model.OrderQuery, updates model.OrderUpdates) error {\n\terr := svc.repo.UpdateOrders(ctx, query, updates)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *CommunicationsDAO) Update(communication Communication) error {\n\terr := db.C(COLLECTION).UpdateId(communication.ID, &communication)\n\treturn err\n}", "func (o *Order) UpdatePO(id, po string) error {\n\ti, err := o.findItem(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif po == \"\" {\n\t\tpo = \"N/A\"\n\t}\n\to.Items[i].PONumber = po\n\treturn nil\n}", "func (o *PaymentObject) Update(ctx context.Context, exec boil.ContextExecutor, columns boil.Columns) (int64, error) {\n\tvar err error\n\tif err = o.doBeforeUpdateHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\tkey := makeCacheKey(columns, nil)\n\tpaymentObjectUpdateCacheMut.RLock()\n\tcache, cached := paymentObjectUpdateCache[key]\n\tpaymentObjectUpdateCacheMut.RUnlock()\n\n\tif !cached {\n\t\twl := columns.UpdateColumnSet(\n\t\t\tpaymentObjectAllColumns,\n\t\t\tpaymentObjectPrimaryKeyColumns,\n\t\t)\n\n\t\tif !columns.IsWhitelist() {\n\t\t\twl = strmangle.SetComplement(wl, []string{\"created_at\"})\n\t\t}\n\t\tif len(wl) == 0 {\n\t\t\treturn 0, errors.New(\"models: unable to update payment_objects, could not build whitelist\")\n\t\t}\n\n\t\tcache.query = fmt.Sprintf(\"UPDATE `payment_objects` SET %s WHERE %s\",\n\t\t\tstrmangle.SetParamNames(\"`\", \"`\", 0, wl),\n\t\t\tstrmangle.WhereClause(\"`\", \"`\", 0, paymentObjectPrimaryKeyColumns),\n\t\t)\n\t\tcache.valueMapping, err = queries.BindMapping(paymentObjectType, paymentObjectMapping, append(wl, paymentObjectPrimaryKeyColumns...))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\tvalues := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cache.valueMapping)\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, cache.query)\n\t\tfmt.Fprintln(writer, values)\n\t}\n\tvar result sql.Result\n\tresult, err = exec.ExecContext(ctx, cache.query, values...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to update payment_objects row\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by update for payment_objects\")\n\t}\n\n\tif !cached {\n\t\tpaymentObjectUpdateCacheMut.Lock()\n\t\tpaymentObjectUpdateCache[key] = cache\n\t\tpaymentObjectUpdateCacheMut.Unlock()\n\t}\n\n\treturn rowsAff, o.doAfterUpdateHooks(ctx, exec)\n}", "func (c *Class) Update() error {\n\tvar err error\n\n\tif c.ID.Valid() == false {\n\t\treturn errmsg.ErrInvalidID\n\t}\n\n\tif err = c.save(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func updateTaskOrders(c *gin.Context) {\r\n\treq, serr := getUpdateTaskOrdersRequest(c)\r\n\tif serr != nil {\r\n\t\tapi.SetErrorStatus(c, serr)\r\n\t\treturn\r\n\t}\r\n\ttx := orm.GetDB().Begin()\r\n\tsrvc := service.NewTaskService(tx)\r\n\tserr = srvc.UpdateTaskOrders(\r\n\t\treq.TaskID, req.FromBoardID, req.FromDispOrder, req.ToBoardID, req.ToDispOrder,\r\n\t)\r\n\tif serr != nil {\r\n\t\tapi.Rollback(tx)\r\n\t\tapi.SetErrorStatus(c, serr)\r\n\t\treturn\r\n\t}\r\n\tserr = api.Commit(tx)\r\n\tif serr != nil {\r\n\t\tapi.SetErrorStatus(c, serr)\r\n\t\treturn\r\n\t}\r\n\tc.Status(http.StatusOK)\r\n}", "func (cd *CommoditiesData) Update() error {\n\n\tcmds, err := getCommodities()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"fetching data: %w\", err)\n\t}\n\n\t// success\n\tcd.Commodities = cmds\n\treturn nil\n}", "func (p *Payment) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !p._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif p._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE public.payment SET (` +\n\t\t`customer_id, staff_id, rental_id, amount, payment_date` +\n\t\t`) = ( ` +\n\t\t`$1, $2, $3, $4, $5` +\n\t\t`) WHERE payment_id = $6`\n\n\t// run query\n\tXOLog(sqlstr, p.CustomerID, p.StaffID, p.RentalID, p.Amount, p.PaymentDate, p.PaymentID)\n\t_, err = db.Exec(sqlstr, p.CustomerID, p.StaffID, p.RentalID, p.Amount, p.PaymentDate, p.PaymentID)\n\treturn err\n}", "func (s *servicePackageCRUD) Update(arg ...crud.Arg) (crud.Arg, error) {\n\tevent := eventFromArg(arg[0])\n\tsp := servicePackageFromStuct(event)\n\n\tupdatedSP, err := s.client.ServicePackages.Update(nil, &sp.ServicePackage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &state.ServicePackage{ServicePackage: *updatedSP}, nil\n}", "func Update(c *gin.Context) {\n\tvar (\n\t\tp updateEnvironment\n\t)\n\tif err := c.ShouldBind(&p); err != nil {\n\t\tc.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\terr := p.update()\n\tif err != nil {\n\t\tlog.Error().Err(err).Msg(\"Error occured while performing db query\")\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\"error\": \"Internal Server Error\"})\n\t} else {\n\t\tc.JSON(http.StatusOK, \"OK\")\n\t}\n}", "func (a *App) updateOrder(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\tif err != nil {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_ORDER_ID\")\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar trequest map[string]string\n\tdecerr := decoder.Decode(&trequest)\n\tif decerr != nil {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_BODY\")\n\t\treturn\n\t}\n\n\tstatus := trequest[\"status\"]\n\tif status != \"taken\" {\n\t\thelpers.RespondWithError(w, http.StatusBadRequest, \"INVALID_STATUS\")\n\t\treturn\n\t}\n\n\tp := models.Order{\n\t\tID: id,\n\t\tStatus: status,\n\t}\n\teffected, err := p.UpdateOrder(a.DB)\n\tif err != nil {\n\t\thelpers.RespondWithError(w, http.StatusInternalServerError, \"DB_CONNECTION_ERR\")\n\t\treturn\n\t}\n\tif effected == 0 {\n\t\thelpers.RespondWithError(w, http.StatusConflict, \"ORDER_ALREADY_BEEN_TAKEN\")\n\t\treturn\n\t}\n\tif effected == -1 {\n\t\thelpers.RespondWithError(w, http.StatusConflict, \"ORDER_NOT_FOUND\")\n\t\treturn\n\t}\n\n\thelpers.RespondWithJSON(w, http.StatusOK, nil)\n}", "func (s *APIProductStore) Update(p *types.APIProduct) types.Error {\n\n\tquery := \"INSERT INTO api_products (\" + apiProductsColumns + \") VALUES(?,?,?,?,?,?,?,?,?,?,?)\"\n\tif err := s.db.CassandraSession.Query(query,\n\t\tp.Name,\n\t\tp.DisplayName,\n\t\tp.Description,\n\t\tp.Attributes.Marshal(),\n\t\tp.RouteGroup,\n\t\tp.Paths.Marshal(),\n\t\tp.Policies,\n\t\tp.CreatedAt,\n\t\tp.CreatedBy,\n\t\tp.LastmodifiedAt,\n\t\tp.LastmodifiedBy).Exec(); err != nil {\n\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn types.NewDatabaseError(\n\t\t\tfmt.Errorf(\"Cannot update apiproduct '%s'\", p.Name))\n\t}\n\treturn nil\n}", "func (m manager) UpdateStatus(s acmeserverless.ShipmentData) (acmeserverless.Order, error) {\n\t// Create a map of DynamoDB Attribute Values containing the table keys\n\t// for the access pattern PK = ORDER SK = ID\n\tkm := make(map[string]*dynamodb.AttributeValue)\n\tkm[\":type\"] = &dynamodb.AttributeValue{\n\t\tS: aws.String(\"ORDER\"),\n\t}\n\tkm[\":id\"] = &dynamodb.AttributeValue{\n\t\tS: aws.String(s.OrderNumber),\n\t}\n\n\t// Create the QueryInput\n\tqi := &dynamodb.QueryInput{\n\t\tTableName: aws.String(os.Getenv(\"TABLE\")),\n\t\tKeyConditionExpression: aws.String(\"PK = :type AND SK = :id\"),\n\t\tExpressionAttributeValues: km,\n\t}\n\n\tqo, err := dbs.Query(qi)\n\tif err != nil {\n\t\treturn acmeserverless.Order{}, err\n\t}\n\n\t// Create an order struct from the data\n\tstr := *qo.Items[0][\"Payload\"].S\n\tord, err := acmeserverless.UnmarshalOrder(str)\n\tif err != nil {\n\t\treturn acmeserverless.Order{}, err\n\t}\n\n\tord.Status = &s.Status\n\n\t// Marshal the newly updated product struct\n\tpayload, err := ord.Marshal()\n\tif err != nil {\n\t\treturn ord, fmt.Errorf(\"error marshalling order: %s\", err.Error())\n\t}\n\n\tem := make(map[string]*dynamodb.AttributeValue)\n\tem[\":payload\"] = &dynamodb.AttributeValue{\n\t\tS: aws.String(string(payload)),\n\t}\n\n\tuii := &dynamodb.UpdateItemInput{\n\t\tTableName: aws.String(os.Getenv(\"TABLE\")),\n\t\tKey: km,\n\t\tExpressionAttributeValues: em,\n\t\tUpdateExpression: aws.String(\"SET Payload = :payload\"),\n\t\tReturnValues: aws.String(\"ALL_NEW\"),\n\t}\n\n\tuio, err := dbs.UpdateItem(uii)\n\tif err != nil {\n\t\treturn acmeserverless.Order{}, fmt.Errorf(\"error updating dynamodb: %s\", err.Error())\n\t}\n\n\treturn acmeserverless.UnmarshalOrder(*uio.Attributes[\"OrderString\"].S)\n}", "func (a *paymentUsecase) Update(c context.Context, ar *models.Payment) (*models.Payment, error) {\n\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\n\tdefer cancel()\n\n\tar.UpdatedAt = time.Now()\n\treturn a.repo.Update(ctx, ar)\n}", "func (u *__GroupOrderdUser_Updater) Update(db XODB) (int, error) {\n\tvar err error\n\n\tvar updateArgs []interface{}\n\tvar sqlUpdateArr []string\n\t/*for up, newVal := range u.updates {\n\t sqlUpdateArr = append(sqlUpdateArr, up)\n\t updateArgs = append(updateArgs, newVal)\n\t}*/\n\tfor _, up := range u.updates {\n\t\tsqlUpdateArr = append(sqlUpdateArr, up.col)\n\t\tupdateArgs = append(updateArgs, up.val)\n\t}\n\tsqlUpdate := strings.Join(sqlUpdateArr, \",\")\n\n\tsqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)\n\n\tvar allArgs []interface{}\n\tallArgs = append(allArgs, updateArgs...)\n\tallArgs = append(allArgs, whereArgs...)\n\n\tsqlstr := `UPDATE sun_chat.group_orderd_user SET ` + sqlUpdate\n\n\tif len(strings.Trim(sqlWherrs, \" \")) > 0 { //2 for safty\n\t\tsqlstr += \" WHERE \" + sqlWherrs\n\t}\n\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLog(sqlstr, allArgs)\n\t}\n\tres, err := db.Exec(sqlstr, allArgs...)\n\tif err != nil {\n\t\tif LogTableSqlReq.GroupOrderdUser {\n\t\t\tXOLogErr(err)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\tnum, err := res.RowsAffected()\n\tif err != nil {\n\t\tif LogTableSqlReq.GroupOrderdUser {\n\t\t\tXOLogErr(err)\n\t\t}\n\t\treturn 0, err\n\t}\n\n\treturn int(num), nil\n}", "func (gou *GroupOrderdUser) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !gou._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif gou._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tconst sqlstr = `UPDATE sun_chat.group_orderd_user SET ` +\n\t\t`GroupId = ?, UserId = ?` +\n\t\t` WHERE OrderId = ?`\n\n\t// run query\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLog(sqlstr, gou.GroupId, gou.UserId, gou.OrderId)\n\t}\n\t_, err = db.Exec(sqlstr, gou.GroupId, gou.UserId, gou.OrderId)\n\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLogErr(err)\n\t}\n\tOnGroupOrderdUser_AfterUpdate(gou)\n\n\treturn err\n}", "func (gi *Sensor) UpdatePid(db *pg.DB, pid int, state int) error {\r\n\t// log.Printf(\">===>sensorItem.Update()\")\r\n\r\n\t_, updateErr := db.Model(gi).\r\n\t\tSet(\"sensorpid=?0,sensorstate=?1\", pid, state).\r\n\t\tWhere(\"id = ?0\", gi.ID).Update()\r\n\tif updateErr != nil {\r\n\t\tlog.Printf(\"Error while updating item in sensorModel.Update()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", updateErr)\r\n\t\treturn updateErr\r\n\t}\r\n\t// log.Printf(\"Product %s updated successfully in table\", gi.Sensorname)\r\n\treturn nil\r\n}", "func (db *DatabaseService) EditOrder(order *models.Order) error {\n\t_, err := db.db.Model(order).Where(\"id = ?\", order.ID).Update()\n\treturn err\n}", "func (m *mysqlDBRepo) UpdateProcessedForReservation(id, processed int) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `update reservations set processed = ? where id = ?`\n\t_, err := m.DB.ExecContext(ctx, query, processed, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (pi *PillorderItem) Update() *PillorderItemUpdateOne {\n\treturn (&PillorderItemClient{config: pi.config}).UpdateOne(pi)\n}", "func UpdateSubProcess(c *middleware.Context, form dtos.UpdateSubProcessForm) Response {\n\n subProcessId := c.ParamsInt64(\":subProcessId\")\n return updateSubProcessHelper( subProcessId,form)\n}", "func updateProduct(dbRef *pg.DB) {\n\tnewPI := &db.ProductItem{\n\t\tID: 11,\n\t\tName: \"Product 6\",\n\t}\n\tnewPI.Update(dbRef)\n}", "func (a *ProductsApiService) OrdersUpdateProductExecute(r ApiOrdersUpdateProductRequest) (*ProductOrderResponse, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *ProductOrderResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ProductsApiService.OrdersUpdateProduct\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/orders/{id}/line_items/{line_item_id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", url.PathEscape(parameterValueToString(r.id, \"id\")), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"line_item_id\"+\"}\", url.PathEscape(parameterValueToString(r.lineItemId, \"lineItemId\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\tif r.updateProduct == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"updateProduct is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/vnd.conekta-v2.1.0+json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.acceptLanguage != nil {\n\t\tparameterAddToHeaderOrQuery(localVarHeaderParams, \"Accept-Language\", r.acceptLanguage, \"\")\n\t}\n\tif r.xChildCompanyId != nil {\n\t\tparameterAddToHeaderOrQuery(localVarHeaderParams, \"X-Child-Company-Id\", r.xChildCompanyId, \"\")\n\t}\n\t// body params\n\tlocalVarPostBody = r.updateProduct\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := io.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 422 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\t\t\tnewErr.error = formatErrorMessage(localVarHTTPResponse.Status, &v)\n\t\t\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (o *Order) Process() {\n\tfor i := range o.Items {\n\t\titem := &o.Items[i]\n\t\titem.ItemStatus = Waiting\n\t}\n\n\to.Status = Processed\n}", "func (u *__DirectToMessage_Updater) Update(db XODB) (int, error) {\n\tvar err error\n\n\tvar updateArgs []interface{}\n\tvar sqlUpdateArr []string\n\tfor up, newVal := range u.updates {\n\t\tsqlUpdateArr = append(sqlUpdateArr, up)\n\t\tupdateArgs = append(updateArgs, newVal)\n\t}\n\tsqlUpdate := strings.Join(sqlUpdateArr, \",\")\n\n\tsqlWherrs, whereArgs := whereClusesToSql(u.wheres, u.whereSep)\n\n\tvar allArgs []interface{}\n\tallArgs = append(allArgs, updateArgs...)\n\tallArgs = append(allArgs, whereArgs...)\n\n\tsqlstr := `UPDATE ms.direct_to_message SET ` + sqlUpdate\n\n\tif len(strings.Trim(sqlWherrs, \" \")) > 0 { //2 for safty\n\t\tsqlstr += \" WHERE \" + sqlWherrs\n\t}\n\n\tXOLog(sqlstr, allArgs)\n\tres, err := db.Exec(sqlstr, allArgs...)\n\tif err != nil {\n\t\tXOLogErr(err)\n\t\treturn 0, err\n\t}\n\n\tnum, err := res.RowsAffected()\n\tif err != nil {\n\t\tXOLogErr(err)\n\t\treturn 0, err\n\t}\n\n\treturn int(num), nil\n}", "func (m *Module) Update() (*Module, error) {\n\tif err := database.BackendDB.DB.Save(m).Error; err != nil {\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}", "func (m OrderMap) Update(o Order) {\n\tif _, ok := m[o.OrderID]; ok {\n\t\tm[o.OrderID] = o\n\t}\n}", "func (o *Transaction) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (gi *Sensor) Update(db *pg.DB) error {\r\n\tlog.Printf(\"===>sensorItem.Update()\")\r\n\r\n\t_, updateErr := db.Model(gi).\r\n\t\tWhere(\"id = ?0\", gi.ID).Update()\r\n\tif updateErr != nil {\r\n\t\tlog.Printf(\"Error while updating item in sensorItem.Update()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", updateErr)\r\n\t\treturn updateErr\r\n\t}\r\n\tlog.Printf(\"Product %s updated successfully in table\", gi.Sensorname)\r\n\treturn nil\r\n}", "func (*Products) Update(product *Products) (Products, error) {\n\n\t_, err := model.Get(product.ID)\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Get)\", \"Product doesn't exist\")\n\t\treturn Products{}, err\n\t}\n\n\tstmt, err := db.Prepare(\n\t\t\"update products \" +\n\t\t\t\"set name = $1, \" +\n\t\t\t\"unit = $2, \" +\n\t\t\t\"date_updated = now() \" +\n\t\t\t\"where id = $3\")\n\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Prepare)\", err)\n\t\treturn Products{}, err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(product.Name, product.Unit, product.ID)\n\n\tif err != nil {\n\t\tlog.Println(\"(UpdateProduct:Exec)\", err)\n\t\treturn Products{}, err\n\t}\n\n\treturn *product, nil\n\n}", "func UpdateSalesOrder(so *model.SalesOrder, itemsReq []*model.SalesOrderItem) (*model.SalesOrder, error) {\n\tvar e error\n\toldSo := &model.SalesOrder{ID: so.ID}\n\toldSo.Read()\n\tdiff := so.TotalCharge - oldSo.TotalCharge\n\t//save dulu perubahan di so\n\tif e = so.Save(); e == nil {\n\t\tvar itemsReqID []int64\n\t\t// looping yang dari req\n\t\tfor _, req := range itemsReq {\n\t\t\tif req.ID != 0 {\n\t\t\t\t// append itemsReqID\n\t\t\t\titemsReqID = append(itemsReqID, req.ID)\n\t\t\t\t// update soitem di database dari data yang ada request ada di database\n\t\t\t\titem := &model.SalesOrderItem{ID: req.ID}\n\t\t\t\titem.Read()\n\t\t\t\titem.ItemVariant = req.ItemVariant\n\t\t\t\titem.Quantity = req.Quantity\n\t\t\t\titem.UnitPrice = req.UnitPrice\n\t\t\t\titem.Discount = req.Discount\n\t\t\t\titem.Subtotal = req.Subtotal\n\t\t\t\titem.Note = req.Note\n\t\t\t\titem.Save(\"ItemVariant\", \"Quantity\", \"UnitPrice\", \"Discount\", \"Subtotal\", \"Note\")\n\t\t\t} else {\n\t\t\t\treq.SalesOrder = &model.SalesOrder{ID: so.ID}\n\t\t\t\treq.Save()\n\t\t\t}\n\n\t\t\t// update available stock dan commited stock\n\t\t\tstock.CalculateAvailableStockItemVariant(req.ItemVariant)\n\n\t\t}\n\n\t\t// looping id dari database\n\t\tfor _, i := range so.SalesOrderItems {\n\t\t\tif !util.HasElem(itemsReqID, i.ID) {\n\t\t\t\ti.Delete()\n\t\t\t}\n\t\t}\n\n\t\t// update partnership\n\t\tcustomer := &model.Partnership{ID: so.Customer.ID}\n\t\tcustomer.Read()\n\t\tcustomer.TotalDebt += diff\n\t\tcustomer.TotalSpend += diff\n\t\tcustomer.Save(\"TotalDebt\", \"TotalSpend\")\n\t\tvar emptyLoad []string\n\t\temptyLoad = append(emptyLoad, \"sales_order_items\")\n\t\tso, _ = GetDetailSalesOrder(so.ID, emptyLoad)\n\t\treturn so, nil\n\t}\n\n\treturn nil, e\n}", "func (m *MutationResolver) UpdateOrder(\n\tctx context.Context,\n\tid string,\n\tinput *models.UpdateOrderInput,\n) (*pb.Order, error) {\n\tg, err := m.GetOrderClient(registry.ORDER).\n\t\tGetOrder(ctx, &pb.OrderId{Id: id})\n\tif err != nil {\n\t\terrorutils.AddGQLError(ctx, err)\n\t\tm.Logger.Error(err)\n\t\treturn nil, err\n\t}\n\tattr := &pb.OrderUpdateAttributes{}\n\tnorm := normalizeUpdateOrderAttr(input)\n\terr = mapstructure.Decode(norm, attr)\n\tif err != nil {\n\t\tm.Logger.Error(err)\n\t\treturn nil, err\n\t}\n\tif input.Status != nil {\n\t\tattr.Status = statusConverter(*input.Status)\n\t} else {\n\t\tattr.Status = g.Data.Attributes.Status\n\t}\n\to, err := m.GetOrderClient(registry.ORDER).UpdateOrder(ctx, &pb.OrderUpdate{\n\t\tData: &pb.OrderUpdate_Data{\n\t\t\tType: \"order\",\n\t\t\tId: id,\n\t\t\tAttributes: attr,\n\t\t},\n\t})\n\tif err != nil {\n\t\terrorutils.AddGQLError(ctx, err)\n\t\tm.Logger.Error(err)\n\t\treturn nil, err\n\t}\n\tm.Logger.Debugf(\"successfully updated order with ID %s\", o.Data.Id)\n\treturn o, nil\n}", "func (q *quote) Update(w http.ResponseWriter, r *http.Request) {\n\t// Request the interactor to perform the update\n\tquote, err := q.quoteInteractor.Update()\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\t// Success\n\tw.WriteHeader(http.StatusOK)\n\tw.Write(quote)\n\treturn\n}", "func (c *Commentmetum) Update(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !c._exists {\n\t\treturn errors.New(\"update failed: does not exist\")\n\t}\n\n\t// if deleted, bail\n\tif c._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\t// sql query\n\tvar sqlstr = `UPDATE ` + GetTableName(\"commentmeta\") + ` SET ` +\n\t\t`comment_id = ?, meta_key = ?, meta_value = ?` +\n\t\t` WHERE meta_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, c.CommentID, c.MetaKey, c.MetaValue, c.MetaID)\n\t_, err = db.Exec(sqlstr, c.CommentID, c.MetaKey, c.MetaValue, c.MetaID)\n\treturn err\n}", "func (m *postgresDBRepo) UpdateProcessedForReservation(id, processed int) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)\n\tdefer cancel()\n\n\tquery := `update reservations set processed = $1 where id = $2`\n\n\t_, err := m.DB.ExecContext(ctx, query, processed, id)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *PartorderClient) Update() *PartorderUpdate {\n\tmutation := newPartorderMutation(c.config, OpUpdate)\n\treturn &PartorderUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (o *Stock) UpdateP(exec boil.Executor, whitelist ...string) {\n\terr := o.Update(exec, whitelist...)\n\tif err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (c *_Comments) Update(ctx context.Context, db database.DB, models ...*Comment) (int64, error) {\n\tif len(models) == 0 {\n\t\treturn 0, errors.Wrap(query.ErrNoModels, \"nothing to insert\")\n\t}\n\tqueryModels := make([]mapping.Model, len(models))\n\tfor i, model := range models {\n\t\tqueryModels[i] = model\n\t}\n\treturn db.Update(ctx, c.Model, queryModels...)\n}", "func (a *ProcessorsApiService) UpdateProcessorExecute(r ProcessorsApiApiUpdateProcessorRequest) (ProcessorEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodPut\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ProcessorEntity\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ProcessorsApiService.UpdateProcessor\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/processors/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.PathEscape(parameterToString(r.id, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\tif r.body == nil {\n\t\treturn localVarReturnValue, nil, reportError(\"body is required and must be specified\")\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\t// body params\n\tlocalVarPostBody = r.body\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (wou *WorkOrderUpdate) Exec(ctx context.Context) error {\n\t_, err := wou.Save(ctx)\n\treturn err\n}", "func (u SysDBUpdater) Update() error {\n\treturn u.db.Updates(u.fields).Error\n}", "func (c *CoursesDAO) Update(course models.Course) error {\n\terr := db.C(COLLECTION).Update(bson.M{\"ID_Course\": course.ID_Course}, &course)\n\treturn err\n}", "func (o *UpdateProcessByIDsInput) Validate() (rawError cErr.RawErrorInfo) {\n\tif o.BizID <= 0 {\n\t\treturn cErr.RawErrorInfo{\n\t\t\tErrCode: common.CCErrCommParamsInvalid,\n\t\t\tArgs: []interface{}{\"bk_biz_id\"},\n\t\t}\n\t}\n\n\tif len(o.ProcessIDs) == 0 {\n\t\treturn cErr.RawErrorInfo{\n\t\t\tErrCode: common.CCErrCommParamsInvalid,\n\t\t\tArgs: []interface{}{\"process_ids\"},\n\t\t}\n\t}\n\n\tif len(o.ProcessIDs) > common.BKMaxPageSize {\n\t\treturn cErr.RawErrorInfo{\n\t\t\tErrCode: common.CCErrExceedMaxOperationRecordsAtOnce,\n\t\t\tArgs: []interface{}{common.BKMaxPageSize},\n\t\t}\n\t}\n\n\tif len(o.UpdateData) == 0 {\n\t\treturn cErr.RawErrorInfo{\n\t\t\tErrCode: common.CCErrCommParamsInvalid,\n\t\t\tArgs: []interface{}{\"update_data\"},\n\t\t}\n\t}\n\n\tif _, ok := o.UpdateData[common.BKProcessIDField]; ok {\n\t\treturn cErr.RawErrorInfo{\n\t\t\tErrCode: common.CCErrCommParamsInvalid,\n\t\t\tArgs: []interface{}{\"update_data.bk_process_id\"},\n\t\t}\n\t}\n\n\treturn cErr.RawErrorInfo{}\n}", "func (c *Company) Update() {\n\tinitdb.DbInstance.Save(&c)\n\tlog.Println(\"Updated -> \", c)\n}", "func (j *ScheduledJob) Update(ctx context.Context, ex sqlutil.InternalExecutor, txn *kv.Txn) error {\n\tif !j.isDirty() {\n\t\treturn nil\n\t}\n\n\tif j.rec.ScheduleID == 0 {\n\t\treturn errors.New(\"cannot update schedule: missing schedule id\")\n\t}\n\n\tcols, qargs, err := j.marshalChanges()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(qargs) == 0 {\n\t\treturn nil // Nothing changed.\n\t}\n\n\tn, err := ex.ExecEx(ctx, \"sched-update\", txn,\n\t\tsessiondata.InternalExecutorOverride{User: security.RootUserName()},\n\t\tfmt.Sprintf(\"UPDATE %s SET (%s) = (%s) WHERE schedule_id = %d\",\n\t\t\tj.env.ScheduledJobsTableName(), strings.Join(cols, \",\"),\n\t\t\tgeneratePlaceholders(len(qargs)), j.ScheduleID()),\n\t\tqargs...,\n\t)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif n != 1 {\n\t\treturn fmt.Errorf(\"expected to update 1 schedule, updated %d instead\", n)\n\t}\n\n\treturn nil\n}", "func (k *RoutesCollection) Update(route Route) error {\n\t// TODO abstract this check in the go-memdb library itself\n\tif utils.Empty(route.ID) {\n\t\treturn errIDRequired\n\t}\n\n\ttxn := k.db.Txn(true)\n\tdefer txn.Abort()\n\n\terr := deleteRoute(txn, *route.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = txn.Insert(routeTableName, &route)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxn.Commit()\n\treturn nil\n}", "func TestDaoUpdateOrder(t *testing.T) {\n\tconvey.Convey(\"UpdateOrder\", t, func() {\n\t\ta, err := d.UpdateOrder(context.TODO(), 4, 5)\n\t\tconvey.So(err, convey.ShouldBeNil)\n\t\tconvey.So(a, convey.ShouldNotBeNil)\n\t})\n}", "func UpdateShipByOrderID(tx *sql.Tx, ostore string, orderid uint32, shipcode string, time time.Time) (uint32, error) {\n\tsql := fmt.Sprintf(orderSQLString[consignByOrderID], ostore)\n\n\tresult, err := tx.Exec(sql, shipcode, time, orderid)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif affected, _ := result.RowsAffected(); affected == 0 {\n\t\treturn 0, errors.New(\"[change error] : not update ship infomation for order module \")\n\t}\n\n\tid, err := result.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn uint32(id), nil\n}", "func (p *Polling) Update(data Polling) {\n\tdb.Model(p).Updates(data)\n}" ]
[ "0.63025737", "0.5981787", "0.596036", "0.5917244", "0.58530456", "0.584902", "0.5802733", "0.5751912", "0.56828326", "0.5663591", "0.56324154", "0.55789536", "0.5567566", "0.55635744", "0.5523855", "0.5507624", "0.550011", "0.5465838", "0.5436716", "0.5433056", "0.5411519", "0.53765494", "0.53393894", "0.533791", "0.531393", "0.5308551", "0.5304906", "0.52893025", "0.52873164", "0.5269808", "0.52462167", "0.5207979", "0.5205456", "0.51959497", "0.51936966", "0.51851666", "0.5169177", "0.51540035", "0.51490873", "0.51421076", "0.51287264", "0.51065624", "0.51011145", "0.51010776", "0.5093501", "0.5093258", "0.5083186", "0.50791895", "0.5075699", "0.5061862", "0.5061305", "0.50545096", "0.5051693", "0.50392663", "0.50360155", "0.503013", "0.5029724", "0.50069433", "0.5002829", "0.5000979", "0.49999896", "0.49995375", "0.49691236", "0.49614903", "0.49562186", "0.49366868", "0.49344522", "0.49340805", "0.4926791", "0.49186462", "0.49074075", "0.4898838", "0.48987427", "0.48969257", "0.48948896", "0.4865865", "0.48615322", "0.48613277", "0.48613277", "0.48569512", "0.48568028", "0.48553827", "0.48506716", "0.48382738", "0.48353514", "0.48348027", "0.48331374", "0.48174456", "0.48091874", "0.48074192", "0.48037457", "0.4802972", "0.4791071", "0.47870192", "0.47778252", "0.47736385", "0.47626552", "0.47600684", "0.47538424", "0.4738905" ]
0.75137573
0
Save saves the ComponentOrderProcess to the database.
func (cop *ComponentOrderProcess) Save(ctx context.Context) error { if cop.Exists() { return cop.Update(ctx) } return cop.Insert(ctx) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (cop *ComponentOrderProcess) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif cop._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, event, do_status, access_url, remark, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tcop.ID = uint(id)\n\tcop._exists = true\n\n\treturn nil\n}", "func (r *OrderRepositoryImpl) Save(Order domain.Order) error {\n\tif err := r.Conn.Save(&Order).Error; err != nil {\n\t\tlog.Println(err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (app *application) SaveOrder(order models.Order) (int, error) {\n\tid, err := app.DB.InsertOrder(order)\n\tif err != nil {\n\t\tapp.errorLog.Println(err)\n\t\treturn 0, err\n\t}\n\n\treturn id, nil\n}", "func (app *application) SaveOrder(order models.Order) (int, error) {\n\tid, err := app.DB.InsertOrder(order)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn id, nil\n}", "func (od *OrderDetail) Save(ctx context.Context, db DB) error {\n\tif od.Exists() {\n\t\treturn od.Update(ctx, db)\n\t}\n\treturn od.Insert(ctx, db)\n}", "func (yom *YhOrderMaster) Save(db XODB) error {\n\tif yom.Exists() {\n\t\treturn yom.Update(db)\n\t}\n\n\treturn yom.Insert(db)\n}", "func (xpcgi *XPriCompGroupItem) Save(db XODB) error {\n\tif xpcgi.Exists() {\n\t\treturn xpcgi.Update(db)\n\t}\n\n\treturn xpcgi.Insert(db)\n}", "func (o *Orders) SaveOrder(db *gorm.DB) (*Orders, error) {\n\terr := o.PopulateOrderCustomer(db, o.Customer_id)\n\tif err != nil {\n\t\treturn &Orders{}, err\n\t}\n\terr = o.PopulateOrderCar(db, o.Car_id)\n\tif err != nil {\n\t\treturn &Orders{}, err\n\t}\n\terr = db.Debug().Create(&o).Error\n\treturn o, err\n}", "func (p *OrderRepo) Save(order cafmodel.Order) (u cafmodel.Order, err error) {\n\tif err = p.Engine.DB.Table(cafmodel.OrderTable).Save(&order).Error; err != nil {\n\t\terr = p.dbError(err, \"E1554817\", order, corterm.Updated)\n\t}\n\n\tp.Engine.DB.Table(cafmodel.OrderTable).Where(\"id = ?\", order.ID).Find(&u)\n\treturn\n}", "func (og *OrderGood) Save(ctx context.Context) error {\n\tif og.Exists() {\n\t\treturn og.Update(ctx)\n\t}\n\n\treturn og.Insert(ctx)\n}", "func (or *OrderRow) Save() error {\n\treturn DB.Save(or).Error\n}", "func (s *OrderService) ProcessOrder(order spec.Order) error {\n\terr := spec.Validate(order)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Check we have a new order\n\tif order.Status != spec.OrderNew {\n\t\treturn OrderStatusError()\n\t}\n\n\tif err := s.AddOrder(order); err != nil {\n\t\treturn err\n\t}\n\n\terr = s.SetStatus(&order, spec.OrderReceived)\n\tif err != nil {\n\t\tlog.Printf(\"### Failed to update state for order %s\\n\", err)\n\t}\n\n\tlog.Printf(\"### Order %s was saved to state store\\n\", order.ID)\n\n\t// Save order to blob storage as a text file \"report\"\n\t// Also email to the user via SendGrid\n\t// For these to work configure the components in cmd/orders/components\n\t// If un-configured then nothing happens (maybe some errors are logged)\n\n\t// Currently the SendGrid integration in Dapr is fubar\n\t// To be fixed by this PR https://github.com/dapr/components-contrib/pull/1867\n\terr = s.EmailNotify(order)\n\tif err != nil {\n\t\tlog.Printf(\"### Email notification failed %s\\n\", err)\n\t}\n\n\terr = s.SaveReport(order)\n\tif err != nil {\n\t\tlog.Printf(\"### Saving order report failed %s\\n\", err)\n\t}\n\n\t// Fake background order processing, move to processing after 30 seconds\n\ttime.AfterFunc(30*time.Second, func() {\n\t\tlog.Printf(\"### Order %s is now processing\\n\", order.ID)\n\t\t_ = s.SetStatus(&order, spec.OrderProcessing)\n\t})\n\n\t// Fake background order completion, move to complete after 2 minutes\n\ttime.AfterFunc(120*time.Second, func() {\n\t\tlog.Printf(\"### Order %s completed\\n\", order.ID)\n\t\t_ = s.SetStatus(&order, spec.OrderComplete)\n\t})\n\n\treturn nil\n}", "func (c *Component) Save(n string, i interface{}) {\n\tc.GM.DB.Save(n, i)\n}", "func ComponentOrderProcessByID(ctx context.Context, id uint, key ...interface{}) (*ComponentOrderProcess, error) {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// sql query\n\tsqlstr := `SELECT ` +\n\t\t`id, orderid, event, do_status, access_url, remark, created_at, updated_at ` +\n\t\t`FROM ` + tableName +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, id)))\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetSlaveConn()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tcop := ComponentOrderProcess{\n\t\t_exists: true,\n\t}\n\n\tif tx != nil {\n\t\terr = tx.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\terr = dbConn.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &cop, nil\n}", "func (ouo *OrderUpdateOne) Save(ctx context.Context) (*Order, error) {\n\tvar (\n\t\terr error\n\t\tnode *Order\n\t)\n\tif len(ouo.hooks) == 0 {\n\t\tnode, err = ouo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\touo.mutation = mutation\n\t\t\tnode, err = ouo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(ouo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = ouo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, ouo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (cop *ComponentOrderProcess) Update(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn errors.New(\"update failed: marked for deletion\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql query\n\tsqlstr := `UPDATE ` + tableName + ` SET ` +\n\t\t`orderid = ?, event = ?, do_status = ?, access_url = ?, remark = ?, created_at = ?, updated_at = ?` +\n\t\t` WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt, cop.ID)\n\t}\n\treturn err\n}", "func (ou *OrderUpdate) Save(ctx context.Context) (int, error) {\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\tif len(ou.hooks) == 0 {\n\t\taffected, err = ou.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tou.mutation = mutation\n\t\t\taffected, err = ou.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(ou.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = ou.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, ou.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (j *Job) Save(ctx context.Context) (err error) {\n\tt := utils.FromTaskContext(ctx)\n\n\tcontent, err := msgpack.Marshal(j)\n\tif err != nil {\n\t\treturn\n\t}\n\n\terr = contexts.DB.Put(constants.FormatJobKey(t, j.Path), content, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\treturn\n}", "func (wou *WorkOrderUpdate) Save(ctx context.Context) (int, error) {\n\tif wou.update_time == nil {\n\t\tv := workorder.UpdateDefaultUpdateTime()\n\t\twou.update_time = &v\n\t}\n\tif wou.name != nil {\n\t\tif err := workorder.NameValidator(*wou.name); err != nil {\n\t\t\treturn 0, fmt.Errorf(\"ent: validator failed for field \\\"name\\\": %v\", err)\n\t\t}\n\t}\n\tif len(wou._type) > 1 {\n\t\treturn 0, errors.New(\"ent: multiple assignments on a unique edge \\\"type\\\"\")\n\t}\n\tif len(wou.location) > 1 {\n\t\treturn 0, errors.New(\"ent: multiple assignments on a unique edge \\\"location\\\"\")\n\t}\n\tif len(wou.technician) > 1 {\n\t\treturn 0, errors.New(\"ent: multiple assignments on a unique edge \\\"technician\\\"\")\n\t}\n\tif len(wou.project) > 1 {\n\t\treturn 0, errors.New(\"ent: multiple assignments on a unique edge \\\"project\\\"\")\n\t}\n\treturn wou.sqlSave(ctx)\n}", "func (wouo *WorkOrderUpdateOne) Save(ctx context.Context) (*WorkOrder, error) {\n\tif wouo.update_time == nil {\n\t\tv := workorder.UpdateDefaultUpdateTime()\n\t\twouo.update_time = &v\n\t}\n\tif wouo.name != nil {\n\t\tif err := workorder.NameValidator(*wouo.name); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"ent: validator failed for field \\\"name\\\": %v\", err)\n\t\t}\n\t}\n\tif len(wouo._type) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"type\\\"\")\n\t}\n\tif len(wouo.location) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"location\\\"\")\n\t}\n\tif len(wouo.technician) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"technician\\\"\")\n\t}\n\tif len(wouo.project) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"project\\\"\")\n\t}\n\treturn wouo.sqlSave(ctx)\n}", "func (o *NSPortInfo) Save() *bambou.Error {\n\n\treturn bambou.CurrentSession().SaveEntity(o)\n}", "func (o *Port) Save() *bambou.Error {\n\n\treturn bambou.CurrentSession().SaveEntity(o)\n}", "func (ou *OrderUpdate) Exec(ctx context.Context) error {\n\t_, err := ou.Save(ctx)\n\treturn err\n}", "func (m *ApplicationModule) Save(fields ...string) (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\t_, err = o.Update(m, fields...)\n\t} else {\n\t\tm.ID, err = o.Insert(m)\n\t}\n\treturn\n}", "func (_pc *PCCreate) Save(ctx context.Context) (*PC, error) {\n\treturn withHooks(ctx, _pc.sqlSave, _pc.mutation, _pc.hooks)\n}", "func (dcc *DoorCompiledContent) Save(db XODB) error {\n\tif dcc.Exists() {\n\t\treturn dcc.Update(db)\n\t}\n\n\treturn dcc.Insert(db)\n}", "func (c *IntentClassifier) Save(file string) error {\n\n\tbuf := new(bytes.Buffer)\n\tencoder := gob.NewEncoder(buf)\n\n\terr := encoder.Encode(c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error encoding model: %s\", err)\n\t}\n\n\tname, version := c.getMeta()\n\tpersist.Save(file, persist.Modeldata{\n\t\tData: buf.Bytes(),\n\t\tName: name,\n\t\tVersion: version,\n\t})\n\treturn nil\n}", "func (p Produts) Save(wr http.ResponseWriter, r *http.Request) {\n\tvar prod data.Product\n\te := json.NewDecoder(r.Body)\n\n\terr := e.Decode(&prod)\n\tif err != nil {\n\t\thttp.Error(wr, \"Invalid Json\", http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\terr = prod.Validate()\n\tif err != nil {\n\t\thttp.Error(wr, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\terr = data.Save(&prod)\n\tif err != nil {\n\t\thttp.Error(wr, \"Error to save Produts\", http.StatusInternalServerError)\n\t}\n\n}", "func (c *Contractor) save() error {\n\treturn c.persist.save(c.persistData())\n}", "func (e *Department) Save() error { return ent.SaveEnt(e) }", "func (app *service) Save(genesis Genesis) error {\n\t_, err := app.repository.Retrieve()\n\tif err == nil {\n\t\treturn errors.New(\"there is already a Genesis instance\")\n\t}\n\n\tbill := genesis.Bill()\n\terr = app.billService.Save(bill)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttrGenesis, err := app.adapter.ToTransfer(genesis)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn app.trService.Save(trGenesis)\n}", "func (payment *PayPalPayment) Save() {\n\tDB.Set(\"PayPalPayment\", payment.ID, payment)\n}", "func (gou *GroupOrderdUser) Save(db XODB) error {\n\tif gou.Exists() {\n\t\treturn gou.Update(db)\n\t}\n\n\treturn gou.Replace(db)\n}", "func (p *Placements) Save(db *sql.DB) error {\n\tfor i, r := range p.Lines {\n\t\tif r.IrisCode == \"\" {\n\t\t\treturn fmt.Errorf(\"Ligne %d, iris_code vide\", i+1)\n\t\t}\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tx begin %v\", err)\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"temp_placement\", \"iris_code\", \"count\",\n\t\t\"contract_year\"))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"copy in %v\", err)\n\t}\n\tdefer stmt.Close()\n\tfor _, r := range p.Lines {\n\t\tif _, err = stmt.Exec(r.IrisCode, r.Count, r.ContractYear); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"insertion de %+v : %s\", r, err.Error())\n\t\t}\n\t}\n\tif _, err = stmt.Exec(); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement exec flush %v\", err)\n\t}\n\tqueries := []string{`INSERT INTO placement(iris_code,count,contract_year,\n\t\tcommitment_id) \n\tSELECT t.iris_code,t.count,t.contract_year,MIN(c.id) FROM temp_placement t\n\tLEFT OUTER JOIN commitment c ON t.iris_code=c.iris_code\n\tWHERE t.iris_code NOT IN (SELECT DISTINCT iris_code FROM placement)\n GROUP BY 1,2,3`,\n\t\t`UPDATE placement SET count=t.count,contract_year=t.contract_year,\n\t\tcommitment_id=t.id FROM\n\t\t(SELECT t.iris_code,t.count,t.contract_year,MIN(c.id) id FROM temp_placement t\n\t\t\tLEFT OUTER JOIN commitment c ON t.iris_code=c.iris_code\n\t\t\tWHERE t.iris_code IN (SELECT DISTINCT iris_code FROM placement)\n\t\t\tGROUP BY 1,2,3) t\n\t\tWHERE placement.iris_code=t.iris_code`,\n\t\t`DELETE FROM temp_placement`,\n\t}\n\tfor i, q := range queries {\n\t\t_, err = tx.Exec(q)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"requête %d : %s\", i, err.Error())\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tcop._deleted = true\n\n\treturn nil\n}", "func (p *Order) Validate(act coract.Action) (err error) {\n\n\tswitch act {\n\tcase coract.Save:\n\n\t\t// if len(p.Name) > 255 {\n\t\t// \terr = limberr.AddInvalidParam(err, \"name\",\n\t\t// \t\tcorerr.MaximumAcceptedCharacterForVisV,\n\t\t// \t\tdict.R(corterm.Name), 255)\n\t\t// }\n\n\t\t// if p.Price == 0 {\n\t\t// \terr = limberr.AddInvalidParam(err, \"price\",\n\t\t// \t\tcorerr.VisRequired, dict.R(\"price\"))\n\t\t// }\n\n\t\tif len(p.Description) > 255 {\n\t\t\terr = limberr.AddInvalidParam(err, \"description\",\n\t\t\t\tcorerr.MaximumAcceptedCharacterForVisV,\n\t\t\t\tdict.R(corterm.Description), 255)\n\t\t}\n\t}\n\n\treturn err\n}", "func (s *OpenconfigOfficeAp_System_Processes_Process) Validate() error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigOfficeAp_System_Processes_Process\"], s); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (a *App) CreateOrder(o *model.Order, shipAddr *model.Address, billAddr *model.Address) (*model.Order, *model.AppErr) {\n\to.PreSave()\n\treturn a.Srv().Store.Order().Save(o, shipAddr, billAddr)\n}", "func (p *Payment) Save(db XODB) error {\n\tif p.Exists() {\n\t\treturn p.Update(db)\n\t}\n\n\treturn p.Insert(db)\n}", "func (transmission *Transmission) Save(context DatabaseService) error {\n\tvar err error\n\tif transmission.ID == 0 {\n\t\terr = context.Insert(transmission)\n\t} else {\n\t\terr = context.Update(transmission)\n\t}\n\n\treturn err\n}", "func doSaveComponent(comp *component.Component, filepath string) error {\n\tcompJSON, jsonErr := json.MarshalIndent(comp, \"\", \" \")\n\tif jsonErr == nil {\n\t\tfileErr := ioutil.WriteFile(filepath, compJSON, 0744)\n\t\tif fileErr != nil {\n\t\t\treturn fmt.Errorf(\"Failed to write component: %v\\n\", fileErr)\n\t\t}\n\t} else {\n\t\treturn fmt.Errorf(\"Failed to serialize component to JSON: %v\\n\", jsonErr)\n\t}\n\n\treturn nil\n}", "func (oc *OperativerecordCreate) Save(ctx context.Context) (*Operativerecord, error) {\n\tif _, ok := oc.mutation.NurseNumber(); !ok {\n\t\treturn nil, &ValidationError{Name: \"Nurse_Number\", err: errors.New(\"ent: missing required field \\\"Nurse_Number\\\"\")}\n\t}\n\tif v, ok := oc.mutation.NurseNumber(); ok {\n\t\tif err := operativerecord.NurseNumberValidator(v); err != nil {\n\t\t\treturn nil, &ValidationError{Name: \"Nurse_Number\", err: fmt.Errorf(\"ent: validator failed for field \\\"Nurse_Number\\\": %w\", err)}\n\t\t}\n\t}\n\tif _, ok := oc.mutation.OperativeTime(); !ok {\n\t\tv := operativerecord.DefaultOperativeTime()\n\t\toc.mutation.SetOperativeTime(v)\n\t}\n\tvar (\n\t\terr error\n\t\tnode *Operativerecord\n\t)\n\tif len(oc.hooks) == 0 {\n\t\tnode, err = oc.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OperativerecordMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\toc.mutation = mutation\n\t\t\tnode, err = oc.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(oc.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = oc.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, oc.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (p *POSend) ProcessPackage(dealerid int, dealerkey string) ([]byte, error) {\n\tdb := p.db\n\t//10.04.2013 naj - start a transaction\n\ttransaction, err := db.Begin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t//06.02.2013 naj - make a slice to hold the purchase orders\n\tr := make([]AcceptedOrder, 0, len(p.PurchaseOrders))\n\n\t//06.05.2015 ghh -because the system has the ability to push more than one purchase\n\t//order through at the same time it will loop through our array and process each\n\t//one separately\n\tfor i := 0; i < len(p.PurchaseOrders); i++ {\n\t\t//06.02.2013 naj - stick the current PO into a new variable to keep the name short.\n\t\tc := p.PurchaseOrders[i]\n\n\n\t\t//06.02.2013 naj - put the current PONumber into the response\n\t\tr = r[0 : len(r)+1]\n\t\tr[i].DealerPO = c.DealerPONumber\n\n\t\t//06.10.2014 naj - check to see if the po is already in the system.\n\t\t//If it is and it's not processed yet, delete the the po and re-enter it.\n\t\t//If it is and it's processed return an error.\n\t\tvar result sql.Result\n\t\tvar temppoid int\n\t\tvar tempstatus int\n\n\t\t//06.02.2015 ghh - first we grab the Ponumber that is being sent to use and we're going to see\n\t\t//if it has already been processed by the vendor\n\t\terr = transaction.QueryRow(`select ifnull(POID, 0 ), ifnull( Status, 0 ) \n\t\t\t\t\t\t\t\t\t\t\tfrom PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\twhere DealerID = ? and DealerPONumber = ?`,\n\t\t\t\t\tdealerid, c.DealerPONumber).Scan(&temppoid, &tempstatus)\n\n\t\t//case err == sql.ErrNoRows:\n\t\t//if we have a PO already there and its not been processed yet by the vendor then we're going\n\t\t//to delete it as we're uploading it a second time.\n\t\tif temppoid > 0 { \n\t\t\tif tempstatus == 0 { //has it been processed by vendor yet?\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrders \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere DealerID=? \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tand DealerPONumber=? `, dealerid, c.DealerPONumber )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t//now delete the items from the old $_POST[\n\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderItems \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\n\t\t\t\t\t//08.06.2015 ghh - delete units from linked units table\n\t\t\t\t\tresult, err = transaction.Exec(`delete from PurchaseOrderUnits \n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\twhere POID=? `, temppoid )\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t//if we get here then we must have found an existing PO so lets log it and return\n\t\t\tif tempstatus > 0 {\n\t\t\t\terr = errors.New(\"Error: 16207 Purchase order already sent and pulled by vendor.\")\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif err != sql.ErrNoRows {\n\t\t\t\t//if there was an error then return it\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\n\n\t\t\t//06.02.2013 naj - create the PO record in the database.\n\t\t\tresult, err = transaction.Exec(`insert into PurchaseOrders (\n\t\t\t\tDealerID, BSVKeyID, DealerPONumber, POReceivedDate, BillToFirstName, BillToLastName, BillToCompanyName, \n\t\t\t\tBillToAddress1, BillToAddress2, BillToCity, BillToState, BillToZip, \n\t\t\t\tBillToCountry, BillToPhone, BillToEmail, \n\t\t\t\tShipToFirstName, ShipToLastName, ShipToCompanyName, ShipToAddress1,\n\t\t\t\tShipToAddress2, ShipToCity, ShipToState, ShipToZip, ShipToCountry, \n\t\t\t\tShipToPhone, ShipToEmail, \n\t\t\t\tPaymentMethod, LastFour, ShipMethod) values \n\t\t\t\t(?, ?, curdate(), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \n\t\t\t\t?, ?, ?, ?, ?, ?, ? )`, \n\t\t\t\tdealerid, c.BSVKeyID, c.DealerPONumber,\n\t\t\t\tc.BillToFirstName, c.BillToLastName, c.BillToCompanyName, c.BillToAddress1, \n\t\t\t\tc.BillToAddress2, c.BillToCity, c.BillToState, c.BillToZip, c.BillToCountry, \n\t\t\t\tc.BillToPhone, c.BillToEmail,\n\t\t\t\tc.ShipToFirstName, c.ShipToLastName, c.ShipToCompanyName, c.ShipToAddress1, \n\t\t\t\tc.ShipToAddress2, c.ShipToCity, c.ShipToState, c.ShipToZip, c.ShipToCountry, \n\t\t\t\tc.ShipToPhone, c.ShipToEmail, c.PaymentMethod, c.LastFour, c.ShipMethod )\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.02.2013 naj - get the POID assigned to the PO\n\t\t\tpoid, err := result.LastInsertId()\n\n\t\t\t//06.02.2013 naj - format the POID and put the assigned POID into the response\n\t\t\ttemp := strconv.FormatInt(poid, 10)\n\n\t\t\tr[i].InternalID = temp\n\t\t\tr[i].DealerKey = dealerkey\n\n\t\t\tif err != nil {\n\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t_ = transaction.Rollback()\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\t//06.05.2015 ghh - now loop through the items array and insert all the parts for\n\t\t\t//the order\n\t\t\tfor j := 0; j < len(c.Items); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderItems (POID, PartNumber, VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Items[j].PartNumber, c.Items[j].VendorID, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Items[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\n\t\t\t\t\t//08.06.2015 ghh - ( now that we've written the line into the table we need to\n\t\t\t\t\t//query a few things in order to build a proper response to send back. Things\n\t\t\t\t\t//we want to know are how many will ship, any supersession or other known info\n\t\t\t\t\t//current cost...\n\n\t\t\t}\n\n\n\t\t\t//07.21.2015 ghh - now loop through the list of units and add them to the PO\n\t\t\tfor j := 0; j < len(c.Units); j++ {\n\t\t\t\t//06.02.2013 naj - attach the parts to the current PO.\n\t\t\t\t_, err := transaction.Exec(`insert into PurchaseOrderUnits (POID, ModelNumber, Year,\n\t\t\t\t\t\t\t\t\t\t\t\t\tVendorID, OrderCode, Colors, Details \n\t\t\t\t\t\t\t\t\t\t\t\t\tQuantity) value (?, ?, ?, ?, ?, ?, ?, ?)`, \n\t\t\t\t\t\t\t\t\t\t\t\t\tpoid, c.Units[j].ModelNumber, c.Units[j].Year, \n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].VendorID, c.Units[j].OrderCode,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Colors, c.Units[j].Details,\n\t\t\t\t\t\t\t\t\t\t\t\t\tc.Units[j].Qty)\n\t\t\t\tif err != nil {\n\t\t\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t\t\t_ = transaction.Rollback()\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t//06.05.2015 ghh - now we'll take the array and marshal it back into a json\n\t//array to be returned to client\n\tif len(r) > 0 {\n\t\t//06.02.2013 naj - JSON Encode the response data.\n\t\tresp, err := json.Marshal(r)\n\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\t//10.04.2013 naj - commit the transaction\n\t\terr = transaction.Commit()\n\t\tif err != nil {\n\t\t\t//10.04.2013 naj - rollback transaction\n\t\t\t_ = transaction.Rollback()\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn resp, nil\n\t} else {\n\t\t//10.04.2013 naj - rollback transaction\n\t\t_ = transaction.Rollback()\n\t\treturn nil, errors.New(\"No valid parts were in the purchase order\")\n\t\t}\n\n}", "func (log *Log) LogProcesso(db *gorm.DB, codProcesso string, codIbge uint32, nomeTabela string, operacao string, codUsuario uint32) error {\n\n\tif operacao == \"i\" {\n\t\terr := db.Debug().Exec(\"INSERT INTO log(cod_usuario, nome_tabela, operacao, espelho, cod_int_1, cod_processo) VALUES (?, ?, ?, ?, ?, ?)\", codUsuario, nomeTabela, operacao, log.Espelho, codIbge, codProcesso).Error\n\n\t\treturn err\n\t}\n\n\tdb.Table(\"processo\").Select(\"CONCAT(IFNULL(cod_processo, ''), ';', IFNULL(cod_ibge, ''), ';', IFNULL(descricao, ''))\").Where(\"cod_processo = ? AND cod_ibge = ?\", codProcesso, codIbge).Row().Scan(&log.Espelho)\n\n\terr := db.Debug().Exec(\"INSERT INTO log(cod_usuario, nome_tabela, operacao, espelho, cod_int_1, cod_processo) VALUES (?, ?, ?, ?, ?, ?)\", codUsuario, nomeTabela, operacao, log.Espelho, codIbge, codProcesso).Error\n\n\treturn err\n}", "func ServiceSave(service entity.Service) {\n\tdb := util.DbConnect()\n\n\tresult, err := db.Exec(`INSERT INTO SERVICE(user_id, service_type_id, is_archived, contact_number, price, image, description, total_reviewer, total_rating)\n\t\tVALUES (?, ?, ?, ?, ?, ?, ?, ?, ? )`, service.UserID, service.ServiceTypeID, 0, service.ContactNumber,\n\t\tservice.Price, service.Image, service.Description, 0, 0)\n\n\tif err != nil {\n\t\tpanic(err)\n\t} else {\n\t\tfmt.Println(result)\n\t}\n\n\tdefer db.Close()\n}", "func executeSave(\n\ttx *bolt.Tx,\n\tns string,\n\tdoc *document.Document,\n\tforce bool,\n) error {\n\ts, err := database.CreateStore(tx, ns)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trec, exists, err := s.TryGetRecord(doc.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !force && doc.Revision != rec.GetRevision() {\n\t\treturn &protavo.OptimisticLockError{\n\t\t\tDocumentID: doc.ID,\n\t\t\tGivenRev: doc.Revision,\n\t\t\tActualRev: rec.GetRevision(),\n\t\t\tOperation: \"save\",\n\t\t}\n\t}\n\n\tvar new *database.Record\n\tif exists {\n\t\tnew, err = updateRecord(s, doc, rec)\n\t} else {\n\t\tnew, err = createRecord(s, doc)\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc, err := marshalContent(doc)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := s.PutContent(doc.ID, c); err != nil {\n\t\treturn err\n\t}\n\n\treturn unmarshalRecordManagedFields(new, doc)\n}", "func (oiuo *OrderInfoUpdateOne) Save(ctx context.Context) (*OrderInfo, error) {\n\tvar (\n\t\terr error\n\t\tnode *OrderInfo\n\t)\n\toiuo.defaults()\n\tif len(oiuo.hooks) == 0 {\n\t\tnode, err = oiuo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderInfoMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\toiuo.mutation = mutation\n\t\t\tnode, err = oiuo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(oiuo.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = oiuo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, oiuo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (s *orderRepo) CreateOrder(order entity.Order) (int64, *resterrors.RestErr) {\n\n\tquery := `\n\t\tINSERT INTO tab_order (\n\t\t\tuser_id,company_id,accept_tip\n\t\t) VALUES (?,?,?);\n\t\t`\n\n\tstmt, err := s.db.Prepare(query)\n\tif err != nil {\n\t\terrorCode := \"Error 0006: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to prepare the query statement in the Create a order\", errorCode), err)\n\t\treturn 0, resterrors.NewInternalServerError(fmt.Sprintf(\"%sDatabase error\", errorCode))\n\t}\n\tdefer stmt.Close()\n\n\tinsertResult, err := stmt.Exec(\n\t\torder.UserID,\n\t\torder.CompanyID,\n\t\torder.AcceptTip)\n\tif err != nil {\n\t\terrorCode := \"Error 0007: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to execute Query in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\torderID, err := insertResult.LastInsertId()\n\tif err != nil {\n\t\terrorCode := \"Error 0008: \"\n\t\tlog.Println(fmt.Sprintf(\"%sError when trying to get LastInsertId in the Create order\", errorCode), err)\n\t\treturn 0, mysqlutils.HandleMySQLError(errorCode, err)\n\t}\n\n\treturn orderID, nil\n}", "func (t *OpenconfigSystem_System_Processes_Process) Validate(opts ...ygot.ValidationOption) error {\n\tif err := ytypes.Validate(SchemaTree[\"OpenconfigSystem_System_Processes_Process\"], t, opts...); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Commentmetum) Save(db XODB) error {\n\tif c.Exists() {\n\t\treturn c.Update(db)\n\t}\n\n\treturn c.Insert(db)\n}", "func (p *Orderer) Process(e dag.Event) (err error) {\n\terr, selfParentFrame := p.checkAndSaveEvent(e)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = p.handleElection(selfParentFrame, e)\n\tif err != nil {\n\t\t// election doesn't fail under normal circumstances\n\t\t// storage is in an inconsistent state\n\t\tp.crit(err)\n\t}\n\treturn err\n}", "func (r *Repository) InsertOrder(data *Order) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func (orderTree *OrderTree) Commit() error {\n\terr := orderTree.Save()\n\tif err == nil {\n\t\terr = orderTree.orderDB.Commit()\n\t}\n\treturn err\n}", "func (wou *WorkOrderUpdate) Exec(ctx context.Context) error {\n\t_, err := wou.Save(ctx)\n\treturn err\n}", "func (oiu *OrderInfoUpdate) Save(ctx context.Context) (int, error) {\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\toiu.defaults()\n\tif len(oiu.hooks) == 0 {\n\t\taffected, err = oiu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderInfoMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\toiu.mutation = mutation\n\t\t\taffected, err = oiu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(oiu.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = oiu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, oiu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func NewOrder(order map[string]interface{}) (err error) {\r\n\tmaster := \"\"\r\n\tdetail := \"\"\r\n\tpayment := \"\"\r\n\tinventory := \"\"\r\n\r\n\t// Get a new reference to the ordered items and remove it from the map.\r\n\tpayments := order[\"payments\"]\r\n\titemsOrdered := order[\"items\"]\r\n\tdelete(order, \"items\")\r\n\tdelete(order, \"payments\")\r\n\r\n\t// Get the master insert query\r\n\tif master, err = MaptoInsert(order, \"orders\"); err != nil {\r\n\t\tCheckError(\"Error Mapping the Order to SQL.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\tmaster += \"SET @last_id := (SELECT LAST_INSERT_ID());\"\r\n\r\n\t// Get the details insert query\r\n\tfor _, _value := range itemsOrdered.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"ordereditems\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Ordered Items to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tinventory += fmt.Sprintf(`UPDATE products SET onhand = onhand - %v, serialnumbers = replace(serialnumbers, '%s', '') WHERE itemcode = \"%s\";`, _value.(map[string]interface{})[\"quantity\"], _value.(map[string]interface{})[\"serialnumber\"], _value.(map[string]interface{})[\"itemcode\"])\r\n\t\tmaster += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t\tmaster = strings.Replace(master, `\"null\"`, `\"\"`, -1)\r\n\t}\r\n\r\n\t// Get the payments insert query\r\n\tfor _, _value := range payments.([]interface{}) {\r\n\t\tif detail, err = MaptoInsert(_value.(map[string]interface{}), \"payments\"); err != nil {\r\n\t\t\tCheckError(\"Error Mapping the Payments to SQL.\", err, false)\r\n\t\t\treturn err\r\n\t\t}\r\n\r\n\t\t// Build out the needed queries\r\n\t\tpayment += strings.Replace(fmt.Sprintf(\"%v\", detail), `\"\"`, \"@last_id\", -1)\r\n\t}\r\n\r\n\t// Save the Order and Reduce inventory\r\n\tif err = Modify(master + payment + inventory); err != nil {\r\n\t\tCheckError(\"Error creating the Order.\", err, false)\r\n\t\treturn err\r\n\t}\r\n\r\n\treturn\r\n}", "func (d *Dao) SaveOrderID(c context.Context, id string) error {\n\terr := d.SaveOrder(c, id)\n\treturn err\n}", "func (h *CoproCommitmentBatch) Save(db *sql.DB) error {\n\tfor i, l := range h.Lines {\n\t\tif l.Reference == \"\" {\n\t\t\treturn fmt.Errorf(\"Ligne %d, Reference vide\", i+1)\n\t\t}\n\t\tif l.IRISCode == \"\" {\n\t\t\treturn fmt.Errorf(\"Ligne %d, IRISCode vide\", i+1)\n\t\t}\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"begin transaction %v\", err)\n\t}\n\tif _, err = tx.Exec(`DELETE FROM copro_commitment`); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"delete query %v\", err)\n\t}\n\tstmt, err := tx.Prepare(pq.CopyIn(\"copro_commitment\", \"reference\", \"iris_code\"))\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement creation %v\", err)\n\t}\n\tfor _, l := range h.Lines {\n\t\tif _, err = stmt.Exec(l.Reference, l.IRISCode); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"statement execution %v\", err)\n\t\t}\n\t}\n\tif _, err = stmt.Exec(); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement flush exec %v\", err)\n\t}\n\tif err = stmt.Close(); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"statement close %v\", err)\n\t}\n\tqueries := []string{`UPDATE commitment SET copro_id=q.copro_id, \n\thousing_id=NULL, renew_project_id=NULL FROM\n\t\t(SELECT c.id AS commitment_id, co.id AS copro_id FROM copro co \n\t\t\tJOIN copro_commitment cc ON co.reference = cc.reference\n\t\t\tJOIN commitment c ON cc.iris_code=c.iris_code) q \n\tWHERE commitment.id=q.commitment_id`,\n\t\t`DELETE FROM copro_commitment`}\n\tfor i, q := range queries {\n\t\tif _, err = tx.Exec(q); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"query %d %v\", i, err)\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (ouo *OrderUpdateOne) Exec(ctx context.Context) error {\n\t_, err := ouo.Save(ctx)\n\treturn err\n}", "func (s Service) AddOrders(o OrdersCreateReq) error {\n\ttx, err := s.db.Begin()\n\tif err != nil {\n\t\tlog.Println(\"Failed to start a transaction\", err.Error())\n\t\treturn err\n\t}\n\n\torderTx, err := tx.Prepare(\"INSERT INTO api_db.order(id, email, total_price, total_weight_grams, order_number) VALUES(?,?,?,?,?)\")\n\tif err != nil {\n\t\tlog.Println(\"Failed to prepare the order transaction\", err.Error())\n\t\treturn err\n\t}\n\n\taddrTx, err := tx.Prepare(\"INSERT INTO api_db.order_shipping_address(order_id, first_name, address1, postcode) VALUES(?, ?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Println(\"Failed to prepare the Address transaction\", err.Error())\n\t\treturn err\n\t}\n\n\tshippingLineTx, err := tx.Prepare(\"INSERT INTO api_db.order_to_shipping_line(order_id, shipping_line_id, title, price) VALUES(?, ?, ?, ?)\")\n\tif err != nil {\n\t\tlog.Println(\"Failed to prepare the Shipping Line transaction\", err.Error())\n\n\t\treturn err\n\t}\n\n\toLen := len(o)\n\tfor i := 0; i < oLen; i++ {\n\n\t\tcurrOrder := o[i]\n\t\tlog.Printf(\"Processing order #%d 📤\\n\", currOrder.ID)\n\t\t_, err = orderTx.Exec(\n\t\t\tcurrOrder.ID,\n\t\t\tcurrOrder.Email,\n\t\t\tcurrOrder.TotalPrice,\n\t\t\tcurrOrder.TotalWeightGrams,\n\t\t\tcurrOrder.OrderNumber,\n\t\t)\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\tlog.Printf(\"Failed to save order #%d: %s\", currOrder.ID, err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tshippingAddr := currOrder.ShippingAddress\n\n\t\t// insert the shipping adddress\n\t\t_, err := addrTx.Exec(currOrder.ID, shippingAddr.FirstName, shippingAddr.Address1, shippingAddr.PostCode)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Failed to save the shipping address\", err.Error())\n\t\t\treturn err\n\t\t}\n\n\t\tslLen := len(currOrder.ShippingLines)\n\t\tfor j := 0; j < slLen; j++ {\n\n\t\t\tsl := currOrder.ShippingLines[j]\n\t\t\t_, err := shippingLineTx.Exec(currOrder.ID, sl.ID, sl.Title, sl.Price)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(\"Failed to save a shipping line\", err.Error())\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\tlog.Println(\"Couldn't commit the transaction\")\n\t\treturn err\n\t}\n\n\tfor i := 0; i < oLen; i++ {\n\t\tcurrOrder := o[i]\n\t\tlog.Printf(\"Delivering order #%d\\n\", currOrder.ID)\n\t\ts.deliverOrderChan <- currOrder\n\t\tlog.Printf(\"Delivered order #%d\\n\", currOrder.ID)\n\t}\n\n\treturn nil\n}", "func (p *PaymentCreditJournalBatch) Save(db *sql.DB) error {\n\tif err := p.validate(); err != nil {\n\t\treturn err\n\t}\n\ttx, err := db.Begin()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"tx begin %v\", err)\n\t}\n\tif _, err = tx.Exec(`DELETE FROM payment_credit_journal \n\t\tWHERE EXTRACT(year FROM creation_date)=EXTRACT(year FROM CURRENT_DATE)`); err != nil {\n\t\ttx.Rollback()\n\t\treturn fmt.Errorf(\"initial delete %v\", err)\n\t}\n\tvar c, m time.Time\n\tfor i, l := range p.Lines {\n\t\tc = time.Date(int(l.CreationDate/10000), time.Month(l.CreationDate/100%100),\n\t\t\tint(l.CreationDate%100), 0, 0, 0, 0, time.UTC)\n\t\tm = time.Date(int(l.ModificationDate/10000),\n\t\t\ttime.Month(l.ModificationDate/100%100), int(l.ModificationDate%100), 0, 0,\n\t\t\t0, 0, time.UTC)\n\t\tif _, err = tx.Exec(`INSERT INTO payment_credit_journal (chapter,function,\n\t\t\tcreation_date,modification_date,name,value) VALUES($1,$2,$3,$4,$5,$6)`,\n\t\t\tl.Chapter, l.Function, c, m, l.Name, l.Value); err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn fmt.Errorf(\"insert %d %v\", i, err)\n\t\t}\n\t}\n\treturn tx.Commit()\n}", "func (repo *OrderRepository) Create(order *models.Order) (id int64, err error) {\n\tstatement := \"insert into `order` (vendorId, customerId, orderDetails, status) values (?, ?, ?, ?)\"\n\tstmt, err := Db.Prepare(statement)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\tresult, err := stmt.Exec(order.VendorId, order.CustomerId, order.OrderDetails, order.Status)\n\tif err != nil {\n\t\tcommon.Error.Println(\"Order could not be created \", err)\n\t\treturn\n\t}\n\treturn result.LastInsertId()\n\n}", "func (w *Worker) processOrder(order orders.Order) {\n\tlog.Println(\n\t\t\"level\", \"INFO\",\n\t\t\"object\", \"workers.worker\",\n\t\t\"method\", \"processOrder\",\n\t\t\"msg\", \"new order to proces\",\n\t\t\"order\", order,\n\t)\n\tw.resultStream <- order.ToRecord()\n}", "func (m *Module) Save(project *Project) (*Module, error) {\n\tif err := database.BackendDB.DB.Model(project).Association(\"Modules\").Append(m).Error; err != nil {\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}", "func (or *mongoOrderRepository) Store(order *models.Order) (*models.Order, error) {\n\t(*order).ID = bson.NewObjectId()\n\terr := or.Conn.C(COLLECTION).Insert(order)\n\treturn order, err\n}", "func (resolution *PolicyResolution) recordProcessingOrder(cik *ComponentInstanceKey) {\n\tkey := cik.GetKey()\n\tif !resolution.componentProcessingOrderHas[key] {\n\t\tresolution.componentProcessingOrderHas[key] = true\n\t\tresolution.ComponentProcessingOrder = append(resolution.ComponentProcessingOrder, key)\n\t}\n}", "func (channel *Channel) Save() {\n\t// Build the data with be saved\n\tdat, err := json.Marshal(channel.ToSerialize())\n\tif err != nil {\n\t\tlog.Errorf(\"Can't serialize the channel: %s\", err)\n\t\treturn\n\t}\n\n\tdb := storage.GetDB()\n\tdb.Put([]byte(fmt.Sprintf(\"/channel/%s\", channel.Name)), dat, nil)\n\tlog.Debugf(\"Channel %s saved into database\", channel.Name)\n}", "func (j *Job) Persist(ctx context.Context, fs afs.Service) error {\n\tJSON, err := json.Marshal(j)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to marshal job %+v\", j)\n\t}\n\terr = fs.Upload(ctx, j.ProcessURL, file.DefaultFileOsMode, bytes.NewReader(JSON))\n\treturn err\n}", "func (xpss *XPipelineSalesStage) Save(db XODB) error {\n\tif xpss.Exists() {\n\t\treturn xpss.Update(db)\n\t}\n\n\treturn xpss.Insert(db)\n}", "func (s *OrderService) SaveReport(order spec.Order) error {\n\tblobName := \"order_\" + order.ID + \".txt\"\n\tblobMetadata := map[string]string{\n\t\t\"ContentType\": \"text/plain\",\n\t\t\"blobName\": blobName,\n\t}\n\tblobData := \"----------\\nTitle: \" + order.Title + \"\\nOrder ID: \" + order.ID +\n\t\t\"\\nUser: \" + order.ForUserID + \"\\nAmount: \" + fmt.Sprintf(\"%f\", order.Amount) + \"\\n----------\"\n\n\trequest := &dapr.InvokeBindingRequest{}\n\trequest.Metadata = blobMetadata\n\trequest.Data = []byte(blobData)\n\trequest.Name = s.reportOutputName\n\trequest.Operation = \"create\"\n\n\tif err := s.client.InvokeOutputBinding(context.Background(), request); err != nil {\n\t\tlog.Printf(\"### Problem sending to blob / report output: %s\", err.Error())\n\t\treturn err\n\t}\n\n\tlog.Printf(\"### Order report %s was saved to blob storage\", blobName)\n\n\treturn nil\n}", "func (ctl *taskController) Save() error {\n\treturn ctl.saveImpl(true)\n}", "func (r *Repository) InsertOrderItem(data *OrderItem) (err error) {\n\n\terr = r.db.Create(data).Error\n\n\treturn\n}", "func (epc *EquipmentPortCreate) Save(ctx context.Context) (*EquipmentPort, error) {\n\tif epc.create_time == nil {\n\t\tv := equipmentport.DefaultCreateTime()\n\t\tepc.create_time = &v\n\t}\n\tif epc.update_time == nil {\n\t\tv := equipmentport.DefaultUpdateTime()\n\t\tepc.update_time = &v\n\t}\n\tif len(epc.definition) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"definition\\\"\")\n\t}\n\tif epc.definition == nil {\n\t\treturn nil, errors.New(\"ent: missing required edge \\\"definition\\\"\")\n\t}\n\tif len(epc.parent) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"parent\\\"\")\n\t}\n\tif len(epc.link) > 1 {\n\t\treturn nil, errors.New(\"ent: multiple assignments on a unique edge \\\"link\\\"\")\n\t}\n\treturn epc.sqlSave(ctx)\n}", "func (s PgPromotionStore) Save(promotion *model.Promotion) (*model.Promotion, *model.AppErr) {\n\tq := `INSERT INTO public.promotion(promo_code, type, amount, description, starts_at, ends_at, created_at, updated_at) VALUES(:promo_code, :type, :amount, :description, :starts_at, :ends_at, :created_at, :updated_at) RETURNING promo_code`\n\tif _, err := s.db.NamedExec(q, promotion); err != nil {\n\t\tif IsUniqueConstraintViolationError(err) {\n\t\t\treturn nil, model.NewAppErr(\"PgPromotionStore.Save\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgUniqueConstraintPromotion, http.StatusInternalServerError, nil)\n\t\t}\n\t\treturn nil, model.NewAppErr(\"PgPromotionStore.Save\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgSavePromotion, http.StatusInternalServerError, nil)\n\t}\n\treturn promotion, nil\n}", "func (itl *ItemLine) Save(tx *sql.Tx) error {\n\tquery := `INSERT INTO item_line(item_line_nm, item_line_desc, item_line_dt, item_value, category_id, user_id, rev_by, rev_dt)\n\tVALUES($1, $2, $3, $4, $5, $6, $7, CURRENT_TIMESTAMP) RETURNING id`\n\treturn tx.QueryRow(query,\n\t\titl.itemLineNm,\n\t\titl.itemLineDesc,\n\t\titl.itemLineDt,\n\t\titl.itemLineValue,\n\t\titl.categoryID,\n\t\titl.userID,\n\t\titl.revBy).Scan(&itl.id)\n}", "func (s *Service) Save(p *entity.Project) (entity.ID, error) {\n\tp.ID = entity.NewID()\n\tp.CreatedAt = time.Now()\n\treturn s.repo.Save(p)\n}", "func (dtm *DirectToMessage) Save(db XODB) error {\n\tif dtm.Exists() {\n\t\treturn dtm.Update(db)\n\t}\n\n\treturn dtm.Replace(db)\n}", "func (c *Contractor) saveSync() error {\n\treturn c.persist.saveSync(c.persistData())\n}", "func (oliu *OrderLineItemUpdate) Save(ctx context.Context) (int, error) {\n\tvar (\n\t\terr error\n\t\taffected int\n\t)\n\toliu.defaults()\n\tif len(oliu.hooks) == 0 {\n\t\taffected, err = oliu.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderLineItemMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\toliu.mutation = mutation\n\t\t\taffected, err = oliu.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn affected, err\n\t\t})\n\t\tfor i := len(oliu.hooks) - 1; i >= 0; i-- {\n\t\t\tif oliu.hooks[i] == nil {\n\t\t\t\treturn 0, fmt.Errorf(\"ent: uninitialized hook (forgotten import ent/runtime?)\")\n\t\t\t}\n\t\t\tmut = oliu.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, oliu.mutation); err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn affected, err\n}", "func (m *Order) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (o *ParkingSpace) Save() error {\n\tif o.ID == \"\" {\n\t\to.ID = uuid.NewV4().String()\n\t}\n\tif err := dynahelpers.DynamoPut(o); err != nil {\n\t\tlog.Printf(\"Error saving object of type %s\\n\", utils.GetType(o))\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s Store) Save(param ParameterSet) error {\n\tbytes, err := json.MarshalIndent(param, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.backingStore.Save(ItemType, \"\", param.Name, bytes)\n}", "func (orderTree *OrderTree) InsertOrder(quote map[string]string) error {\n\n\t// orderID := ToBigInt(quote[\"order_id\"])\n\t// key := GetKeyFromBig(orderID)\n\n\t// if orderTree.OrderExist(key) {\n\t// \t// orderTree.RemoveOrderByID(key)\n\t// \tfmt.Println(\"Order already exsited, do nothing or should remove it?\")\n\t// \treturn\n\t// }\n\n\tprice := ToBigInt(quote[\"price\"])\n\n\tvar orderList *OrderList\n\n\tif !orderTree.PriceExist(price) {\n\t\t// create and save\n\t\tfmt.Println(\"CREATE price list\", price.String())\n\t\torderList = orderTree.CreatePrice(price)\n\t} else {\n\t\torderList = orderTree.PriceList(price)\n\t}\n\n\t// order will be insert if there is a follow orderList key\n\tif orderList != nil {\n\n\t\torder := NewOrder(quote, orderList.Key)\n\n\t\tif orderList.OrderExist(order.Key) {\n\t\t\t// orderTree.RemoveOrderByID(key)\n\t\t\torderTree.RemoveOrder(order)\n\t\t\t// fmt.Println(\"Order already exsited, do nothing or should remove it?\")\n\t\t\t// return nil\n\t\t}\n\n\t\torderList.AppendOrder(order)\n\t\t// orderTree.OrderMap[order.OrderID] = order\n\t\torderList.Save()\n\t\torderList.SaveOrder(order)\n\t\torderTree.Item.Volume = Add(orderTree.Item.Volume, order.Item.Quantity)\n\n\t\t// increase num of orders, should be big.Int ?\n\t\torderTree.Item.NumOrders++\n\t\t// fmt.Println(\"Num order\", orderTree.Item.NumOrders)\n\t\t// update\n\t\t// should use batch to optimize the performance\n\t\treturn orderTree.Save()\n\t}\n\n\treturn nil\n}", "func (csi ChannelStoreImpl) Save(channel *models.Channel, db *gorm.DB) *u.AppError {\n\ttransaction := db.Begin()\n\tchannel.PreSave()\n\tif appError := channel.IsValid(false); appError != nil {\n\t\ttransaction.Rollback()\n\t\treturn u.NewLocAppError(\"channelStoreImpl.Save.channel.PreSave\", appError.ID, nil, appError.DetailedError)\n\t}\n\tif !transaction.NewRecord(channel) {\n\t\ttransaction.Rollback()\n\t\treturn u.NewLocAppError(\"channelStoreImpl.Save\", \"save.transaction.create.already_exist\", nil, \"Channel Name: \"+channel.ChannelName)\n\t}\n\tif err := transaction.Create(&channel).Error; err != nil {\n\t\ttransaction.Rollback()\n\t\treturn u.NewLocAppError(\"channelStoreImpl.Save\", \"save.transaction.create.encounterError :\"+err.Error(), nil, \"\")\n\t}\n\ttransaction.Commit()\n\treturn nil\n}", "func (oliuo *OrderLineItemUpdateOne) Save(ctx context.Context) (*OrderLineItem, error) {\n\tvar (\n\t\terr error\n\t\tnode *OrderLineItem\n\t)\n\toliuo.defaults()\n\tif len(oliuo.hooks) == 0 {\n\t\tnode, err = oliuo.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*OrderLineItemMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\toliuo.mutation = mutation\n\t\t\tnode, err = oliuo.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(oliuo.hooks) - 1; i >= 0; i-- {\n\t\t\tif oliuo.hooks[i] == nil {\n\t\t\t\treturn nil, fmt.Errorf(\"ent: uninitialized hook (forgotten import ent/runtime?)\")\n\t\t\t}\n\t\t\tmut = oliuo.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, oliuo.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func (jc *JobpositionCreate) Save(ctx context.Context) (*Jobposition, error) {\n\tif _, ok := jc.mutation.Positionname(); !ok {\n\t\treturn nil, &ValidationError{Name: \"positionname\", err: errors.New(\"ent: missing required field \\\"positionname\\\"\")}\n\t}\n\tvar (\n\t\terr error\n\t\tnode *Jobposition\n\t)\n\tif len(jc.hooks) == 0 {\n\t\tnode, err = jc.sqlSave(ctx)\n\t} else {\n\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\tmutation, ok := m.(*JobpositionMutation)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t}\n\t\t\tjc.mutation = mutation\n\t\t\tnode, err = jc.sqlSave(ctx)\n\t\t\tmutation.done = true\n\t\t\treturn node, err\n\t\t})\n\t\tfor i := len(jc.hooks) - 1; i >= 0; i-- {\n\t\t\tmut = jc.hooks[i](mut)\n\t\t}\n\t\tif _, err := mut.Mutate(ctx, jc.mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn node, err\n}", "func SavePersonallyProcuredMove(db *pop.Connection, ppm *PersonallyProcuredMove) (*validate.Errors, error) {\n\tresponseVErrors := validate.NewErrors()\n\tvar responseError error\n\n\ttransactionErr := db.Transaction(func(db *pop.Connection) error {\n\t\ttransactionError := errors.New(\"Rollback The transaction\")\n\n\t\tif ppm.HasRequestedAdvance {\n\t\t\tif ppm.Advance != nil {\n\t\t\t\tif verrs, err := db.ValidateAndSave(ppm.Advance); verrs.HasAny() || err != nil {\n\t\t\t\t\tresponseVErrors.Append(verrs)\n\t\t\t\t\tresponseError = errors.Wrap(err, \"Error Saving Advance\")\n\t\t\t\t\treturn transactionError\n\t\t\t\t}\n\t\t\t\tppm.AdvanceID = &ppm.Advance.ID\n\t\t\t}\n\t\t}\n\n\t\tif verrs, err := db.ValidateAndSave(ppm); verrs.HasAny() || err != nil {\n\t\t\tresponseVErrors.Append(verrs)\n\t\t\tresponseError = errors.Wrap(err, \"Error Saving PPM\")\n\t\t\treturn transactionError\n\t\t}\n\n\t\treturn nil\n\n\t})\n\n\tif transactionErr != nil {\n\t\treturn responseVErrors, responseError\n\t}\n\n\treturn responseVErrors, responseError\n}", "func (t *TradePool) cancelProcess(order *comm.Order) (bool, comm.Order) {\n\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_TRACK, \"%s-%s TradePool CancelProcess Order ID(%d), Time(%d)\\n\", t.Symbol, t.MarketType.String(), order.ID, order.Timestamp)\n\tif order == nil {\n\t\tfmt.Printf(\"%s-%s Cancel input order==nil error!\\n\", t.Symbol, t.MarketType.String())\n\t\treturn false, comm.Order{}\n\t}\n\tif order.Symbol != t.Symbol {\n\t\tfmt.Printf(\"Market(%s-%s) cancelProcess illegal order with symbol(%s) to %s Match Engine\", t.Symbol, t.MarketType.String(), order.Symbol, t.Symbol)\n\t\treturn false, comm.Order{}\n\t}\n\n\tif order.AorB == comm.TradeType_BID {\n\t\tt.bidPoolRWMutex.Lock(\"CancelProcess BID\")\n\t\tdefer t.bidPoolRWMutex.Unlock(\"CancelProcess BID\")\n\n\t\t/// debug:\n\t\tTimeDot1 := time.Now().UnixNano()\n\t\ttarget, suc := t.orderCheck(order)\n\t\tif !suc {\n\t\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_TRACK,\n\t\t\t\t\"%s-%s Cancel OrderCheck ID(%d) fail! Order perhaps not exist or had been processed or input order illegal!\\n\",\n\t\t\t\tt.Symbol, t.MarketType.String(), order.ID)\n\t\t\treturn false, comm.Order{}\n\t\t}\n\n\t\t/// Output the order corpse for DS operate use\n\t\torderCorpse := t.bidPoolIDSlice[target].Value.(comm.Order)\n\t\tbRet := t.rmBidOrderByTarget(target)\n\n\t\t/// debug:\n\t\tTimeDot2 := time.Now().UnixNano()\n\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_TRACK,\n\t\t\t`%s-%s TradePool CancelProcess bid order complete==\n\tuser:%s, id:%d, type:%s, time:%d, price:%f, volume:%f\t, ****USE_TIME:%f\n`,\n\t\t\tt.Symbol, t.MarketType.String(),\n\t\t\torderCorpse.Who, orderCorpse.ID, orderCorpse.AorB.String(), orderCorpse.Timestamp, orderCorpse.Price, orderCorpse.Volume, float64(TimeDot2-TimeDot1)/float64(1*time.Second),\n\t\t)\n\t\treturn bRet, orderCorpse\n\t} else if order.AorB == comm.TradeType_ASK {\n\t\tt.askPoolRWMutex.Lock(\"CancelProcess ASK\")\n\t\tdefer t.askPoolRWMutex.Unlock(\"CancelProcess ASK\")\n\n\t\t/// debug:\n\t\tTimeDot1 := time.Now().UnixNano()\n\t\ttarget, suc := t.orderCheck(order)\n\t\tif !suc {\n\t\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_TRACK,\n\t\t\t\t\"%s-%s Cancel OrderCheck ID(%d) fail! Order perhaps not exist or had been processed or input order illegal!\\n\",\n\t\t\t\tt.Symbol, t.MarketType.String(), order.ID)\n\t\t\treturn false, comm.Order{}\n\t\t}\n\n\t\t/// Output the order corpse for DS operate use\n\t\torderCorpse := t.askPoolIDSlice[target].Value.(comm.Order)\n\t\tbRet := t.rmAskOrderByTarget(target)\n\n\t\t/// debug:\n\t\tTimeDot2 := time.Now().UnixNano()\n\t\tcomm.DebugPrintf(MODULE_NAME_SORTSLICE, comm.LOG_LEVEL_TRACK,\n\t\t\t`%s-%s TradePool CancelProcess ask order complete==\n\tuser:%s, id:%d, type:%s, time:%d, price:%f, volume:%f\t, ****USE_TIME:%f\n`,\n\t\t\tt.Symbol, t.MarketType.String(),\n\t\t\torderCorpse.Who, orderCorpse.ID, orderCorpse.AorB.String(), orderCorpse.Timestamp, orderCorpse.Price, orderCorpse.Volume, float64(TimeDot2-TimeDot1)/float64(1*time.Second),\n\t\t)\n\t\treturn bRet, orderCorpse\n\t} else {\n\t\tfmt.Printf(\"%s-%s CancelProcess illegal order type!\", t.Symbol, t.MarketType.String())\n\t\treturn false, comm.Order{}\n\t}\n}", "func (s *BlockStorage) SaveOrderBlock(block *tradeblocks.OrderBlock) error {\n\tif err := s.createStorageDir(); err != nil {\n\t\treturn err\n\t}\n\thash := block.Hash()\n\tp := filepath.Join(ordersDir(s.dir), hash)\n\tf, err := os.Create(p)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer f.Close()\n\tif err := json.NewEncoder(f).Encode(block); err != nil {\n\t\treturn err\n\t}\n\treturn f.Close()\n}", "func (o *Order) Process() {\n\tfor i := range o.Items {\n\t\titem := &o.Items[i]\n\t\titem.ItemStatus = Waiting\n\t}\n\n\to.Status = Processed\n}", "func PlaceOrderDetails(order *Order) (err error) {\n\n\torder.Status = \"Failed!\"\n\tdefer mutex.Unlock()\n\terr = GetProductByID(&order.Product, strconv.Itoa(int(order.ProductID)))\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = GetCustomerByID(&order.Customer, strconv.Itoa(int(order.CustomerID)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tmutex.Lock()\n\t_ = GetProductByID(&order.Product, strconv.Itoa(int(order.ProductID)))\n\tif order.Product.Quantity < order.Quantity {\n\t\torder.Status = \"Processed!\"\n\t\tif err = Config.DB.Create(order).Error; err != nil {\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\torder.Product.Quantity = order.Product.Quantity - order.Quantity\n\tUpdateProductDetails(&order.Product, strconv.Itoa(int(order.ProductID)))\n\torder.Status = \"Successful!\"\n\tif err = Config.DB.Create(order).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (tx TxRepo) SaveCartItem(c checkout.CartItemSchema) error {\n\t_, err := tx.NamedExec(checkout.StmtInsertCartItem, c)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (oliuo *OrderLineItemUpdateOne) Exec(ctx context.Context) error {\n\t_, err := oliuo.Save(ctx)\n\treturn err\n}", "func (nos *NewOrderServiceImpl) ProcessTransaction(req *models.NewOrder) (*models.NewOrderOutput, error) {\n\tlog.Printf(\"Starting the New Order Transaction for row: c=%d w=%d d=%d n=%d\", req.CustomerID, req.WarehouseID, req.DistrictID, req.UniqueItems)\n\n\tresult, err := nos.execute(req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error occured while executing the new order transaction. Err: %v\", err)\n\t}\n\n\tlog.Printf(\"Completed the New Order Transaction for row: c=%d w=%d d=%d n=%d\", req.CustomerID, req.WarehouseID, req.DistrictID, req.UniqueItems)\n\treturn result, nil\n}", "func (s *Store) CreateOrder(o *models.Order) (po *models.Order, err error) {\n\tc := s.orders // Basic Validation\n\n\to.Time = primitive.NewDateTimeFromTime(time.Now())\n\n\tif err = o.Validate(); err != nil {\n\t\treturn po, err\n\t}\n\n\tif err = s.processOrder(o); err != nil {\n\t\treturn po, err\n\t}\n\n\tif id, err := s.w.Add(c, o); err != nil {\n\t\treturn nil, err\n\t} else if o.ID, err = primitive.ObjectIDFromHex(id); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn o, err\n}", "func (db Database) saveProduct() error {\n\treturn makeError()\n}", "func (component *Component) Save(filename string) error {\n\treturn util.SaveYAML(filename, component)\n}", "func (self *ProductService) beforeSave(product *entity.Product, productSave *ProductSave) error {\n\tif err := product.Merge(productSave.Product, productSave.Changes.Fields); err != nil {\n\t\treturn err\n\t}\n\n\tproduct.GenerateHandle()\n\n\treturn nil\n}", "func (company *Company) Save() {\n\tDB.Set(\"Company\", company.ID, company)\n}", "func (orm *JallyORM) Save(q Query) error {\n\tqTxt, values := q.Insert()\n\treturn orm.Query(qTxt, values...).Exec()\n}" ]
[ "0.6069941", "0.5661553", "0.5620989", "0.5588996", "0.55009925", "0.54862595", "0.541738", "0.5408916", "0.5407348", "0.5355476", "0.5277565", "0.5203932", "0.5147161", "0.5084345", "0.50703514", "0.5038039", "0.5016763", "0.5013877", "0.49604553", "0.4956536", "0.49514148", "0.49246508", "0.48931012", "0.4860107", "0.48305917", "0.48072577", "0.480597", "0.48058718", "0.47995514", "0.47771013", "0.4772064", "0.4759683", "0.47459754", "0.47249505", "0.470957", "0.47053072", "0.46990028", "0.46915585", "0.46742302", "0.46653518", "0.46629745", "0.46564606", "0.46557167", "0.46516392", "0.46278077", "0.46219385", "0.46213365", "0.4603423", "0.4597059", "0.4587251", "0.45856488", "0.45848775", "0.4578407", "0.4564088", "0.4528137", "0.4518155", "0.45108855", "0.45049605", "0.45047137", "0.4504626", "0.4504573", "0.44875726", "0.44857863", "0.44823134", "0.44818714", "0.44765234", "0.44763827", "0.4468592", "0.44612142", "0.44606158", "0.4456085", "0.44418404", "0.44368866", "0.4436145", "0.4432296", "0.4431657", "0.44243434", "0.44242993", "0.4423917", "0.44231242", "0.4416936", "0.44168925", "0.44137016", "0.44098204", "0.4394229", "0.4390088", "0.4388964", "0.4383725", "0.43828648", "0.43806523", "0.4374786", "0.43729034", "0.4372344", "0.43674812", "0.43652087", "0.4362741", "0.43615073", "0.4360036", "0.43537155", "0.4345943" ]
0.7703521
0
Delete deletes the ComponentOrderProcess from the database.
func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error { var err error var dbConn *sql.DB // if deleted, bail if cop._deleted { return nil } tx, err := components.M.GetConnFromCtx(ctx) if err != nil { dbConn, err = components.M.GetMasterConn() if err != nil { return err } } tableName, err := GetComponentOrderProcessTableName(key...) if err != nil { return err } //1 // sql query with composite primary key sqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?` // run query utils.GetTraceLog(ctx).Debug("DB", zap.String("SQL", fmt.Sprint(sqlstr, cop.ID))) if tx != nil { _, err = tx.Exec(sqlstr, cop.ID) } else { _, err = dbConn.Exec(sqlstr, cop.ID) } if err != nil { return err } // set deleted cop._deleted = true return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (process *Process) Delete() {\n\tsql := \"DELETE FROM `process` WHERE id=?\"\n\tquery, err := database.Connection.Prepare(sql)\n\tif err != nil {\n\t\tfmt.Println(\"Delete #1 error for process:\")\n\t\tfmt.Println(err)\n\t}\n\tquery.Exec(process.Action.ID)\n}", "func (p *ProcessDefinition) Delete(by QueryProcessDefinitionBy, query map[string]string) error {\n\terr := p.client.doDelete(\"/process-definition/\"+by.String(), query)\n\treturn err\n}", "func (od *OrderDetail) Delete(ctx context.Context, db DB) error {\n\tswitch {\n\tcase !od._exists: // doesn't exist\n\t\treturn nil\n\tcase od._deleted: // deleted\n\t\treturn nil\n\t}\n\t// delete with composite primary key\n\tconst sqlstr = `DELETE FROM northwind.order_details ` +\n\t\t`WHERE order_id = ? AND product_id = ?`\n\t// run\n\tlogf(sqlstr, od.OrderID, od.ProductID)\n\tif _, err := db.ExecContext(ctx, sqlstr, od.OrderID, od.ProductID); err != nil {\n\t\treturn logerror(err)\n\t}\n\t// set deleted\n\tod._deleted = true\n\treturn nil\n}", "func (r *Repository) DeleteOrder(data *Order) (err error) {\n\n\terr = r.db.Delete(data).Error\n\n\treturn\n}", "func (xpcgi *XPriCompGroupItem) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !xpcgi._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif xpcgi._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM x_showroom.x_pri_comp_group_item WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, xpcgi.ID)\n\t_, err = db.Exec(sqlstr, xpcgi.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\txpcgi._deleted = true\n\n\treturn nil\n}", "func (db *DatabaseService) DeleteOrder(order *models.Order) error {\n\t_, err := db.db.Model(order).Where(\"id = ?\", order.ID).Update()\n\treturn err\n}", "func (p *Process) deleteProcess() error {\n\tif p.command == nil || p.command.Process == nil {\n\t\treturn nil\n\t}\n\n\t// Close the process watcher\n\tif p.cancelChan != nil {\n\t\tclose(p.cancelChan)\n\t}\n\n\tp.log.Debugf(\"Process %s deleted\", p.name)\n\treturn nil\n}", "func (yom *YhOrderMaster) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !yom._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif yom._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM devdb.yh_order_master WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, yom.ID)\n\t_, err = db.Exec(sqlstr, yom.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tyom._deleted = true\n\n\treturn nil\n}", "func (d *Db) DeleteOrder(idOrder int) int {\n\tvar query = \"DELETE FROM orders WHERE idOrder = ?\"\n\tstmt, err := d.Prepare(query)\n\tif err != nil {\n\t\tfmt.Println(\"DeleteOrder Preperation Err: \", err)\n\t}\n\t// Make query with our stmt, passing in name argument\n\tres, err := stmt.Exec(idOrder)\n\tif err != nil {\n\t\tfmt.Println(\"DeleteOrder Query Err: \", err)\n\t}\n\n\trowsAffected, _ := res.RowsAffected()\n\n\treturn int(rowsAffected)\n}", "func (m *CommunicationsDAO) Delete(communication Communication) error {\n\terr := db.C(COLLECTION).Remove(&communication)\n\treturn err\n}", "func (o *Order) Delete() error {\n\tif o.State != Empty && o.State != Ongoing {\n\t\treturn fmt.Errorf(\"order in wrong state\")\n\t}\n\to.TrackChange(o, &Deleted{})\n\treturn nil\n}", "func (sC StoreController) DeleteOrder(context *gin.Context) {\n\tid, err := strconv.ParseInt(context.Param(\"orderId\"), 10, 64)\n\tif err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\t\n\tmessage, err := sC.StoreService.Delete(id)\n\tif err != nil {\n\t\tcontext.JSON(http.StatusBadRequest, gin.H{\"error\": err.Error()})\n\t\treturn\n\t}\n\n\tcontext.JSON(http.StatusOK, gin.H{\"data\": message})\n}", "func (cop *ComponentOrderProcess) Deleted() bool {\n\treturn cop._deleted\n}", "func (p *Payment) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !p._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif p._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM public.payment WHERE payment_id = $1`\n\n\t// run query\n\tXOLog(sqlstr, p.PaymentID)\n\t_, err = db.Exec(sqlstr, p.PaymentID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tp._deleted = true\n\n\treturn nil\n}", "func (a *Agent) DeleteProcess(pid int) error {\n\t//err := a.processes[pid].Process.Kill()\n\terr := a.processes[pid].Process.Signal(os.Interrupt)\n\tif err != nil {\n\t\treturn err\n\t}\n\t_, err = a.processes[pid].Process.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdelete(a.processes, pid)\n\treturn nil\n}", "func (em *EndingMessage) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !em._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif em._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query with composite primary key\n\tconst sqlstr = `DELETE FROM custmchat.ending_message WHERE ent_id = ? AND platform = ?`\n\n\t// run query\n\tXOLog(sqlstr, em.EntID, em.Platform)\n\t_, err = db.Exec(sqlstr, em.EntID, em.Platform)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tem._deleted = true\n\n\treturn nil\n}", "func (og *OrderGood) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif og._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetOrderGoodTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE order_gid = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, og.OrderGid)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, og.OrderGid)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, og.OrderGid)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tog._deleted = true\n\n\treturn nil\n}", "func OrderDestroy(c buffalo.Context) error {\n\tcu, err := CurrentUser(c)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\torder := &models.Order{}\n\n\tif err := tx.Where(\"user_id = ? AND id = ?\", cu.ID, c.Param(\"order_id\")).First(order); err != nil {\n\t\treturn c.Error(404, err)\n\t}\n\n\tif err := tx.Destroy(order); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn c.Render(200, r.JSON(map[string]interface{}{\n\t\t\"message\": \"order deleted successfully\",\n\t}))\n}", "func (client *ClientImpl) DeleteProcessBehavior(ctx context.Context, args DeleteProcessBehaviorArgs) error {\n\trouteValues := make(map[string]string)\n\tif args.ProcessId == nil {\n\t\treturn &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessId\"}\n\t}\n\trouteValues[\"processId\"] = (*args.ProcessId).String()\n\tif args.BehaviorRefName == nil || *args.BehaviorRefName == \"\" {\n\t\treturn &azuredevops.ArgumentNilOrEmptyError{ArgumentName: \"args.BehaviorRefName\"}\n\t}\n\trouteValues[\"behaviorRefName\"] = *args.BehaviorRefName\n\n\tlocationId, _ := uuid.Parse(\"d1800200-f184-4e75-a5f2-ad0b04b4373e\")\n\t_, err := client.Client.Send(ctx, http.MethodDelete, locationId, \"6.0-preview.2\", routeValues, nil, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (dtm *DirectToMessage) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !dtm._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif dtm._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM ms.direct_to_message WHERE Id = ?`\n\n\t// run query\n\tXOLog(sqlstr, dtm.Id)\n\t_, err = db.Exec(sqlstr, dtm.Id)\n\tif err != nil {\n\t\tXOLogErr(err)\n\t\treturn err\n\t}\n\n\t// set deleted\n\tdtm._deleted = true\n\n\tOnDirectToMessage_AfterDelete(dtm)\n\n\treturn nil\n}", "func (r *Repository) DeleteOrderItem(data *OrderItem) (err error) {\n\n\terr = r.db.Delete(data).Error\n\n\treturn\n}", "func (w *WorkflowInstance) Delete(trs *db.Transaction) error {\n\tif err := db.DeleteStructTx(trs.Tx, constants.TableCoreGroups, &db.Options{\n\t\tConditions: builder.Equal(\"code\", w.ID),\n\t}); err != nil {\n\t\treturn customerror.New(http.StatusInternalServerError, \"workflow instance delete\", err.Error())\n\t}\n\treturn nil\n}", "func (o *CMFPaidprogramComment) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no CMFPaidprogramComment provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cmfPaidprogramCommentPrimaryKeyMapping)\n\tsql := \"DELETE FROM `cmf_paidprogram_comment` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from cmf_paidprogram_comment\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for cmf_paidprogram_comment\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (p *PaymentNeed) Delete(db *sql.DB) error {\n\tres, err := db.Exec(`DELETE FROM payment_need WHERE id=$1`, p.ID)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"delete %v\", err)\n\t}\n\tcount, err := res.RowsAffected()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"rows affected %v\", err)\n\t}\n\tif count != 1 {\n\t\treturn fmt.Errorf(\"payment need introuvable\")\n\t}\n\treturn err\n}", "func (o *Phenotypeprop) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"chado: no Phenotypeprop provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), phenotypepropPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"phenotypeprop\\\" WHERE \\\"phenotypeprop_id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"chado: unable to delete from phenotypeprop\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (p *process) Delete() error {\n\tvar (\n\t\targs = append(p.container.runtimeArgs, \"delete\", \"-f\", p.container.id)\n\t\tcmd = exec.Command(p.container.runtime, args...)\n\t)\n\n\tcmd.SysProcAttr = osutils.SetPDeathSig()\n\tout, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s: %v\", out, err)\n\t}\n\treturn nil\n}", "func (o *PaymentObject) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no PaymentObject provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), paymentObjectPrimaryKeyMapping)\n\tsql := \"DELETE FROM `payment_objects` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from payment_objects\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for payment_objects\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (s *Service) DeleteOrder(w http.ResponseWriter, r *http.Request) {\n\t// Get the order ID\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\t// Delete the recipe\n\tif err := usecases.DeleteOrderByID(s.storage, id); err != nil {\n\t\tlog.Errorf(\"DeleteOrder: %v\", err)\n\t\tutils.ResponseWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\tutils.ResponseWithJSON(w, http.StatusOK, map[string]string{\"result\": \"success\"})\n}", "func (s PgPromotionStore) Delete(code string) *model.AppErr {\n\tif _, err := s.db.NamedExec(\"DELETE from public.promotion WHERE promo_code = :code\", map[string]interface{}{\"code\": code}); err != nil {\n\t\treturn model.NewAppErr(\"PgPromotionStore.Delete\", model.ErrInternal, locale.GetUserLocalizer(\"en\"), msgDeletePromotion, http.StatusInternalServerError, nil)\n\t}\n\treturn nil\n}", "func (qs ControlQS) Delete(db models.DBInterface) (int64, error) {\n\tc := &models.PositionalCounter{}\n\n\ts, p := qs.whereClause(c)\n\ts = `DELETE FROM \"heatcontrol_control\"` + s\n\n\tresult, err := db.Exec(s, p...)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn result.RowsAffected()\n}", "func (pmt *Payment) Delete(db *bolt.DB) error {\n\tid := paymentID(pmt.Height, pmt.CreatedOn, pmt.Account)\n\treturn deleteEntry(db, paymentBkt, id)\n}", "func (sS StoreService) Delete(id int64) (message string, err error) {\n\tvar order models.Order\n\terr = sS.DB.First(&order, id).Error\n\tif err != nil {\n\t\treturn \"not found!\", err\n\t}\n\n\tsS.DB.Delete(&order)\n\treturn \"success\", err\n}", "func (ts *TaskService) Delete(requestCtx context.Context, req *taskAPI.DeleteRequest) (*taskAPI.DeleteResponse, error) {\n\tdefer logPanicAndDie(log.G(requestCtx))\n\tlog.G(requestCtx).WithFields(logrus.Fields{\"id\": req.ID, \"exec_id\": req.ExecID}).Debug(\"delete\")\n\n\tresp, err := ts.taskManager.DeleteProcess(requestCtx, req, ts.runcService)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.G(requestCtx).WithFields(logrus.Fields{\n\t\t\"pid\": resp.Pid,\n\t\t\"exit_status\": resp.ExitStatus,\n\t}).Debug(\"delete succeeded\")\n\treturn resp, nil\n}", "func (m *Mongo) DeleteOrderItem(dbname string, id string) error {\n\tc := m.session.DB(dbname).C(orderItemsCollectionName)\n\treturn c.RemoveId(bson.ObjectIdHex(id))\n}", "func (o *DMessageEmbed) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no DMessageEmbed provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), dMessageEmbedPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"d_message_embeds\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from d_message_embeds\")\n\t}\n\n\treturn nil\n}", "func (o *Transaction) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *Transaction) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (o *AuthMessage) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no AuthMessage provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), authMessagePrimaryKeyMapping)\n\tsql := \"DELETE FROM `auth_message` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from auth_message\")\n\t}\n\n\treturn nil\n}", "func (p *DeliveryConfigProcessor) Delete(cli *Client) error {\n\tif p.rawDeliveryConfig == nil {\n\t\terr := p.Load()\n\t\tif err != nil {\n\t\t\treturn xerrors.Errorf(\"Failed to load delivery config: %w\", err)\n\t\t}\n\t}\n\t_, err := commonRequest(cli, \"DELETE\", \"/managed/delivery-configs/\"+p.deliveryConfig.Application, requestBody{})\n\treturn err\n}", "func (pm *ProductModel) Delete(product Product) error {\n\tif _, err := pm.DB.Query(DELETE_PRODUCT_STMT, product.ProductName); err != nil {\n\t\tlog.Printf(\"error occurred on deleting a specific product : %s\", err)\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *Dao) Delete(query bson.M) (n int, err error) {\n\n\tdb := d.Database.Clone()\n\tdefer db.Close()\n\n\tinfo, err := db.C(d.Collection.Name).RemoveAll(query)\n\n\treturn info.Removed, err\n}", "func (*Products) Delete(id int64) error {\n\n\t_, err := model.Get(id)\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Get)\", \"Product doesn't exist\")\n\t\treturn err\n\t}\n\n\tstmt, err := db.Prepare(\n\t\t\"delete from products where id = $1\")\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Prepare)\", err)\n\t\treturn err\n\t}\n\n\tdefer stmt.Close()\n\n\t_, err = stmt.Exec(id)\n\n\tif err != nil {\n\t\tlog.Println(\"(DeleteProduct:Physical:Exec)\", err)\n\n\t\tstmt, err = db.Prepare(\n\t\t\t\"update products \" +\n\t\t\t\t\"set deleted = true, \" +\n\t\t\t\t\"date_updated = now() \" +\n\t\t\t\t\"where id = $1\")\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeteleProduct:Logic:Prepare)\", err)\n\t\t\treturn err\n\t\t}\n\n\t\t_, err = stmt.Exec(id)\n\n\t\tif err != nil {\n\t\t\tlog.Println(\"(DeleteProduct:Logic:Exec)\", err)\n\t\t\treturn err\n\t\t}\n\n\t}\n\n\treturn nil\n}", "func (o *VSP) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no VSP provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), vspPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"vsp\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from vsp\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for vsp\")\n\t}\n\n\treturn rowsAff, nil\n}", "func (c *Commentmetum) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !c._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif c._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tvar sqlstr = `DELETE FROM ` + GetTableName(\"commentmeta\") + ` WHERE meta_id = ?`\n\n\t// run query\n\tXOLog(sqlstr, c.MetaID)\n\t_, err = db.Exec(sqlstr, c.MetaID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tc._deleted = true\n\n\treturn nil\n}", "func (m *Manager) Delete() error {\n\treturn m.b.Delete()\n}", "func (gou *GroupOrderdUser) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !gou._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif gou._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM sun_chat.group_orderd_user WHERE OrderId = ?`\n\n\t// run query\n\tif LogTableSqlReq.GroupOrderdUser {\n\t\tXOLog(sqlstr, gou.OrderId)\n\t}\n\t_, err = db.Exec(sqlstr, gou.OrderId)\n\tif err != nil {\n\t\tif LogTableSqlReq.GroupOrderdUser {\n\t\t\tXOLogErr(err)\n\t\t}\n\t\treturn err\n\t}\n\n\t// set deleted\n\tgou._deleted = true\n\n\tOnGroupOrderdUser_AfterDelete(gou)\n\n\treturn nil\n}", "func (s *PurchaseOrdersEndpoint) Delete(ctx context.Context, division int, id *types.GUID) error {\n\tb, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/purchaseorder/PurchaseOrders\", division) // #nosec\n\tu, err := api.AddOdataKeyToURL(b, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, r, requestError := s.client.NewRequestAndDo(ctx, \"DELETE\", u.String(), nil, nil)\n\tif requestError != nil {\n\t\treturn requestError\n\t}\n\n\tif r.StatusCode != http.StatusNoContent {\n\t\tbody, _ := ioutil.ReadAll(r.Body) // #nosec\n\t\treturn fmt.Errorf(\"Failed with status %v and body %v\", r.StatusCode, body)\n\t}\n\n\treturn nil\n}", "func (c *OrderClient) Delete() *OrderDelete {\n\tmutation := newOrderMutation(c.config, OpDelete)\n\treturn &OrderDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (m *LogDAO) Delete(logMessage model.LogMessage) error {\n\t_, err := db.Model(logMessage).WherePK().Delete()\n\treturn err\n}", "func (s *OrderItemService) Delete(ctx context.Context, id string) error {\n\treturn s.repo.Delete(ctx, id)\n}", "func (o *CMFBalanceChargeAdmin) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no CMFBalanceChargeAdmin provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cmfBalanceChargeAdminPrimaryKeyMapping)\n\tsql := \"DELETE FROM `cmf_balance_charge_admin` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from cmf_balance_charge_admin\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for cmf_balance_charge_admin\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (dcc *DoorCompiledContent) Delete(db XODB) error {\n\tvar err error\n\n\t// if doesn't exist, bail\n\tif !dcc._exists {\n\t\treturn nil\n\t}\n\n\t// if deleted, bail\n\tif dcc._deleted {\n\t\treturn nil\n\t}\n\n\t// sql query\n\tconst sqlstr = `DELETE FROM public.door_compiled_content WHERE id = $1`\n\n\t// run query\n\tXOLog(sqlstr, dcc.ID)\n\t_, err = db.Exec(sqlstr, dcc.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tdcc._deleted = true\n\n\treturn nil\n}", "func (d DB) DeleteWorkflow(ctx context.Context, id string, state int32) error {\n\treturn nil\n}", "func (o *Item) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Item provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), itemPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"items\\\" WHERE \\\"id\\\"=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from items\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for items\")\n\t}\n\n\treturn rowsAff, nil\n}", "func (o *Organism) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"chado: no Organism provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), organismPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"organism\\\" WHERE \\\"organism_id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"chado: unable to delete from organism\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *DMessageEmbed) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (a *Client) OrderOrderGroupDelete(params *OrderOrderGroupDeleteParams, authInfo runtime.ClientAuthInfoWriter) error {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewOrderOrderGroupDeleteParams()\n\t}\n\n\t_, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"OrderOrderGroup_delete\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/order/orderGroup/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &OrderOrderGroupDeleteReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (csi ChannelStoreImpl) Delete(channel *models.Channel, db *gorm.DB) *u.AppError {\n\ttransaction := db.Begin()\n\tif appError := channel.IsValid(true); appError != nil {\n\t\ttransaction.Rollback()\n\t\treturn u.NewLocAppError(\"channelStoreImpl.Delete.channel.PreSave\", appError.ID, nil, appError.DetailedError)\n\t}\n\tif err := transaction.Delete(&channel).Error; err != nil {\n\t\ttransaction.Rollback()\n\t\treturn u.NewLocAppError(\"channelStoreImpl.Delete\", \"update.transaction.delete.encounterError :\"+err.Error(), nil, \"\")\n\t}\n\ttransaction.Commit()\n\treturn nil\n}", "func (o *Vendor) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Vendor provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), vendorPrimaryKeyMapping)\n\tsql := \"DELETE FROM `vendors` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from vendors\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for vendors\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (s *PurchaseOrderLinesEndpoint) Delete(ctx context.Context, division int, id *types.GUID) error {\n\tb, _ := s.client.ResolvePathWithDivision(\"/api/v1/{division}/purchaseorder/PurchaseOrderLines\", division) // #nosec\n\tu, err := api.AddOdataKeyToURL(b, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, r, requestError := s.client.NewRequestAndDo(ctx, \"DELETE\", u.String(), nil, nil)\n\tif requestError != nil {\n\t\treturn requestError\n\t}\n\n\tif r.StatusCode != http.StatusNoContent {\n\t\tbody, _ := ioutil.ReadAll(r.Body) // #nosec\n\t\treturn fmt.Errorf(\"Failed with status %v and body %v\", r.StatusCode, body)\n\t}\n\n\treturn nil\n}", "func (c *Control) Delete(db models.DBInterface) error {\n\t_, err := db.Exec(`DELETE FROM \"heatcontrol_control\" WHERE \"id\" = $1`, c.id)\n\n\tc.existsInDB = false\n\n\treturn err\n}", "func (o *Transaction) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Transaction provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), transactionPrimaryKeyMapping)\n\tsql := \"DELETE FROM `transactions` WHERE `transaction_id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from transactions\")\n\t}\n\n\treturn nil\n}", "func (o *Stock) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func deleteProduct(dbRef *pg.DB) {\n\tnewPI := &db.ProductItem{\n\t\tName: \"Product 2\",\n\t}\n\tnewPI.Delete(dbRef)\n}", "func (o *Channel) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Channel provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), channelPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"channels\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from channels\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for channels\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (c *Customer) Delete() error {\n\tif c.Id.Hex() == \"\" {\n\t\treturn fmt.Errorf(\"error: %s\", \"invalid customer reference\")\n\t}\n\n\tsess, err := mgo.DialWithInfo(database.MongoConnectionString())\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer sess.Close()\n\n\tif err := c.Get(); err != nil {\n\t\treturn err\n\t}\n\n\tif c.Orders != nil && len(c.Orders) > 0 {\n\t\treturn fmt.Errorf(\"error: %s\", \"can't remove a customer that has order information\")\n\t}\n\n\treturn sess.DB(\"CurtCart\").C(\"customer\").RemoveId(c.Id)\n}", "func (s *APIProductStore) Delete(apiProduct string) types.Error {\n\n\tapiproduct, err := s.Get(apiProduct)\n\tif err != nil {\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn err\n\t}\n\n\tquery := \"DELETE FROM api_products WHERE name = ?\"\n\tif err := s.db.CassandraSession.Query(query, apiproduct.Name).Exec(); err != nil {\n\t\ts.db.metrics.QueryFailed(apiProductsMetricLabel)\n\t\treturn types.NewDatabaseError(err)\n\t}\n\treturn nil\n}", "func (c *CoursesDAO) Delete(course models.Course) error {\n\terr := db.C(COLLECTION).Remove(&course)\n\treturn err\n}", "func DeleteOrder(client *golangsdk.ServiceClient, opts DeleteOrderOpts) (r DeleteOrderResult) {\n\treqBody, err := opts.ToServerDeleteOrderMap()\n\tif err != nil {\n\t\tr.Err = err\n\t\treturn\n\t}\n\t_, r.Err = client.Post(deleteOrderURL(client), reqBody, &r.Body, &golangsdk.RequestOpts{OkCodes: []int{200}})\n\treturn\n}", "func (o *AuthMessage) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func (m *ApplicationModule) Delete() (err error) {\n\to := orm.NewOrm()\n\tif m.ID > 0 {\n\t\tvar i int64\n\t\tif i, err = o.Delete(m); i == 0 && err == nil {\n\t\t\terr = orm.ErrNoAffected\n\t\t}\n\t\treturn\n\t}\n\treturn orm.ErrNoRows\n}", "func (o *InstrumentClass) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no InstrumentClass provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), instrumentClassPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"instruments\\\".\\\"instrument_class\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from instrument_class\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *servicePackageCRUD) Delete(arg ...crud.Arg) (crud.Arg, error) {\n\tevent := eventFromArg(arg[0])\n\tsp := servicePackageFromStuct(event)\n\terr := s.client.ServicePackages.Delete(nil, sp.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sp, nil\n}", "func (a *ProcessorsApiService) DeleteProcessorExecute(r ProcessorsApiApiDeleteProcessorRequest) (ProcessorEntity, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodDelete\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ProcessorEntity\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ProcessorsApiService.DeleteProcessor\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/processors/{id}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"id\"+\"}\", _neturl.PathEscape(parameterToString(r.id, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.version != nil {\n\t\tlocalVarQueryParams.Add(\"version\", parameterToString(*r.version, \"\"))\n\t}\n\tif r.clientId != nil {\n\t\tlocalVarQueryParams.Add(\"clientId\", parameterToString(*r.clientId, \"\"))\n\t}\n\tif r.disconnectedNodeAcknowledged != nil {\n\t\tlocalVarQueryParams.Add(\"disconnectedNodeAcknowledged\", parameterToString(*r.disconnectedNodeAcknowledged, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (s *PaymentStorage) Delete(ctx context.Context, id aggregate.ID) error {\n\tlogger := log.FromContext(ctx)\n\n\tquery := `DELETE FROM %[1]s WHERE id = $1`\n\tquery = fmt.Sprintf(query, s.table)\n\n\tif logger != nil {\n\t\tlogger.Debugf(\"exec in transaction sql %s, values %+v\", query, []interface{}{\n\t\t\tid,\n\t\t})\n\t}\n\n\treturn execInTransaction(s.db, func(tx *sqlx.Tx) error {\n\t\t_, err := tx.ExecContext(ctx, query, id)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (dao AccountPUCDAOPsql) Delete(obj *models.AccountPUC) error {\n\tquery := \"DELETE FROM accounts_puc WHERE id = $1\"\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(obj.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif rowsAffected, _ := result.RowsAffected(); rowsAffected == 0 {\n\t\t\treturn errors.New(\"No se eliminó ningún registro\")\n\t}\n\tobj = new(models.AccountPUC)\n\treturn nil\n}", "func (o *Comment) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Comment provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), commentPrimaryKeyMapping)\n\tsql := \"DELETE FROM `comment` WHERE `index`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from comment\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *Stock) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Stock provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), stockPrimaryKeyMapping)\n\tsql := \"DELETE FROM `stock` WHERE `stock_id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from stock\")\n\t}\n\n\treturn nil\n}", "func (c *PartorderClient) Delete() *PartorderDelete {\n\tmutation := newPartorderMutation(c.config, OpDelete)\n\treturn &PartorderDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}\n}", "func (o *Jet) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"models: no Jet provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), jetPrimaryKeyMapping)\n\tsql := \"DELETE FROM `jets` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"models: unable to delete from jets\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *Task) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Task provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), taskPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"tasks\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from tasks\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for tasks\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func DeleteComponent(request []string, params map[string][]string) (answer Answer) {\n\tanswer.Message = \"DeleteComponent\"\n\treturn\n}", "func (s *service) Delete(ctx context.Context, constraintID, formationTemplateID string) error {\n\tif err := s.repo.Delete(ctx, formationTemplateID, constraintID); err != nil {\n\t\treturn errors.Wrapf(err, \"while deleting Formation Template Constraint Reference for Constraint with ID %q and Formation Template with ID %q\", constraintID, formationTemplateID)\n\t}\n\n\treturn nil\n}", "func (o *CMFFamiliesPolicy) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no CMFFamiliesPolicy provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), cmfFamiliesPolicyPrimaryKeyMapping)\n\tsql := \"DELETE FROM `cmf_families_policies` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from cmf_families_policies\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for cmf_families_policies\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (h *History) DeleteProcessInstance(id string) error {\n\treturn h.client.doDelete(\"/history/process-instance/\"+id, nil)\n}", "func (o *Transaction) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"model: no Transaction provided for delete\")\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), transactionPrimaryKeyMapping)\n\tsql := \"DELETE FROM `transaction` WHERE `id`=?\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"model: unable to delete from transaction\")\n\t}\n\n\treturn nil\n}", "func DropOrder(ctx context.Context, db *mongo.Database) (err error) {\n\tcollection := db.Collection(\"order\")\n\terr = collection.Drop(ctx)\n\treturn\n}", "func (m *Module) Delete() (*Module, error) {\n\tif err := database.BackendDB.DB.Delete(m).Error; err != nil {\n\t\tlog.Print(err)\n\t\treturn nil, err\n\t}\n\treturn m, nil\n}", "func DeleteProduct(c *gin.Context) {\n\tID := c.Param(\"id\")\n\n\t//ID := c.Query(\"id\")\n\tfmt.Println(\"id is: \", ID)\n\tlog.Println(\"id: \", ID)\n\tdb := DbConn()\n\tvar prod Products\n\tdbc := db.Where(\"id = ?\", ID).Delete(&prod).Error\n\tif dbc != nil {\n\t\tfmt.Println(\"Error while deleting: \", dbc)\n\t\tc.String(http.StatusBadRequest, \"Error while deleting\")\n\t}\n\tc.String(http.StatusOK, \"Success\")\n}", "func (c *Comment) Delete(dbp zesty.DBProvider) (err error) {\n\tdefer errors.DeferredAnnotatef(&err, \"Failed to delete comment\")\n\n\trows, err := dbp.DB().Delete(c)\n\tif err != nil {\n\t\treturn pgjuju.Interpret(err)\n\t} else if rows == 0 {\n\t\treturn errors.NotFoundf(\"No such comment to delete: %s\", c.PublicID)\n\t}\n\n\treturn nil\n}", "func (o *FeatureRelationship) Delete(exec boil.Executor) error {\n\tif o == nil {\n\t\treturn errors.New(\"chado: no FeatureRelationship provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), featureRelationshipPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"feature_relationship\\\" WHERE \\\"feature_relationship_id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\t_, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"chado: unable to delete from feature_relationship\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (tip *Tipo)Delete() (err error) {\n\tstatement := \"delete from tipos where id = $1\"\n\tstmt, err := Db.Prepare(statement)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer stmt.Close()\n\t_, err = stmt.Exec(tip.Id)\n\treturn\n}", "func (s *service) Delete(ctx context.Context, id string) error {\n\tif err := s.repo.Delete(ctx, id); err != nil {\n\t\treturn errors.Wrapf(err, \"while deleting Formation Constraint with ID %s\", id)\n\t}\n\n\treturn nil\n}", "func Delete(cmd *cobra.Command, args []string) error {\n\n\tdeleteRequest := &module.ModuleDeleteRequest{\n\t\tName: deleteOpts.name,\n\t}\n\n\tfmt.Println(\"deleting module\")\n\t_, err := Client.Delete(context.Background(), deleteRequest)\n\tif err != nil {\n\t\treturn fmt.Errorf(fmt.Sprintf(\"failed to delete module: %+v\", err))\n\t}\n\tfmt.Printf(\"deleted module %s\\n\", deleteOpts.name)\n\treturn nil\n}", "func (o *Notification) Delete(exec boil.Executor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no Notification provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), notificationPrimaryKeyMapping)\n\tsql := \"DELETE FROM \\\"notification\\\" WHERE \\\"id\\\"=$1\"\n\n\tif boil.DebugMode {\n\t\tfmt.Fprintln(boil.DebugWriter, sql)\n\t\tfmt.Fprintln(boil.DebugWriter, args...)\n\t}\n\n\tresult, err := exec.Exec(sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from notification\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for notification\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (o *FeatureCvtermDbxref) DeleteP(exec boil.Executor) {\n\tif err := o.Delete(exec); err != nil {\n\t\tpanic(boil.WrapErr(err))\n\t}\n}", "func DeleteLog() {\n\tsql := \"DELETE FROM `process`\"\n\tquery, err := database.Connection.Prepare(sql)\n\tif err != nil {\n\t\tfmt.Println(\"Delete #1 error for log:\")\n\t\tfmt.Println(err)\n\t}\n\tquery.Exec()\n}", "func (e *engine) DeletePipeline(ctx context.Context, p *library.Pipeline) error {\n\te.logger.WithFields(logrus.Fields{\n\t\t\"pipeline\": p.GetCommit(),\n\t}).Tracef(\"deleting pipeline %s from the database\", p.GetCommit())\n\n\t// cast the library type to database type\n\t//\n\t// https://pkg.go.dev/github.com/go-vela/types/database#PipelineFromLibrary\n\tpipeline := database.PipelineFromLibrary(p)\n\n\t// send query to the database\n\treturn e.client.\n\t\tTable(constants.TablePipeline).\n\t\tDelete(pipeline).\n\t\tError\n}", "func (o *AuthItemGroup) Delete(ctx context.Context, exec boil.ContextExecutor) (int64, error) {\n\tif o == nil {\n\t\treturn 0, errors.New(\"models: no AuthItemGroup provided for delete\")\n\t}\n\n\tif err := o.doBeforeDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\targs := queries.ValuesFromMapping(reflect.Indirect(reflect.ValueOf(o)), authItemGroupPrimaryKeyMapping)\n\tsql := \"DELETE FROM `auth_item_groups` WHERE `id`=?\"\n\n\tif boil.IsDebug(ctx) {\n\t\twriter := boil.DebugWriterFrom(ctx)\n\t\tfmt.Fprintln(writer, sql)\n\t\tfmt.Fprintln(writer, args...)\n\t}\n\tresult, err := exec.ExecContext(ctx, sql, args...)\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: unable to delete from auth_item_groups\")\n\t}\n\n\trowsAff, err := result.RowsAffected()\n\tif err != nil {\n\t\treturn 0, errors.Wrap(err, \"models: failed to get rows affected by delete for auth_item_groups\")\n\t}\n\n\tif err := o.doAfterDeleteHooks(ctx, exec); err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn rowsAff, nil\n}", "func (dao CompanyDAOPsql) Delete(obj *models.Company) error {\n\tquery := \"DELETE FROM companies WHERE id = $1\"\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(obj.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif rowsAffected, _ := result.RowsAffected(); rowsAffected == 0 {\n\t\t\treturn errors.New(\"No se eliminó ningún registro\")\n\t}\n\tobj = new(models.Company)\n\treturn nil\n}" ]
[ "0.66532147", "0.62714803", "0.62118816", "0.6032562", "0.6014197", "0.6003978", "0.599696", "0.5988549", "0.5762294", "0.57239544", "0.56981295", "0.56890845", "0.5681269", "0.562764", "0.56168", "0.5594396", "0.5540558", "0.55369294", "0.5501525", "0.54986113", "0.5488075", "0.5475108", "0.54736805", "0.5468505", "0.54325217", "0.5423667", "0.54196596", "0.5417197", "0.5394833", "0.5384024", "0.5379292", "0.5373919", "0.537254", "0.5366995", "0.5365827", "0.533673", "0.533673", "0.52939385", "0.52886516", "0.5285119", "0.5277755", "0.5261356", "0.5247648", "0.5227416", "0.52225786", "0.5211695", "0.5202204", "0.51999587", "0.5196693", "0.51916736", "0.5176295", "0.5156444", "0.51530266", "0.51485145", "0.5147275", "0.5145639", "0.51357025", "0.5129092", "0.51221335", "0.51091015", "0.5106705", "0.5101764", "0.5097276", "0.50924104", "0.509202", "0.50878024", "0.50857854", "0.5076746", "0.5073886", "0.5068818", "0.5066565", "0.50546396", "0.5054241", "0.5052363", "0.5050594", "0.50495255", "0.50484294", "0.5044134", "0.50434935", "0.5038099", "0.50337553", "0.5029158", "0.50283015", "0.5026941", "0.50246507", "0.5017249", "0.50146693", "0.5008406", "0.5007853", "0.50055164", "0.50026697", "0.49946982", "0.49883932", "0.49869406", "0.49846202", "0.49842688", "0.4981369", "0.49808568", "0.49719688", "0.4970746" ]
0.7422059
0
ComponentOrderProcessByID retrieves a row from 'aypcddg.component_order_process' as a ComponentOrderProcess. Generated from index 'component_order_process_id_pkey'.
func ComponentOrderProcessByID(ctx context.Context, id uint, key ...interface{}) (*ComponentOrderProcess, error) { var err error var dbConn *sql.DB tableName, err := GetComponentOrderProcessTableName(key...) if err != nil { return nil, err } // sql query sqlstr := `SELECT ` + `id, orderid, event, do_status, access_url, remark, created_at, updated_at ` + `FROM ` + tableName + ` WHERE id = ?` // run query utils.GetTraceLog(ctx).Debug("DB", zap.String("SQL", fmt.Sprint(sqlstr, id))) tx, err := components.M.GetConnFromCtx(ctx) if err != nil { dbConn, err = components.M.GetSlaveConn() if err != nil { return nil, err } } cop := ComponentOrderProcess{ _exists: true, } if tx != nil { err = tx.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt) if err != nil { return nil, err } } else { err = dbConn.QueryRow(sqlstr, id).Scan(&cop.ID, &cop.Orderid, &cop.Event, &cop.DoStatus, &cop.AccessURL, &cop.Remark, &cop.CreatedAt, &cop.UpdatedAt) if err != nil { return nil, err } } return &cop, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (context Context) GetProcessByID(id bson.ObjectId) (result types.Process, err error) {\n\n\t// Currently there are no restrictions for non-root users here.\n\n\tc := context.Session.DB(context.DBName).C(\"processes\")\n\tvar allResults []types.Process\n\terr = c.Find(bson.M{\"_id\": id}).All(&allResults)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"mongo find failed\")\n\t\treturn\n\t}\n\n\tif len(allResults) == 0 {\n\t\terr = ErrNotFound\n\t\treturn\n\t}\n\n\treturn allResults[0], nil\n}", "func (s *RunbookProcessService) GetByID(id string) (*RunbookProcess, error) {\n\tif internal.IsEmpty(id) {\n\t\treturn nil, internal.CreateInvalidParameterError(constants.OperationGetByID, constants.ParameterID)\n\t}\n\n\tpath, err := services.GetByIDPath(s, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := api.ApiGet(s.GetClient(), new(RunbookProcess), path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn resp.(*RunbookProcess), nil\n}", "func (client *ClientImpl) GetProcessByItsId(ctx context.Context, args GetProcessByItsIdArgs) (*ProcessInfo, error) {\n\trouteValues := make(map[string]string)\n\tif args.ProcessTypeId == nil {\n\t\treturn nil, &azuredevops.ArgumentNilError{ArgumentName: \"args.ProcessTypeId\"}\n\t}\n\trouteValues[\"processTypeId\"] = (*args.ProcessTypeId).String()\n\n\tqueryParams := url.Values{}\n\tif args.Expand != nil {\n\t\tqueryParams.Add(\"$expand\", string(*args.Expand))\n\t}\n\tlocationId, _ := uuid.Parse(\"02cc6a73-5cfb-427d-8c8e-b49fb086e8af\")\n\tresp, err := client.Client.Send(ctx, http.MethodGet, locationId, \"6.0-preview.2\", routeValues, queryParams, nil, \"\", \"application/json\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar responseValue ProcessInfo\n\terr = client.Client.UnmarshalBody(resp, &responseValue)\n\treturn &responseValue, err\n}", "func (p *process) ProcessID() int {\n\tproc := p.p\n\tif proc != nil {\n\t\treturn proc.Pid\n\t}\n\treturn 0\n}", "func (p propEncoding) ProcessID() int {\n\tpanic(\"not implemented\")\n}", "func (o *os) GetProcessId() gdnative.Int {\n\to.ensureSingleton()\n\t//log.Println(\"Calling _OS.GetProcessId()\")\n\n\t// Build out the method's arguments\n\tptrArguments := make([]gdnative.Pointer, 0, 0)\n\n\t// Get the method bind\n\tmethodBind := gdnative.NewMethodBind(\"_OS\", \"get_process_id\")\n\n\t// Call the parent method.\n\t// int\n\tretPtr := gdnative.NewEmptyInt()\n\tgdnative.MethodBindPtrCall(methodBind, o.GetBaseObject(), ptrArguments, retPtr)\n\n\t// If we have a return type, convert it from a pointer into its actual object.\n\tret := gdnative.NewIntFromPointer(retPtr)\n\treturn ret\n}", "func XPriCompGroupItemByID(db XODB, id uint) (*XPriCompGroupItem, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, name, display_name, type_cd, primary_flag, seq_num, x_pri_comp_group_id, created_by, updated_by, created_at, updated_at ` +\n\t\t`FROM x_showroom.x_pri_comp_group_item ` +\n\t\t`WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\txpcgi := XPriCompGroupItem{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&xpcgi.ID, &xpcgi.Name, &xpcgi.DisplayName, &xpcgi.TypeCd, &xpcgi.PrimaryFlag, &xpcgi.SeqNum, &xpcgi.XPriCompGroupID, &xpcgi.CreatedBy, &xpcgi.UpdatedBy, &xpcgi.CreatedAt, &xpcgi.UpdatedAt)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &xpcgi, nil\n}", "func (c *ProcessClient) Get(ctx context.Context, guid string) (*resource.Process, error) {\n\tvar iso resource.Process\n\terr := c.client.get(ctx, path.Format(\"/v3/processes/%s\", guid), &iso)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &iso, nil\n}", "func (s *OrderService) GetByID(id bson.ObjectId) (*types.Order, error) {\n\treturn s.orderDao.GetByID(id)\n}", "func (m *RegistryKeyState) GetProcessId()(*int32) {\n return m.processId\n}", "func NewComponentProcess(ctx context.Context, dir, binPath, component string, version v0manifest.Version, arg ...string) (Process, error) {\n\tif dir == \"\" {\n\t\tpanic(\"dir must be set\")\n\t}\n\n\tenv := environment.GlobalEnv()\n\tcmd, err := tiupexec.PrepareCommand(ctx, component, version, binPath, \"\", dir, arg, env)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &process{cmd: cmd}, nil\n}", "func (n *Namespace) GetProcessID(cmd *exec.Cmd) {\n\tcmd.SysProcAttr = &syscall.SysProcAttr{\n\t\tCloneflags: syscall.CLONE_NEWPID,\n\t}\n}", "func (c *MetricsClient) GetProcess(id int) (ProcessMetrics, error) {\n\tresponse, err := c.request(\"GET\", metricsEndpointPath+\"processes/\"+strconv.Itoa(id), \"\", nil, nil)\n\tif err != nil {\n\t\treturn ProcessMetrics{}, errors.Wrap(err, \"error during request\")\n\t}\n\tif response.StatusCode() != 200 {\n\t\treturn ProcessMetrics{}, getHTTPError(response)\n\t}\n\tvar process ProcessMetrics\n\terr = json.Unmarshal(response.Body(), &process)\n\tif err != nil {\n\t\treturn ProcessMetrics{}, errors.Wrap(err, \"error during unmarshalling http response\")\n\t}\n\treturn process, nil\n}", "func findProcessWithPID(pid int) (ps.Process, error) {\n\tmatchPID := func(p ps.Process) bool { return p.Pid() == pid }\n\tprocs, err := findProcessesWithFn(ps.Processes, matchPID, 1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(procs) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn procs[0], nil\n}", "func (s *service) GetByID(ctx context.Context, id string) (ordersvc.Order, error) {\n\tlogger := log.With(s.logger, \"method\", \"GetByID\")\n\torder, err := s.repository.GetOrderByID(ctx, id)\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"err\", err)\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn order, ordersvc.ErrOrderNotFound\n\t\t}\n\t\treturn order, ordersvc.ErrQueryRepository\n\t}\n\treturn order, nil\n}", "func (p Process) Pid() (int, error) {\n\t// math.MinInt32 is returned here, because it's invalid value\n\t// for the kill() system call.\n\tif p.ops == nil {\n\t\treturn math.MinInt32, errInvalidProcess\n\t}\n\treturn p.ops.pid(), nil\n}", "func (s *service) GetByID(ctx context.Context, id string) (Order, error) {\n\tlogger := log.With(s.logger, \"method\", \"GetByID\")\n\tvar order Order\n\tif tmp, ok := Orders.Get(id); ok {\n\t\tif !ok {\n\t\t\tlevel.Error(logger).Log(\"err\", ok)\n\t\t\treturn order, ErrOrderNotFound\n\t\t}\n\t\torder = tmp.(Order)\n\t}\n\n\treturn order, nil\n}", "func (d *DermagaUsecaseProcess) GetByID(id int) (*model.Dermaga, error) {\n\treturn d.dermagaRepo.GetByID(id)\n}", "func GetProcessByPID(PID int) (Process, error) {\n\t// Try to open the folder to see if it exists and if we have access to it.\n\tf, err := os.Open(fmt.Sprintf(\"/proc/%d\", PID))\n\tdefer f.Close()\n\tif err != nil {\n\t\treturn Process{}, errors.New(fmt.Sprintf(\"Error opening /proc/%d\", PID))\n\t}\n\n\treturn Process{PID: uint64(PID)}, nil\n}", "func findProcess(pid int) (*process, error) {\n\tprs, err := findProcesses(pid)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(prs) != 1 {\n\t\treturn nil, fmt.Errorf(\"pid %v not found\", pid)\n\t}\n\treturn prs[0], nil\n}", "func (r Virtual_Guest) GetOrderedPackageId() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getOrderedPackageId\", nil, &r.Options, &resp)\n\treturn\n}", "func OrderIDByOrderCode(db *sql.DB, ostore, ordercode string) (uint32, error) {\n\tvar orderid uint32\n\n\tsql := fmt.Sprintf(orderSQLString[orderIDByOrderCode], ostore)\n\n\terr := db.QueryRow(sql, ordercode).Scan(&orderid)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn orderid, nil\n}", "func (sS StoreService) GetByOrderID(id int64) (outputOrder models.Order, err error) {\n\terr = sS.DB.First(&outputOrder, id).Error\n\treturn outputOrder, err\n}", "func (cop *ComponentOrderProcess) Insert(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\tvar res sql.Result\n\t// if already exist, bail\n\tif cop._exists {\n\t\treturn errors.New(\"insert failed: already exists\")\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// sql insert query, primary key provided by autoincrement\n\tsqlstr := `INSERT INTO ` + tableName +\n\t\t` (` +\n\t\t`orderid, event, do_status, access_url, remark, created_at, updated_at` +\n\t\t`) VALUES (` +\n\t\t`?, ?, ?, ?, ?, ?, ?` +\n\t\t`)`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)))\n\tif err != nil {\n\t\treturn err\n\t}\n\tif tx != nil {\n\t\tres, err = tx.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t} else {\n\t\tres, err = dbConn.Exec(sqlstr, cop.Orderid, cop.Event, cop.DoStatus, cop.AccessURL, cop.Remark, cop.CreatedAt, cop.UpdatedAt)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// retrieve id\n\tid, err := res.LastInsertId()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set primary key and existence\n\tcop.ID = uint(id)\n\tcop._exists = true\n\n\treturn nil\n}", "func (js *JobService) JobByID(id uint) (*entity.Job, []error) {\n\tjob, errs := js.jobRepo.JobByID(id)\n\n\tif len(errs) > 0 {\n\t\treturn nil, errs\n\t}\n\n\treturn job, nil\n}", "func FindProcess(key string) (int, string, error) {\n\tpname := \"\"\n\tpid := 0\n\terr := errors.New(\"not found\")\n\tps, _ := ps.Processes()\n\n\tfor i, _ := range ps {\n\t\tif ps[i].Executable() == key {\n\t\t\tpid = ps[i].Pid()\n\t\t\tpname = ps[i].Executable()\n\t\t\terr = nil\n\t\t\tbreak\n\t\t\tbreak\n\t\t}\n\t}\n\treturn pid, pname, err\n}", "func (d *DB) OrderByID(id string) (o Order, found bool) {\n\tfor _, order := range d.Orders {\n\t\tif order.ID == id {\n\t\t\treturn order, true\n\t\t}\n\t}\n\treturn\n}", "func (db *PgDB) JobByID(jID model.JobID) (*model.Job, error) {\n\tvar j model.Job\n\tif err := db.query(`\nSELECT *\nFROM jobs\nWHERE job_id = $1\n`, &j, jID); err != nil {\n\t\treturn nil, errors.Wrap(err, \"querying job\")\n\t}\n\treturn &j, nil\n}", "func GetProductByID(productID uint64, preloads ...string) (*Product, error) {\n\tproduct := &Product{}\n\tscope := db.New()\n\tfor _, column := range preloads {\n\t\tscope = scope.Preload(column)\n\t}\n\tscope = scope.Find(product, productID)\n\treturn product, scope.Error\n}", "func (p *OrderRepo) FindByID(id types.RowID) (order cafmodel.Order, err error) {\n\terr = p.Engine.DB.Table(cafmodel.OrderTable).First(&order, id.ToUint64()).Error\n\n\torder.ID = id\n\terr = p.dbError(err, \"E1572991\", order, corterm.List)\n\n\treturn\n}", "func (s *Service) GetProductByID(ctx context.Context, id int64) (*types.Product, error) {\n\tproduct := &types.Product{}\n\terr := s.pool.QueryRow(ctx,\n\t\t`SELECT id, name, category_id, description, qty, price, active FROM products WHERE id = $1 AND active = true`, id).\n\t\tScan(&product.ID, &product.Name, &product.CategoryID, &product.Description, &product.Qty, &product.Price, &product.Active)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, ErrProductDoesNotExist\n\t}\n\treturn product, nil\n}", "func (gi *Sensor) GetPidByID(db *pg.DB, sensorID int) (int, error) {\r\n\t// log.Printf(\">===>sensorItem.GetPidByID()\")\r\n\r\n\tgetErr := db.Model(gi).\r\n\t\tWhere(\"id = ?0\", sensorID).\r\n\t\tSelect()\r\n\tif getErr != nil {\r\n\t\tlog.Printf(\"Error while selecting item in sensorItem.GetByOwner()\\n\")\r\n\t\tlog.Printf(\"Reason %v\\n\", getErr)\r\n\t\treturn gi.SensorPid, getErr\r\n\t}\r\n\t// log.Printf(\"Select by Owner successful for gi: %v\\n\", *gi)\r\n\treturn gi.SensorPid, nil\r\n}", "func (database *Database) FindOrderItemByID(item *OrderItem, id int) error {\n\tif err := database.DB.First(item, id).Error; err != nil {\n\t\treturn fmt.Errorf(\"Failed to get an order item with ID = %d: %s\", id, err)\n\t}\n\treturn nil\n}", "func getNamedPipeClientProcessID(pipe windows.Handle, clientProcessID *int32) (err error) {\n\tif procGetNamedPipeClientProcessIDErr != nil {\n\t\treturn procGetNamedPipeClientProcessIDErr\n\t}\n\tr1, _, e1 := syscall.SyscallN(procGetNamedPipeClientProcessID.Addr(), uintptr(pipe), uintptr(unsafe.Pointer(clientProcessID)))\n\tif r1 == 0 {\n\t\treturn e1\n\t}\n\treturn nil\n}", "func (intr Internal) GetProductByID(ctx context.Context, ID int64) (Product, error) {\n\tvar (\n\t\tproduct Product\n\t\tquery string\n\t)\n\n\tquery = qSelectProduct\n\tquery += `WHERE\n\t\t\t\tproduct_id = ?\n\t\t\t`\n\tdb := intr.Storage.DB\n\trow := db.QueryRowxContext(ctx, db.Rebind(query), ID)\n\terr := row.StructScan(&product)\n\n\t// pass if sql no rows error\n\tif err == sql.ErrNoRows {\n\t\terr = nil\n\t}\n\treturn product, err\n}", "func ProcessorID() (string, error) {\n\t/*\n\t\tSample output of 'wmic os get caption'\n\n\t\tProcessorID\n\t\tABCDFGHI012345JK\n\t*/\n\tresult, err := readAndParseFromCommandLine(processorIDCmd)\n\tif err != nil {\n\t\treturn \"-1\", err\n\t}\n\tprocessorID := \"\"\n\tif len(result) > 1 {\n\t\tprocessorID = result[1]\n\t}\n\treturn processorID, err\n}", "func FindProcess(pid int) (*os.Process, error)", "func (or *mongoOrderRepository) FetchByID(id string) (*models.Order, error) {\n\tvar order models.Order\n\t//If the ID passed is not a valid Object ID, return error\n\tisValidID := bson.IsObjectIdHex(id)\n\tif isValidID != true {\n\t\treturn nil, errors.New(\"Invalid Id\")\n\t}\n\t//Find document in DB by ID\n\terr := or.Conn.C(COLLECTION).FindId(bson.ObjectIdHex(id)).One(&order)\n\treturn &order, err\n}", "func (m *Model) RefProcess() *ProcessInstance {\n\tif m == nil || m.QRef == nil {\n\t\treturn nil\n\t}\n\tid := *m.QRef\n\tfor i := range m.Processes {\n\t\tif m.Processes[i].InternalID == id {\n\t\t\treturn &m.Processes[i]\n\t\t}\n\t}\n\treturn nil\n}", "func (m *MockCoreClient) GetProcessById(arg0 context.Context, arg1 core.GetProcessByIdArgs) (*core.Process, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetProcessById\", arg0, arg1)\n\tret0, _ := ret[0].(*core.Process)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (p *process) Pid() int {\n\treturn p.cmd.Process.Pid\n}", "func (c *Component) ID() string {\n\tc.Cmu.Lock()\n\tdefer c.Cmu.Unlock()\n\treturn c.Id\n}", "func GetProductByID(c *gin.Context) {\n\tid := c.Params.ByName(\"id\")\n\tvar product Models.Product\n\terr := Models.GetProductByID(&product, id)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func ByID(ds datastore.Datastore, id int) (CPD, error) {\n\treturn cpdByID(ds, id)\n}", "func (container *container) OpenProcess(pid int) (Process, error) {\r\n\tp, err := container.system.OpenProcess(context.Background(), pid)\r\n\tif err != nil {\r\n\t\treturn nil, convertSystemError(err, container)\r\n\t}\r\n\treturn &process{p: p}, nil\r\n}", "func isActiveChronosProcess(pid int32) bool {\n\tp, err := process.NewProcess(pid)\n\tif err != nil {\n\t\t// The process may be gone already.\n\t\treturn false\n\t}\n\n\tif status, err := p.Status(); err != nil || status[0] == \"Z\" || status[0] == \"X\" {\n\t\t// The process exited already, or is a zombie that hasn't yet been reaped\n\t\t// by its parent (https://crbug.com/963144), or is in the mysterious \"dead\" state\n\t\t// that \"should never be seen\" but sometimes is (https://crrev.com/c/1303781).\n\t\treturn false\n\t}\n\n\tuids, err := p.Uids()\n\tif err != nil {\n\t\t// The process is gone between NewProcess() and Uids() call.\n\t\treturn false\n\t}\n\t// euid is stored at [1].\n\treturn uint32(uids[1]) == sysutil.ChronosUID\n}", "func (h *HitBTC) GetActiveOrderByClientOrderID(ctx context.Context, clientOrderID string) (OrderHistoryResponse, error) {\n\tvar result OrderHistoryResponse\n\n\treturn result, h.SendAuthenticatedHTTPRequest(ctx, exchange.RestSpot, http.MethodGet,\n\t\tapiv2OpenOrders+\"/\"+clientOrderID,\n\t\tnil,\n\t\ttradingRequests,\n\t\t&result)\n}", "func (cop *ComponentOrderProcess) Delete(ctx context.Context, key ...interface{}) error {\n\tvar err error\n\tvar dbConn *sql.DB\n\n\t// if deleted, bail\n\tif cop._deleted {\n\t\treturn nil\n\t}\n\n\ttx, err := components.M.GetConnFromCtx(ctx)\n\tif err != nil {\n\t\tdbConn, err = components.M.GetMasterConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttableName, err := GetComponentOrderProcessTableName(key...)\n\tif err != nil {\n\t\treturn err\n\t}\n\t//1\n\n\t// sql query with composite primary key\n\tsqlstr := `UPDATE ` + tableName + ` SET is_del = 1 WHERE id = ?`\n\n\t// run query\n\tutils.GetTraceLog(ctx).Debug(\"DB\", zap.String(\"SQL\", fmt.Sprint(sqlstr, cop.ID)))\n\tif tx != nil {\n\t\t_, err = tx.Exec(sqlstr, cop.ID)\n\t} else {\n\t\t_, err = dbConn.Exec(sqlstr, cop.ID)\n\t}\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// set deleted\n\tcop._deleted = true\n\n\treturn nil\n}", "func (c *MainController) getDataByID(PID int) {\n\to := orm.NewOrm()\n\tproduct := models.Product{PID: PID}\n\terr := o.Read(&product)\n\tif err != nil {\n\t\tbeego.Info(\"o.Read err=\", err)\n\t\treturn\n\t}\n\tc.Data[\"product\"] = product\n}", "func (b Build) ByID(c *gin.Context) (models.Build, error) {\n\tbuild := models.Build{}\n\tvar id string\n\tif !bindID(c, &id) {\n\t\treturn build, errNotFound\n\t}\n\terr := b.Query(c).First(&build, \"builds.id = ?\", id).Error\n\t// Not found? Might be a public build ID\n\tif err == gorm.ErrRecordNotFound {\n\t\terr = b.QueryWhere(\"projects.id=?\", b.PublicProjectID).\n\t\t\tWhere(&models.Build{ProjectID: b.PublicProjectID}).First(&build, \"builds.id = ?\", id).Error\n\t}\n\n\tif err != nil {\n\t\tsugar.NotFoundOrError(c, err)\n\t\treturn build, err\n\t}\n\treturn build, nil\n}", "func YhOrderMasterByID(db XODB, id uint) (*YhOrderMaster, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, order_time, seller_id, image_id, item_id, is_hidden_page ` +\n\t\t`FROM devdb.yh_order_master ` +\n\t\t`WHERE id = ?`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\tyom := YhOrderMaster{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&yom.ID, &yom.OrderTime, &yom.SellerID, &yom.ImageID, &yom.ItemID, &yom.IsHiddenPage)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &yom, nil\n}", "func (a *HyperflexApiService) GetHyperflexSoftwareDistributionComponentByMoidExecute(r ApiGetHyperflexSoftwareDistributionComponentByMoidRequest) (*HyperflexSoftwareDistributionComponent, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tformFiles []formFile\n\t\tlocalVarReturnValue *HyperflexSoftwareDistributionComponent\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"HyperflexApiService.GetHyperflexSoftwareDistributionComponentByMoid\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/api/v1/hyperflex/SoftwareDistributionComponents/{Moid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"Moid\"+\"}\", url.PathEscape(parameterToString(r.moid, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/csv\", \"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 400 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 403 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Error\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tvar v Error\n\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\tif err != nil {\n\t\t\tnewErr.error = err.Error()\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tnewErr.model = v\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := &GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (s *OrderItemService) QueryByID(ctx context.Context, id string) (entity.OrderItem, error) {\n\treturn s.repo.QueryByID(ctx, id)\n}", "func NewGetComponentByIDParams() *GetComponentByIDParams {\n\treturn &GetComponentByIDParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (qs ControlQS) OrderByID() ControlQS {\n\tqs.order = append(qs.order, `\"id\"`)\n\n\treturn qs\n}", "func GetFromSnapProcess(pid uint32) (string, error) {\n\tsnap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, pid)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer windows.CloseHandle(snap)\n\tvar pe32 windows.ProcessEntry32\n\tpe32.Size = uint32(unsafe.Sizeof(pe32)) //nolint:gosec // G103: Valid use of unsafe call to determine the size of the struct\n\tif err := windows.Process32First(snap, &pe32); err != nil {\n\t\treturn \"\", err\n\t}\n\tfor {\n\t\tif pe32.ProcessID == pid {\n\t\t\tszexe := windows.UTF16ToString(pe32.ExeFile[:])\n\t\t\treturn szexe, nil\n\t\t}\n\t\tif err = windows.Process32Next(snap, &pe32); err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"couldn't find pid: %d\", pid)\n}", "func GetProcessName(processID uint32) string {\n\tsnapshot := w32.CreateToolhelp32Snapshot(w32.TH32CS_SNAPMODULE, processID)\n\tif snapshot == w32.ERROR_INVALID_HANDLE {\n\t\treturn \"<UNKNOWN>\"\n\t}\n\tdefer w32.CloseHandle(snapshot)\n\n\tvar me w32.MODULEENTRY32\n\tme.Size = uint32(unsafe.Sizeof(me))\n\tif w32.Module32First(snapshot, &me) {\n\t\treturn w32.UTF16PtrToString(&me.SzModule[0])\n\t}\n\n\treturn \"<UNKNOWN>\"\n}", "func (mr *MockCoreClientMockRecorder) GetProcessById(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetProcessById\", reflect.TypeOf((*MockCoreClient)(nil).GetProcessById), arg0, arg1)\n}", "func IdByHandle(handle string) *base.Id {\n\tvar data member.EntityData\n\tif ecol.Find(bson.M{\"handle\": handle}).Select(\n\t\tbson.M{\"_id\": 1}).One(&data) != nil {\n\t\treturn nil\n\t}\n\treturn &data.Id\n}", "func (dao AccountPUCDAOPsql) GetByID(id int) (*models.AccountPUC, error) {\n\tquery := \"SELECT id, account, account_name, account_puc_parent_id, account_class_id, account_level_id, created_at, updated_at FROM accounts_puc WHERE id = $1\"\n\tobj := &models.AccountPUC{}\n\tdb := get()\n\tdefer db.Close()\n\n\tstmt, err := db.Prepare(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer stmt.Close()\n\n\trow := stmt.QueryRow(id)\n\terr = dao.rowToObject(row, obj)\n\treturn obj, err\n}", "func (o *SmsTracking) GetProcessKey() string {\n\tif o == nil || o.ProcessKey == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ProcessKey\n}", "func getProcessPidFromName(t *testing.T) (string, int32) {\n\tpp, err := process.Processes()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get the processes with err: %v\", err)\n\t\treturn \"\", 0\n\t}\n\tp := pp[0]\n\tif len(pp) == 0 {\n\t\tt.Skip(\"no available processes\")\n\t\treturn \"\", 0\n\t}\n\tname, err := p.Name()\n\tif err != nil {\n\t\tt.Fatalf(\"failed to get process name with error: %v\", err)\n\t}\n\treturn name, p.Pid\n}", "func ActivePID(pid int32, args ...int) error {\n\tif xu == nil {\n\t\tvar err error\n\t\txu, err = xgbutil.NewConn()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(args) > 0 {\n\t\terr := ewmh.ActiveWindowReq(xu, xproto.Window(pid))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn nil\n\t}\n\n\txid, err := getXidFromPid(xu, pid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = ewmh.ActiveWindowReq(xu, xid)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func LoadByWorkflowID(db gorp.SqlExecutor, workflowID int64) ([]sdk.Pipeline, error) {\n\tpips := []sdk.Pipeline{}\n\tquery := `SELECT DISTINCT pipeline.*\n\tFROM pipeline\n\t\tJOIN workflow_node ON pipeline.id = workflow_node.pipeline_id\n\t\tJOIN workflow ON workflow_node.workflow_id = workflow.id\n\tWHERE workflow.id = $1`\n\n\tif _, err := db.Select(&pips, query, workflowID); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\treturn pips, nil\n\t\t}\n\t\treturn nil, sdk.WrapError(err, \"Unable to load pipelines linked to workflow id %d\", workflowID)\n\t}\n\n\treturn pips, nil\n}", "func (x *CtlCommand) getPid(rpcc *xmlrpcclient.XMLRPCClient, process string) {\n\tprocInfo, err := rpcc.GetProcessInfo(process)\n\tif err != nil {\n\t\tfmt.Printf(\"program '%s' not found\\n\", process)\n\t\tos.Exit(1)\n\t} else {\n\t\tfmt.Printf(\"%d\\n\", procInfo.Pid)\n\t}\n}", "func (a *TopologySmartscapeProcessGroupApiService) GetSingleProcessGroupExecute(r ApiGetSingleProcessGroupRequest) (ProcessGroup, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ProcessGroup\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"TopologySmartscapeProcessGroupApiService.GetSingleProcessGroup\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/entity/infrastructure/process-groups/{meIdentifier}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"meIdentifier\"+\"}\", _neturl.PathEscape(parameterToString(r.meIdentifier, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json; charset=utf-8\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif apiKey, ok := auth[\"Api-Token\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif apiKey.Prefix != \"\" {\n\t\t\t\t\tkey = apiKey.Prefix + \" \" + apiKey.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = apiKey.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func DoorCompiledContentByID(db XODB, id int) (*DoorCompiledContent, error) {\n\tvar err error\n\n\t// sql query\n\tconst sqlstr = `SELECT ` +\n\t\t`id, door_id, patches, unprotected_full, protected_full, created_at, created_by, activated, needs_approval, approved_by ` +\n\t\t`FROM public.door_compiled_content ` +\n\t\t`WHERE id = $1`\n\n\t// run query\n\tXOLog(sqlstr, id)\n\tdcc := DoorCompiledContent{\n\t\t_exists: true,\n\t}\n\n\terr = db.QueryRow(sqlstr, id).Scan(&dcc.ID, &dcc.DoorID, &dcc.Patches, &dcc.UnprotectedFull, &dcc.ProtectedFull, &dcc.CreatedAt, &dcc.CreatedBy, &dcc.Activated, &dcc.NeedsApproval, &dcc.ApprovedBy)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &dcc, nil\n}", "func (m CrossOrderCancelReplaceRequest) GetProcessCode() (v enum.ProcessCode, err quickfix.MessageRejectError) {\n\tvar f field.ProcessCodeField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func ActivePIDC(pid int32, args ...int) {\n\tvar hwnd int\n\tif len(args) > 0 {\n\t\thwnd = args[0]\n\n\t\tinternalActive(pid, hwnd)\n\t\treturn\n\t}\n\n\tif xu == nil {\n\t\tvar err error\n\t\txu, err = xgbutil.NewConn()\n\t\tif err != nil {\n\t\t\tlog.Println(\"xgbutil.NewConn errors is: \", err)\n\t\t\treturn\n\t\t}\n\t}\n\n\txid, err := getXidFromPid(xu, pid)\n\tif err != nil {\n\t\tlog.Println(\"getXidFromPid errors is: \", err)\n\t\treturn\n\t}\n\n\tinternalActive(int32(xid), hwnd)\n}", "func (p *procBase) Pid() int {\n\tif !p.Running() {\n\t\treturn 0\n\t}\n\treturn p.cmd.Process.Pid\n}", "func GetSystemByID(id string) (System, error) {\n\tvar (\n\t\tdb = GetGORMDbConnection()\n\t\tsystem System\n\t\terr error\n\t)\n\tdefer Close(db)\n\n\tif _, err = strconv.ParseUint(id, 10, 64); err != nil {\n\t\treturn System{}, fmt.Errorf(\"invalid input %s; %s\", id, err)\n\t}\n\t// must use the explicit where clause here because the id argument is a string\n\tif err = db.Find(&system, \"id = ?\", id).Error; err != nil {\n\t\terr = fmt.Errorf(\"no System record found with ID %s\", id)\n\t}\n\treturn system, err\n}", "func (m CrossOrderCancelReplaceRequest) GetOrderID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.OrderIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (ec *executionContext) _Order_id(ctx context.Context, field graphql.CollectedField, obj *order.Order) (ret graphql.Marshaler) {\n\tfc, err := ec.fieldContext_Order_id(ctx, field)\n\tif err != nil {\n\t\treturn graphql.Null\n\t}\n\tctx = graphql.WithFieldContext(ctx, fc)\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\tec.Error(ctx, ec.Recover(ctx, r))\n\t\t\tret = graphql.Null\n\t\t}\n\t}()\n\tresTmp, err := ec.ResolverMiddleware(ctx, func(rctx context.Context) (interface{}, error) {\n\t\tctx = rctx // use context from middleware stack in children\n\t\treturn ec.resolvers.Order().ID(rctx, obj)\n\t})\n\tif err != nil {\n\t\tec.Error(ctx, err)\n\t\treturn graphql.Null\n\t}\n\tif resTmp == nil {\n\t\tif !graphql.HasFieldError(ctx, fc) {\n\t\t\tec.Errorf(ctx, \"must not be null\")\n\t\t}\n\t\treturn graphql.Null\n\t}\n\tres := resTmp.(string)\n\tfc.Result = res\n\treturn ec.marshalNID2string(ctx, field.Selections, res)\n}", "func (x *CtlCommand) getPid(rpcc *rpcclient.RPCClient, process string) {\n\tret, err := rpcc.GetProcessInfo(&rpcclient.GetProcessInfoArg{process})\n\tif err != nil {\n\t\tfmt.Printf(\"program '%s' not found\\n\", process)\n\t\tos.Exit(1)\n\t\treturn\n\t}\n\tfmt.Printf(\"%d\\n\", ret.ProcessInfo.Pid)\n}", "func NewIIDProcess(params []variable.RandomVariable, dist dist.Dist) *IIDProcess {\n\treturn &IIDProcess{\n\t\tParams: params,\n\t\tDist: dist,\n\t}\n}", "func (a *paymentUsecase) GetByID(c context.Context, id int64) (*models.Payment, error) {\n\tctx, cancel := context.WithTimeout(c, a.contextTimeout)\n\tdefer cancel()\n\n\tres, err := a.repo.GetByID(ctx, id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn res, nil\n}", "func (p Order) GetServiceID() string {\n\treturn p.ServiceID.Hex()\n}", "func (m NoMDEntries) GetOrderID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.OrderIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (db *MySQLDB) GetProductByID(ctx context.Context, productID int) (*ProductRecord, error) {\n\tfLog := mysqlLog.WithField(\"func\", \"GetProductByID\")\n\tproduct := &ProductRecord{}\n\n\trow := db.instance.QueryRowContext(ctx, \"SELECT id, brand_id, name, price, qty FROM products WHERE id = ?\", productID)\n\terr := row.Scan(&product.ID, &product.BrandID, &product.Name, &product.Price, &product.Qty)\n\tif err != nil {\n\t\tfLog.Errorf(\"row.Scan got %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn product, nil\n}", "func (m DontKnowTrade) GetOrderID() (v string, err quickfix.MessageRejectError) {\n\tvar f field.OrderIDField\n\tif err = m.Get(&f); err == nil {\n\t\tv = f.Value()\n\t}\n\treturn\n}", "func (s *ProcessesServiceOp) Get(ctx context.Context, groupID, hostname string, port int) (*Process, *Response, error) {\n\tif groupID == \"\" {\n\t\treturn nil, nil, NewArgError(\"groupID\", \"must be set\")\n\t}\n\tif hostname == \"\" {\n\t\treturn nil, nil, NewArgError(\"hostname\", \"must be set\")\n\t}\n\tif port == 0 {\n\t\treturn nil, nil, NewArgError(\"port\", \"must be set\")\n\t}\n\tpath := fmt.Sprintf(processesPath, groupID)\n\tpath = fmt.Sprintf(\"%s/%s:%d\", path, hostname, port)\n\treq, err := s.Client.NewRequest(ctx, http.MethodGet, path, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := new(Process)\n\tresp, err := s.Client.Do(ctx, req, root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn root, resp, nil\n}", "func (r *PackageProductRow) GetProductID() int32 { return r.Data.ProductID }", "func (c *Container) PID() (int, error) {\n\tc.lock.Lock()\n\tdefer c.lock.Unlock()\n\n\tif err := c.syncContainer(); err != nil {\n\t\treturn -1, err\n\t}\n\n\treturn c.state.PID, nil\n}", "func (ph *processHashtable) getKey(process *model.Process) string {\n\tif ph.processes == nil {\n\t\tph.processes = make(map[uint64][]processKey)\n\t}\n\thash := ph.hash(process)\n\tif keys, ok := ph.processes[hash]; ok {\n\t\tfor _, k := range keys {\n\t\t\tif k.process.Equal(process) {\n\t\t\t\treturn k.key\n\t\t\t}\n\t\t}\n\t\tkey := ph.nextKey()\n\t\tkeys = append(keys, processKey{process: process, key: key})\n\t\tph.processes[hash] = keys\n\t\treturn key\n\t}\n\tkey := ph.nextKey()\n\tph.processes[hash] = []processKey{{process: process, key: key}}\n\treturn key\n}", "func FetchPersonallyProcuredMoveByOrderID(db *pop.Connection, orderID uuid.UUID) (*PersonallyProcuredMove, error) {\n\tvar ppm PersonallyProcuredMove\n\terr := db.Q().\n\t\tLeftJoin(\"moves as m\", \"m.id = personally_procured_moves.move_id\").\n\t\tWhere(\"m.orders_id = ?\", orderID).\n\t\tFirst(&ppm)\n\tif err != nil {\n\t\tif errors.Cause(err).Error() == RecordNotFoundErrorString {\n\t\t\treturn &PersonallyProcuredMove{}, ErrFetchNotFound\n\t\t}\n\t\treturn &PersonallyProcuredMove{}, err\n\t}\n\n\treturn &ppm, nil\n}", "func (p *Provider) GetNUMANodeIDForPID(ctx context.Context, pid int32) (uint, error) {\n\tch := make(chan numaResult)\n\tgo p.getNUMANodeIDForPIDAsync(ctx, pid, ch)\n\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn 0, ctx.Err()\n\tcase result := <-ch:\n\t\treturn result.numaNode, result.err\n\t}\n}", "func GetOrderByID(order *Order, id string) (err error) {\n\tif err = Config.DB.Where(\"id = ?\", id).First(order).Error; err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (wo *WorkOrder) id() int {\n\tid, _ := strconv.Atoi(wo.ID)\n\treturn id\n}", "func NewBuildOrderProcess(\n\toc controllers.OrderController,\n\tpc controllers.ProductController,\n\tuc controllers.UserController,\n) process.Processor {\n\tproc := BuildOrderProcess{}\n\tproc.name = \"Order Products\"\n\tproc.orders = oc\n\tproc.products = pc\n\tproc.users = uc\n\treturn proc\n}", "func (node *PostgresNode) GetProcess() (result *Process) {\n\tresult = getProcessByPid(node.Pid())\n\tresult.Type = Postmaster\n\treturn result\n}", "func (r *ProcessorResolver) Component(ctx context.Context, processor *model.Processor) (*model.Component, error) {\n\tresult, err := r.DataLoaders.ProcessorLoader(ctx).ComponentByProcessor(processor.ID)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get component from loader\")\n\t}\n\treturn result, nil\n}", "func (s *Store) GetApcByID(ctx context.Context, id int) (*[]APC, error) {\n\tapc := []APC{}\n\n\tif err := s.db.Select(&apc, getApcByID, id); err != nil {\n\t\tlog.Error(err)\n\t\treturn nil, err\n\t}\n\n\treturn &apc, nil\n}", "func (c *CmdReal) GetProcess() ios.Process {\n\treturn ios.NewProcess(c.cmd.Process)\n}", "func (ps *ProductService) GetByID(ctx context.Context, id int) (*Product, *Response, error) {\n\tp := fmt.Sprintf(\"products/%d\", id)\n\treq, err := ps.client.NewRequest(\"GET\", p, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tproduct := new(Product)\n\tresp, err := ps.client.Do(ctx, req, product)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn product, resp, nil\n}", "func ImportProcess(path string) (*Process, error) {\n\tdat, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to read PID file %q: %w\", path, err)\n\t}\n\n\tproc := Process{}\n\terr = yaml.Unmarshal(dat, &proc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Unable to parse YAML in PID file %q: %w\", path, err)\n\t}\n\n\treturn &proc, nil\n}", "func (ps *ProjectsPG) GetByID(ctx context.Context, id string, customerId string) (*api.Project, error) {\n\tprojs, err := ps.getBySQL(ctx, \"WHERE id=$1 AND customer_id=$2 LIMIT 1\", id, customerId)\n\tif err != nil {\n\t\treturn nil, errors.Wrapf(err, \"failed to get project by id: %s customerId: %s\", id, customerId)\n\t}\n\n\tif len(projs) == 0 {\n\t\treturn nil, &ProjectNotFoundError{fmt.Sprintf(\"id %s\", id)}\n\t}\n\treturn &projs[0], nil\n}", "func (c Companion) FindByID(id uint) *Companion {\n\tdb := db.GetDb()\n\tcompanion := new(Companion)\n\tdb.First(&companion, id)\n\treturn companion\n}", "func NewProcess(c *Component) *Process {\n\tp := Process{\n\t\tComp: c,\n\n\t\tchnAcceptMessage: make(chan bool),\n\t\tchnMessage: make(chan attributesInMessage),\n\t}\n\treturn &p\n}", "func processPath(pid uint32) (string, error) {\r\n\tsnap, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPMODULE, pid)\r\n\tif err != nil {\r\n\t\treturn \"\", errors.Wrap(err, \"modules list snapshot\")\r\n\t}\r\n\tdefer windows.CloseHandle(snap)\r\n\r\n\tentry := winapi.ModuleEntry32{}\r\n\tentry.Size = uint32(unsafe.Sizeof(entry))\r\n\tif err = winapi.Module32First(snap, &entry); err != nil {\r\n\t\treturn \"\", errors.Wrap(err, \"first process module entry\")\r\n\t}\r\n\r\n\treturn windows.UTF16ToString(entry.ExePath[:]), nil\r\n}", "func (d *DB) ProductByID(id string) (p Product, found bool) {\n\tfor _, product := range d.Products {\n\t\tif product.ID == id {\n\t\t\treturn product, true\n\t\t}\n\t}\n\treturn\n}" ]
[ "0.64895046", "0.57633936", "0.57099223", "0.5554113", "0.5474267", "0.524535", "0.52283865", "0.51899385", "0.51103336", "0.5103208", "0.50500935", "0.50482893", "0.49981907", "0.49786568", "0.49697137", "0.4951414", "0.49393922", "0.49203083", "0.4918713", "0.49077082", "0.48993", "0.4863263", "0.4859408", "0.4842328", "0.4839769", "0.48387676", "0.48246777", "0.47788602", "0.4768716", "0.4765058", "0.4757635", "0.47557008", "0.47510368", "0.4726149", "0.47185248", "0.4713804", "0.47089747", "0.4707129", "0.47035748", "0.46984226", "0.4676426", "0.4650139", "0.463951", "0.4625733", "0.46117222", "0.46058849", "0.4605403", "0.45909068", "0.4580701", "0.45800886", "0.45769194", "0.45709246", "0.4565215", "0.4557638", "0.45540154", "0.45399362", "0.45341277", "0.4518702", "0.45127827", "0.45048285", "0.44894797", "0.4485609", "0.44840705", "0.44836167", "0.44835883", "0.44827995", "0.44739726", "0.4466109", "0.44649526", "0.44639722", "0.44629395", "0.4460423", "0.4459137", "0.44569895", "0.4456785", "0.44548887", "0.4453047", "0.44494477", "0.44452375", "0.44438115", "0.44297546", "0.4424359", "0.44194323", "0.44129044", "0.44120547", "0.44014502", "0.4401371", "0.4401201", "0.4400374", "0.43892097", "0.4388055", "0.43878952", "0.43850505", "0.4383183", "0.4382941", "0.4370215", "0.4363327", "0.43592393", "0.43576252", "0.43520406" ]
0.83237463
0
Get returns a random TCP port. It asks the OS to return a random address by swifly listening on ":0". The listener will then be closed immediately and Get will return the assigned port. Warning: Get will panic if listen fails.
func Get() int { lis, err := net.Listen("tcp", ":0") if err != nil { panic(err) } defer lis.Close() return lis.Addr().(*net.TCPAddr).Port }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Get() (port int, err error) {\n\treturn within(0, 0)\n}", "func getPort() int {\n\tcount := 0\n\tfor count < 1000 {\n\t\tln, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\t\tif err == nil {\n\t\t\tp := ln.Addr().(*net.TCPAddr).Port\n\t\t\tln.Close()\n\t\t\treturn p\n\t\t}\n\t\tcount++\n\t}\n\tpanic(\"Could not find an available port\")\n}", "func GetFreePort(t *testing.T) string {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\trequire.NoError(t, err)\n\tlistener, err := net.ListenTCP(\"tcp\", addr)\n\trequire.NoError(t, err)\n\tdefer listener.Close()\n\n\taddress := listener.Addr().String()\n\tcolon := strings.Index(address, \":\")\n\tport := address[colon+1:]\n\treturn port\n}", "func GetPort() int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port\n}", "func getFreePort() (int, error) {\n\tlistener, err := net.Listen(\"tcp\", \":0\")\n\tdefer listener.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tport := listener.Addr().(*net.TCPAddr).Port\n\treturn port, nil\n}", "func randomPort() string {\n\tl, err := net.Listen(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\t// listening for port 0 should never error but just in case\n\t\treturn strconv.Itoa(1024 + rand.Intn(65536-1024))\n\t}\n\n\tp := l.Addr().(*net.TCPAddr).Port\n\tl.Close()\n\treturn strconv.Itoa(p)\n}", "func RandomPort() (int, error) {\n\tl, err := net.Listen(\"tcp\", \"\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif err := l.Close(); err != nil {\n\t\treturn 0, nil\n\t}\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func Get() int {\n\tfor i := maxReservedTCPPort; i < maxTCPPort; i++ {\n\t\tp := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1\n\t\tif IsAvailable(p) {\n\t\t\treturn p\n\t\t}\n\t}\n\treturn -1\n}", "func getFreePort(t *testing.T) string {\n\tl, err := net.Listen(\"tcp\", \":\")\n\tif err != nil {\n\t\tt.Fatalf(\"getFreePort: could not get free port: %v\", err)\n\t}\n\tdefer l.Close()\n\treturn l.Addr().String()[strings.LastIndex(l.Addr().String(), \":\"):]\n}", "func FindRandomPort() int {\n\tlistener, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tport := strconv.Itoa(listener.Addr().(*net.TCPAddr).Port)\n\n\terr = listener.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tp, err := strconv.Atoi(port)\n\tif err != nil || p == 0 {\n\t\tpanic(err)\n\t}\n\n\treturn p\n}", "func randomPort() (string, error) {\n\tconst (\n\t\tminPort = 1024\n\t\tmaxPort = 65535\n\t\tmaxTries = 10\n\t)\n\tfor i := 0; i < maxTries; i++ {\n\t\tport := rand.Intn(maxPort-minPort+1) + minPort\n\t\tl, err := net.Listen(\"tcp\", fmt.Sprintf(\":%d\", port))\n\t\tif err == nil {\n\t\t\t_ = l.Close()\n\t\t\treturn strconv.Itoa(port), nil\n\t\t}\n\t\tflog.Info(\"port taken: %d\", port)\n\t}\n\n\treturn \"\", xerrors.Errorf(\"max number of tries exceeded: %d\", maxTries)\n}", "func getFreePort() int {\n\tln, err := net.Listen(\"tcp\", \"[::]:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tport := ln.Addr().(*net.TCPAddr).Port\n\n\terr = ln.Close()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn port\n}", "func getPort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func getAvailablePort(t *testing.T) int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\trequire.Nil(t, err)\n\n\tlisten, err := net.ListenTCP(\"tcp\", addr)\n\trequire.Nil(t, err)\n\n\tdefer listen.Close()\n\treturn listen.Addr().(*net.TCPAddr).Port\n}", "func getPort() (port uint16) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\treturn uint16(l.Addr().(*net.TCPAddr).Port)\n}", "func GetPort() (int, error) {\n\tfor i := previousPort; i < maxPort; i++ {\n\t\tif IsPortAvailable(i) {\n\t\t\t// Next previousPort is 1124 if i == 1024 now.\n\t\t\tpreviousPort = i + 100\n\t\t\treturn i, nil\n\t\t}\n\t}\n\treturn -1, errors.New(\"Not found free TCP Port\")\n}", "func (server *testHTTPServerImpl) GetPort() int64 {\n\tif server.port == nil {\n\t\tport := server.randomFreePort()\n\t\tserver.port = &port\n\t}\n\treturn *server.port\n}", "func getFreePort() string {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\treturn fmt.Sprintf(\"%d\", l.Addr().(*net.TCPAddr).Port)\n}", "func GetListener() net.Listener {\n\t// I create a TCP listener on the specified port...\n\tlistener, err := net.Listen(\"tcp4\", \":5001\")\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\t// ... and I return it\n\treturn listener\n}", "func (r *reader) GetListeningPort() (listeningPort uint16, err error) {\n\ts, err := r.envParams.GetEnv(\"LISTENINGPORT\", libparams.Default(\"53\"))\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tn, err := strconv.ParseUint(s, 10, 16)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn uint16(n), nil\n}", "func GetListener(address string) (listener *net.Listener, serverAddress string, err error) {\n\tvar l net.Listener = nil\n\n\tre := regexp.MustCompile(\"localhost:\\\\d+\")\n\tmatch := re.FindString(address)\n\n\tif match == \"\" { // Case: No given port provided for localhost\n\t\t// Creating a listener on the next available port\n\t\tl, err = net.Listen(\"tcp\", \"localhost:0\")\n\t} else { // Case: Port provided for localhost\n\t\t// Creating a listener on the provided port\n\t\tl, err = net.Listen(\"tcp\", match)\n\t}\n\n\tif err != nil {\n\t\treturn nil, \"\", fmt.Errorf(\"Unable to open port: %v\", err)\n\t}\n\n\ttcpPort := (l).Addr().(*net.TCPAddr).Port\n\t// Updating redirect uri to reflect port to use.\n\tlocalhostAddr := \"http://localhost:\" + strconv.Itoa(tcpPort)\n\treturn &l, localhostAddr, nil\n}", "func GetFreePort() int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tlisten, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer listen.Close()\n\treturn listen.Addr().(*net.TCPAddr).Port\n}", "func (p *paramsReader) GetListeningPort() (listeningPort uint16, err error) {\r\n\ts, err := p.envParams.GetEnv(\"LISTENINGPORT\", libparams.Default(\"53\"))\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\tn, err := strconv.ParseUint(s, 10, 16)\r\n\tif err != nil {\r\n\t\treturn 0, err\r\n\t}\r\n\treturn uint16(n), nil\r\n}", "func getFreePort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func findFreePort() int {\n\tln, _ := net.Listen(\"tcp\", \":0\")\n\tln.Close()\n\n\taddr := ln.Addr().(*net.TCPAddr)\n\treturn addr.Port\n}", "func pickFreeAddr(t *testing.T) string {\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer l.Close()\n\treturn l.Addr().String()\n}", "func freeport(t *testing.T) (port int, addr string) {\n\tl, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\")})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer l.Close()\n\ta := l.Addr().(*net.TCPAddr)\n\tport = a.Port\n\treturn port, a.String()\n}", "func GetFreePort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func (p *PortForward) getFreePort() (int, error) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tport := listener.Addr().(*net.TCPAddr).Port\n\terr = listener.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn port, nil\n}", "func (p *PortForward) getFreePort() (int, error) {\n\tlistener, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tport := listener.Addr().(*net.TCPAddr).Port\n\terr = listener.Close()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn port, nil\n}", "func GetRandomPort() int32 {\n\treturn rand.Int31n(maxValidPort) + 1\n}", "func ListenOnLocalRandomPort() (net.Listener, error) {\n\tip, err := Localhost()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn net.ListenTCP(\"tcp\", &net.TCPAddr{IP: ip, Port: 0})\n}", "func freeport() (port int, addr string) {\n\tl, err := net.ListenTCP(\"tcp\", &net.TCPAddr{IP: net.ParseIP(\"127.0.0.1\")})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\ta := l.Addr().(*net.TCPAddr)\n\tport = a.Port\n\treturn port, a.String()\n}", "func getProbablyFreePortNumber() (int, error) {\n\tl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer l.Close()\n\n\t_, port, err := net.SplitHostPort(l.Addr().String())\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tportNum, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn portNum, nil\n}", "func FreePort() (int, error) {\n\t// Opens a TCP connection to a free port on the host\n\t// and closes the connection but getting the port from it\n\t// so the can be setted to a free\n\t// random port each time if no one is specified\n\tl, err := net.Listen(\"tcp\", \"\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl.Close()\n\tsl := strings.Split(l.Addr().String(), \":\")\n\tp, err := strconv.Atoi(sl[len(sl)-1])\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn p, nil\n}", "func freePort() (uint16, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn uint16(l.Addr().(*net.TCPAddr).Port), nil\n}", "func freePort() (uint16, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn uint16(l.Addr().(*net.TCPAddr).Port), nil\n}", "func (s *DefaultServer) GetPort() uint16 {\n\treturn s.port\n}", "func (box *Box) Listen() string {\n\treturn fmt.Sprintf(\"127.0.0.1:%v\", box.Port)\n}", "func FreePort() int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn 0\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\treturn 0\n\t}\n\n\tdefer l.Close()\n\n\treturn l.Addr().(*net.TCPAddr).Port\n}", "func (p *Proxy) GetServePort(id uint64) int {\n\tif p.ports == 1 {\n\t\treturn p.port\n\t}\n\n\tfor failed := 0; failed < p.ports; failed++ {\n\t\tport := (atomic.AddUint64(&p.roundRobinCounter, 1) - 1) % uint64(p.ports)\n\t\tif p.listeners[port] != nil {\n\t\t\treturn int(port) + p.port\n\t\t}\n\t}\n\t// If no ports is available, simply return a port.\n\treturn 0\n}", "func FreePort() (int, error) {\n\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tlisten, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tdefer listen.Close()\n\treturn listen.Addr().(*net.TCPAddr).Port, nil\n}", "func getListenAddress() string {\n\tport := getEnv(\"PORT\", \"1338\")\n\treturn \":\" + port\n}", "func getListenAddress() string {\n\tport := getEnv(\"PORT\", \"1338\")\n\treturn \":\" + port\n}", "func (ss ServerSettings) GetPort() string {\n\tport := ss.General.Port\n\tif port == \"\" {\n\t\tpanic(\"can't start without port\")\n\t}\n\treturn \":\" + port\n}", "func RandomPort() int {\n\tr := rand.New(rand.NewSource(time.Now().UnixNano()))\n\tport := r.Intn(2000) + 30000\n\tfor i := 0; i < 18000; i++ {\n\t\tif checkPortIsOpen(port) == false {\n\t\t\tbreak\n\t\t}\n\t\tport++\n\t\t// retry next port\n\t}\n\treturn port\n}", "func (this *ReceiverHolder) getListener() (net.Listener, error) {\n\tvar port string = \"0\"\n\tif this.receiver.port != \"\" {\n\t\tport = this.receiver.port\n\t}\n\tlistener, err := net.Listen(\"tcp\", fmt.Sprintf(\":%s\", port))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%s\", err.Error())\n\t}\n\treturn listener, nil\n}", "func findPort() (int, error) {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func GetPort(site, UserAgent string) int {\n\treturn getAPIResponse(site, UserAgent).Port\n}", "func GetPort() string {\r\n\tport := os.Getenv(\"PORT\")\r\n\tif len(port) == 0 {\r\n\t\tport = \"9898\"\r\n\t}\r\n\treturn \":\" + port\r\n}", "func GetFreePort(host string, preferredPort uint32) (int, error) {\n\taddress := host + \":\" + fmt.Sprint(preferredPort)\n\taddr, err := net.ResolveTCPAddr(\"tcp\", address)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port, nil\n}", "func (s *Server) GetPort() (port uint16) {\n\tport = defaultIrcPort\n\tif s.Port != 0 {\n\t\tport = s.Port\n\t} else if s.parent != nil && s.parent.Global.Port != 0 {\n\t\tport = s.parent.Global.Port\n\t}\n\treturn\n}", "func FindFreePort() int {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdefer l.Close()\n\treturn l.Addr().(*net.TCPAddr).Port\n}", "func (server *testHTTPServerImpl) randomFreePort() int64 {\n\tmaxAttempts := 5\n\tattempt := 0\n\trandomPort := server.randomPort()\n\tfor attempt < maxAttempts && server.isPortInUse(randomPort) {\n\t\tlog.Printf(\"Port %d already in use, try with new port number\", randomPort)\n\t\tattempt++\n\t\trandomPort = server.randomPort()\n\t}\n\treturn randomPort\n}", "func randomPort() int {\n\tconst minPort = 1024\n\tconst maxPort = 65535\n\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(maxPort-minPort) + minPort\n}", "func Listen() (string, net.Listener, error) {\n\tlis, err := net.Listen(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"failed to listen: %v\", err)\n\t}\n\t_, port, err := net.SplitHostPort(lis.Addr().String())\n\tif err != nil {\n\t\treturn \"\", nil, fmt.Errorf(\"Failed to parse listener address: %v\", err)\n\t}\n\taddr := \"localhost:\" + port\n\treturn addr, lis, nil\n}", "func GetPort(addr string) int {\n\ts := strings.Split(addr, \":\")\n\tport, _ := strconv.Atoi(s[1])\n\treturn port\n}", "func (p *PortForward) getListenPort() (int, error) {\n\tvar err error\n\n\tif p.ListenPort == 0 {\n\t\tp.ListenPort, err = p.getFreePort()\n\t}\n\n\treturn p.ListenPort, err\n}", "func (p *PortForward) getListenPort() (int, error) {\n\tvar err error\n\n\tif p.ListenPort == 0 {\n\t\tp.ListenPort, err = p.getFreePort()\n\t}\n\n\treturn p.ListenPort, err\n}", "func GetPort() string {\n\tvar port = os.Getenv(\"PORT\")\n\n\t// Check if port is blank (localhost)\n\tif port == \"\" {\n\t\tport = \"4747\"\n\t}\n\n\treturn \":\" + port\n}", "func RandomTCPPort() int {\n\tfor i := maxReservedTCPPort; i < maxTCPPort; i++ {\n\t\tp := tcpPortRand.Intn(maxRandTCPPort) + maxReservedTCPPort + 1\n\t\tif IsTCPPortAvailable(p) {\n\t\t\treturn p\n\t\t}\n\t}\n\treturn -1\n}", "func GetPort() string {\n\treturn fmt.Sprintf(\":%d\", viper.GetInt(port))\n}", "func (g *GRPC) Port() int {\n\treturn g.lis.Addr().(*net.TCPAddr).Port\n}", "func (a *App) getPort() int {\n\tif a.Configs.Service.Listen == 0 {\n\t\ta.Logger.Debug(\"no port specified, using default port\", logging.DataFields{\"port\": PORT})\n\t\treturn PORT\n\t}\n\treturn a.Configs.Service.Listen\n}", "func (m *Manager) GetRandomEvenPort() (int, error) {\n\tfor i := 0; i < 128; i++ {\n\t\tconn, addr, err := m.allocatePacketConn(\"udp4\", 0)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tudpAddr, ok := addr.(*net.UDPAddr)\n\t\terr = conn.Close()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\n\t\tif !ok {\n\t\t\treturn 0, errFailedToCastUDPAddr\n\t\t}\n\t\tif udpAddr.Port%2 == 0 {\n\t\t\treturn udpAddr.Port, nil\n\t\t}\n\t}\n\treturn 0, errFailedToAllocateEvenPort\n}", "func (app *App) GetPort() string {\n\tport := app.LoadedConfig.ServerPort\n\n\tportEnv := os.Getenv(\"PORT\")\n\n\tif portEnv != \"\" {\n\t\tport = portEnv\n\t\tlog.Println(\"Using port set in the environment, PORT=\" + port)\n\t}\n\treturn port\n}", "func Create(port string) (net.Listener, *grpc.Server) {\n\t//TODO: Find a better way to pass \"127.0.0.1:\"\n\tlis, err := net.Listen(\"tcp\", \"127.0.0.1:\"+port)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"port\": port,\n\t\t}).WithError(err).Fatal(\"Failed to bind port !\")\n\t\tlog.Print(\"Trying to bind onto another port !\")\n\t}\n\treturn lis, grpc.NewServer()\n}", "func StartTemporaryListener() int {\n\t// @todo: move this to a setup/teardown (Issue #29)\n\t// Temporarily listen for the test connection\n\tconn, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\ttmpListener = conn\n\tladdr := strings.Split(conn.Addr().String(), \":\")\n\tif len(laddr) < 2 {\n\t\tpanic(\"Could not get port of listener.\")\n\t}\n\n\tport, err := strconv.ParseInt(laddr[1], 10, 32)\n\n\tif err != nil {\n\t\tpanic(\"Could not get port of listener.\")\n\t}\n\n\treturn int(port)\n}", "func (self *holder) GetPort() int {\n\treturn self.port\n}", "func GetServer(port int) *Server {\n\treturn servers[port]\n}", "func (srv *Server) getListener(addr string) (*net.TCPListener, error) {\n\tvar ln net.Listener\n\tvar err error\n\n\tif srv.isGraceful {\n\t\tfile := os.NewFile(3, \"\")\n\t\tln, err = net.FileListener(file)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"GraceHttp: net.FileListener error: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tln, err = net.Listen(\"tcp\", addr)\n\t\tif err != nil {\n\t\t\terr = fmt.Errorf(\"GraceHttp: net.Listen error: %v\", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn ln.(*net.TCPListener), nil\n}", "func GetPort() string {\n\tp := os.Getenv(\"APP_PORT\")\n\tif \"\" == p {\n\t\tp = \"3030\"\n\t}\n\n\treturn fmt.Sprintf(\":%s\", p)\n}", "func (mds *metadataService) Port() int {\n\treturn mds.listener.Addr().(*net.TCPAddr).Port\n}", "func (d *discovery) Choose() (target string, port uint16) {\n\td.serversLock.RLock()\n\tdefer d.serversLock.RUnlock()\n\n\td.loadBalancerLock.RLock()\n\ttarget, port = d.loadBalancer.LoadBalance()\n\td.loadBalancerLock.RUnlock()\n\n\treturn\n}", "func GetAddr() string {\n\tvar port = os.Getenv(\"PORT\")\n\n\tif port == \"\" {\n\t\tport = \"8080\"\n\t\tfmt.Println(\"No port variable detected, defaulting to \" + port)\n\t}\n\treturn \":\" + port\n}", "func getEndPoint(port int) string {\n\treturn fmt.Sprintf(\"http://%s:%d\", defaultServerIP, port)\n}", "func (m *Manager) useFreePort() error {\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer l.Close()\n\tlocalServerPort = l.Addr().(*net.TCPAddr).Port\n\treturn nil\n}", "func ListenHTTP(ctx context.Context) (int, error) {\n\tl, err := net.Listen(\"tcp\", \":0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tserver := new(http.Server)\n\tserver.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tHandler(w, r.WithContext(ctx))\n\t})\n\tgo server.Serve(l)\n\tgo func() {\n\t\t<-ctx.Done()\n\t\tserver.Shutdown(context.Background())\n\t\tserver.Close()\n\t}()\n\n\t_, port, _ := net.SplitHostPort(l.Addr().String())\n\tn, _ := strconv.Atoi(port)\n\treturn n, nil\n}", "func (f *FastURL) GetPort() []byte {\n\treturn f.port\n}", "func FindUnusedPort() (uint16, error) {\n\t// We let the kernel to find the port for us.\n\taddr, err := net.ResolveTCPAddr(\"tcp\", \"localhost:0\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tl, err := net.ListenTCP(\"tcp\", addr)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer l.Close()\n\treturn uint16(l.Addr().(*net.TCPAddr).Port), nil\n}", "func getPort() (string, error) {\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\treturn \":3500\", fmt.Errorf(\"$PORT not set\")\n\t}\n\n\treturn \":\" + port, nil\n}", "func (d *Device) ListenPort() int {\n\treturn d.listenPort\n}", "func GetPORT() string {\n\tport := os.Getenv(\"PORT\")\n\tif !strings.Contains(port, \":\") {\n\t\tport = \":\" + port\n\t}\n\tif len(port) < 3 {\n\t\tport = \":6007\"\n\t}\n\treturn port\n}", "func generateRandomPort(minPort int, maxPort int) int {\n\trand.Seed(time.Now().UnixNano())\n\treturn rand.Intn(maxPort - minPort) + minPort\n}", "func GetPort(lookupFunc func(key string) (string, bool)) string {\n\tif lookupFunc == nil {\n\t\tlookupFunc = os.LookupEnv\n\t}\n\n\tif port, ok := lookupFunc(EnvPort); ok {\n\t\treturn port\n\t}\n\n\treturn \"8080\"\n}", "func (s *Server) Port() int {\n return s.ln.Addr().(*net.TCPAddr).Port\n}", "func GetPort() string {\n\tport := os.Getenv(\"PORT\")\n\tif len(port) == 0 {\n\t\tport = \"8080\"\n\t}\n\treturn port\n}", "func Listen(name string, port string) (net.Listener, *net.TCPAddr) {\n\tnPort := NormalizePort(port)\n\tlistener, err := net.Listen(\"tcp\", nPort)\n\tif err != nil {\n\t\tlog.Critf(\"Can't listen to %v for %s: %v\", nPort, name, err)\n\t\treturn nil, nil\n\t}\n\taddr := listener.Addr().(*net.TCPAddr)\n\tif len(name) > 0 {\n\t\tfmt.Printf(\"Fortio %s %s server listening on %s\\n\", version.Short(), name, addr.String())\n\t}\n\treturn listener, addr\n}", "func (s *Server) Listen() (net.Listener, error) {\n\tl, err := reuseport.Listen(\"tcp\", s.Addr[len(transport.DNS+\"://\"):])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn l, nil\n}", "func getListener(socketPath string, listenerMap map[string]net.Listener) (net.Listener, error) {\n\tif listener, ok := listenerMap[socketPath]; ok {\n\t\treturn listener, nil\n\t}\n\n\tif c, err := net.Dial(\"unix\", socketPath); err == nil {\n\t\tc.Close()\n\t\treturn nil, fmt.Errorf(\"socket %q already in use\", socketPath)\n\t}\n\n\tif err := os.Remove(socketPath); err != nil && !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\taddress, err := net.ResolveUnixAddr(\"unix\", socketPath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\truntime.LockOSThread()\n\toldmask := syscall.Umask(0111)\n\tlistener, err := net.ListenUnix(\"unix\", address)\n\tsyscall.Umask(oldmask)\n\truntime.UnlockOSThread()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Debugf(\"socket %q was not activated; listening\", socketPath)\n\n\treturn listener, nil\n}", "func RandPort(lo, hi int) int {\n\treturn lo + rand.Intn(hi-lo)\n}", "func RunServer(port int) {}", "func Listen(port int) {\n\tgo func() {\n\t\tsrv := &dns.Server{Addr: \":\" + strconv.Itoa(port), Net: \"udp\"}\n\t\tlog.Printf(\"Listening on udp port %d\", port)\n\t\tif err := srv.ListenAndServe(); err != nil {\n\t\t\tlog.Fatalf(\"Failed to set udp listener: %s\\n\", err.Error())\n\t\t}\n\t}()\n\n\tgo func() {\n\t\tsrv := &dns.Server{Addr: \":\" + strconv.Itoa(port), Net: \"tcp\"}\n\t\tlog.Printf(\"Listening on tcp port %d\", port)\n\t\tif err := srv.ListenAndServe(); err != nil {\n\t\t\tlog.Fatalf(\"Failed to set tcp listener: %s\\n\", err.Error())\n\t\t}\n\t}()\n}", "func (s *Socket) Port() string {\n\tif s.port == \"\" {\n\t\ts.port = strings.Split(path.Base(s.fname), \":\")[util.PORT]\n\t\treturn s.port\n\t}\n\treturn s.port\n}", "func alloc() (int, net.Listener) {\n\tfor i := 0; i < attempts; i++ {\n\t\tblock := int(rand.Int31n(int32(effectiveMaxBlocks)))\n\t\tfirstPort := lowPort + block*blockSize\n\t\tln, err := net.ListenTCP(\"tcp\", tcpAddr(\"127.0.0.1\", firstPort))\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\t// logf(\"DEBUG\", \"allocated port block %d (%d-%d)\", block, firstPort, firstPort+blockSize-1)\n\t\treturn firstPort, ln\n\t}\n\tpanic(\"freeport: cannot allocate port block\")\n}", "func NewListener() (net.Listener, error) {\n\tport := os.Getenv(\"PORT\")\n\tif port == \"\" {\n\t\tport = defaultPort\n\t}\n\treturn net.Listen(\"tcp\", \":\"+port)\n}", "func LoadServerPort() int {\n\treturn viper.GetInt(\"port\")\n}", "func (this *HostAddress) GetPort() uint16 {\n\treturn this.port\n}", "func getPort() string {\n\tvar PORT = os.Getenv(\"PORT\")\n\tif PORT == \"\" {\n\t\tPORT = \"9001\"\n\t\tfmt.Println(\"no port set in environment variable, using default port \" + PORT)\n\t}\n\treturn \":\" + PORT\n}", "func GetServerPort(l *v1alpha1.ListenersConfig) int32 {\n\tvar httpsServerPort int32\n\tvar httpServerPort int32\n\tfor _, iListener := range l.InternalListeners {\n\t\tif iListener.Type == v1alpha1.HttpsListenerType {\n\t\t\thttpsServerPort = iListener.ContainerPort\n\t\t} else if iListener.Type == v1alpha1.HttpListenerType {\n\t\t\thttpServerPort = iListener.ContainerPort\n\t\t}\n\t}\n\tif httpsServerPort != 0 {\n\t\treturn httpsServerPort\n\t}\n\treturn httpServerPort\n}" ]
[ "0.6986965", "0.678367", "0.6747273", "0.6683555", "0.6668388", "0.6659009", "0.6632165", "0.6618945", "0.6566605", "0.6560838", "0.65348476", "0.6527751", "0.65117294", "0.64696467", "0.6399872", "0.6388386", "0.637514", "0.6300814", "0.629962", "0.6287023", "0.6210371", "0.6199835", "0.61851114", "0.618277", "0.61663884", "0.6145725", "0.61217165", "0.61134434", "0.60921663", "0.60921663", "0.6018444", "0.5986926", "0.5973704", "0.59631217", "0.5959872", "0.59541327", "0.59541327", "0.58764803", "0.5778224", "0.57337826", "0.57144624", "0.5665301", "0.56595653", "0.56595653", "0.5659495", "0.56422794", "0.56366503", "0.561669", "0.56051624", "0.5597766", "0.55804384", "0.5575248", "0.5573526", "0.5569658", "0.5565044", "0.5560097", "0.55543673", "0.55429924", "0.55429924", "0.5516912", "0.5511762", "0.54873747", "0.5479968", "0.5466966", "0.54445666", "0.5440667", "0.5434703", "0.5411915", "0.5399091", "0.539254", "0.53852946", "0.53751016", "0.5374812", "0.53667885", "0.534122", "0.5333561", "0.5330458", "0.53288764", "0.5277172", "0.52717775", "0.52590764", "0.52555907", "0.52480054", "0.52452815", "0.52445674", "0.52335495", "0.5189728", "0.51818126", "0.51812357", "0.5179089", "0.51718634", "0.5166417", "0.51640517", "0.5149497", "0.5137967", "0.5132834", "0.51309246", "0.5125889", "0.5113208", "0.51090527" ]
0.75623345
0
XXX_OneofWrappers is for the internal use of the proto package.
func (*OutlierDetectionEvent) XXX_OneofWrappers() []interface{} { return []interface{}{ (*OutlierDetectionEvent_EjectSuccessRateEvent)(nil), (*OutlierDetectionEvent_EjectConsecutiveEvent)(nil), (*OutlierDetectionEvent_EjectFailurePercentageEvent)(nil), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (*DRB) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_NotUsed)(nil),\n\t\t(*DRB_Rohc)(nil),\n\t\t(*DRB_UplinkOnlyROHC)(nil),\n\t}\n}", "func (*Interface) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Interface_Sub)(nil),\n\t\t(*Interface_Memif)(nil),\n\t\t(*Interface_Afpacket)(nil),\n\t\t(*Interface_Tap)(nil),\n\t\t(*Interface_Vxlan)(nil),\n\t\t(*Interface_Ipsec)(nil),\n\t\t(*Interface_VmxNet3)(nil),\n\t\t(*Interface_Bond)(nil),\n\t\t(*Interface_Gre)(nil),\n\t\t(*Interface_Gtpu)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*TwoOneofs) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TwoOneofs_Field1)(nil),\n\t\t(*TwoOneofs_Field2)(nil),\n\t\t(*TwoOneofs_Field3)(nil),\n\t\t(*TwoOneofs_Field34)(nil),\n\t\t(*TwoOneofs_Field35)(nil),\n\t\t(*TwoOneofs_SubMessage2)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*Layer7) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer7_Dns)(nil),\n\t\t(*Layer7_Http)(nil),\n\t\t(*Layer7_Kafka)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_NewRoundStep)(nil),\n\t\t(*Message_NewValidBlock)(nil),\n\t\t(*Message_Proposal)(nil),\n\t\t(*Message_ProposalPol)(nil),\n\t\t(*Message_BlockPart)(nil),\n\t\t(*Message_Vote)(nil),\n\t\t(*Message_HasVote)(nil),\n\t\t(*Message_VoteSetMaj23)(nil),\n\t\t(*Message_VoteSetBits)(nil),\n\t}\n}", "func (*GroupMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GroupMod_L2Iface)(nil),\n\t\t(*GroupMod_L3Unicast)(nil),\n\t\t(*GroupMod_MplsIface)(nil),\n\t\t(*GroupMod_MplsLabel)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Layer4) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Layer4_TCP)(nil),\n\t\t(*Layer4_UDP)(nil),\n\t\t(*Layer4_ICMPv4)(nil),\n\t\t(*Layer4_ICMPv6)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Init)(nil),\n\t\t(*Message_File)(nil),\n\t\t(*Message_Resize)(nil),\n\t\t(*Message_Signal)(nil),\n\t}\n}", "func (*Example) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Example_A)(nil),\n\t\t(*Example_BJk)(nil),\n\t}\n}", "func (*ExampleMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ExampleMsg_SomeString)(nil),\n\t\t(*ExampleMsg_SomeNumber)(nil),\n\t\t(*ExampleMsg_SomeBool)(nil),\n\t}\n}", "func (*WALMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*WALMessage_EventDataRoundState)(nil),\n\t\t(*WALMessage_MsgInfo)(nil),\n\t\t(*WALMessage_TimeoutInfo)(nil),\n\t\t(*WALMessage_EndHeight)(nil),\n\t}\n}", "func (*Modulation) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Modulation_Lora)(nil),\n\t\t(*Modulation_Fsk)(nil),\n\t\t(*Modulation_LrFhss)(nil),\n\t}\n}", "func (*TestVersion2) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion2_E)(nil),\n\t\t(*TestVersion2_F)(nil),\n\t}\n}", "func (*TestVersion1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion1_E)(nil),\n\t\t(*TestVersion1_F)(nil),\n\t}\n}", "func (*CodebookType_Type1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookType_Type1_TypeI_SinglePanel)(nil),\n\t\t(*CodebookType_Type1_TypeI_MultiPanell)(nil),\n\t}\n}", "func (*DRB_ToAddMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DRB_ToAddMod_Eps_BearerIdentity)(nil),\n\t\t(*DRB_ToAddMod_Sdap_Config)(nil),\n\t}\n}", "func (*TestVersion3) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersion3_E)(nil),\n\t\t(*TestVersion3_F)(nil),\n\t}\n}", "func (*Bitmaps) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bitmaps_OneSlot)(nil),\n\t\t(*Bitmaps_TwoSlots)(nil),\n\t\t(*Bitmaps_N2)(nil),\n\t\t(*Bitmaps_N4)(nil),\n\t\t(*Bitmaps_N5)(nil),\n\t\t(*Bitmaps_N8)(nil),\n\t\t(*Bitmaps_N10)(nil),\n\t\t(*Bitmaps_N20)(nil),\n\t\t(*Bitmaps_N40)(nil),\n\t}\n}", "func (*Bit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Bit_DecimalValue)(nil),\n\t\t(*Bit_LongValue)(nil),\n\t}\n}", "func (*SeldonMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SeldonMessage_Data)(nil),\n\t\t(*SeldonMessage_BinData)(nil),\n\t\t(*SeldonMessage_StrData)(nil),\n\t\t(*SeldonMessage_JsonData)(nil),\n\t\t(*SeldonMessage_CustomData)(nil),\n\t}\n}", "func (*TestVersionFD1) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestVersionFD1_E)(nil),\n\t\t(*TestVersionFD1_F)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Pubkey)(nil),\n\t\t(*Message_EncK)(nil),\n\t\t(*Message_Mta)(nil),\n\t\t(*Message_Delta)(nil),\n\t\t(*Message_ProofAi)(nil),\n\t\t(*Message_CommitViAi)(nil),\n\t\t(*Message_DecommitViAi)(nil),\n\t\t(*Message_CommitUiTi)(nil),\n\t\t(*Message_DecommitUiTi)(nil),\n\t\t(*Message_Si)(nil),\n\t}\n}", "func (*TestUnit) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestUnit_GceTestCfg)(nil),\n\t\t(*TestUnit_HwTestCfg)(nil),\n\t\t(*TestUnit_MoblabVmTestCfg)(nil),\n\t\t(*TestUnit_TastVmTestCfg)(nil),\n\t\t(*TestUnit_VmTestCfg)(nil),\n\t}\n}", "func (*Tag) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tag_DecimalValue)(nil),\n\t\t(*Tag_LongValue)(nil),\n\t\t(*Tag_StringValue)(nil),\n\t}\n}", "func (*Record) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Record_Local_)(nil),\n\t\t(*Record_Ledger_)(nil),\n\t\t(*Record_Multi_)(nil),\n\t\t(*Record_Offline_)(nil),\n\t}\n}", "func (*GeneratedObject) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GeneratedObject_DestinationRule)(nil),\n\t\t(*GeneratedObject_EnvoyFilter)(nil),\n\t\t(*GeneratedObject_ServiceEntry)(nil),\n\t\t(*GeneratedObject_VirtualService)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_Deal)(nil),\n\t\t(*Packet_Response)(nil),\n\t\t(*Packet_Justification)(nil),\n\t}\n}", "func (*Response) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Response_ImageVersion)(nil),\n\t\t(*Response_ErrorDescription)(nil),\n\t}\n}", "func (*FlowMod) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FlowMod_Vlan)(nil),\n\t\t(*FlowMod_TermMac)(nil),\n\t\t(*FlowMod_Mpls1)(nil),\n\t\t(*FlowMod_Unicast)(nil),\n\t\t(*FlowMod_Bridging)(nil),\n\t\t(*FlowMod_Acl)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*MFADevice) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MFADevice_Totp)(nil),\n\t\t(*MFADevice_U2F)(nil),\n\t}\n}", "func (*P4Data) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*P4Data_Bitstring)(nil),\n\t\t(*P4Data_Varbit)(nil),\n\t\t(*P4Data_Bool)(nil),\n\t\t(*P4Data_Tuple)(nil),\n\t\t(*P4Data_Struct)(nil),\n\t\t(*P4Data_Header)(nil),\n\t\t(*P4Data_HeaderUnion)(nil),\n\t\t(*P4Data_HeaderStack)(nil),\n\t\t(*P4Data_HeaderUnionStack)(nil),\n\t\t(*P4Data_Enum)(nil),\n\t\t(*P4Data_Error)(nil),\n\t\t(*P4Data_EnumValue)(nil),\n\t}\n}", "func (*SSB_ConfigMobility) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SSB_ConfigMobility_ReleaseSsb_ToMeasure)(nil),\n\t\t(*SSB_ConfigMobility_SetupSsb_ToMeasure)(nil),\n\t}\n}", "func (*SpCellConfig) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*SpCellConfig_ReleaseRlf_TimersAndConstants)(nil),\n\t\t(*SpCellConfig_SetupRlf_TimersAndConstants)(nil),\n\t}\n}", "func (*ServerMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerMessage_State)(nil),\n\t\t(*ServerMessage_Runtime)(nil),\n\t\t(*ServerMessage_Event)(nil),\n\t\t(*ServerMessage_Response)(nil),\n\t\t(*ServerMessage_Notice)(nil),\n\t}\n}", "func (*ParaP2PSubMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ParaP2PSubMsg_CommitTx)(nil),\n\t\t(*ParaP2PSubMsg_SyncMsg)(nil),\n\t}\n}", "func (*ServerAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServerAuctionMessage_Challenge)(nil),\n\t\t(*ServerAuctionMessage_Success)(nil),\n\t\t(*ServerAuctionMessage_Error)(nil),\n\t\t(*ServerAuctionMessage_Prepare)(nil),\n\t\t(*ServerAuctionMessage_Sign)(nil),\n\t\t(*ServerAuctionMessage_Finalize)(nil),\n\t\t(*ServerAuctionMessage_Account)(nil),\n\t}\n}", "func (*Body) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Body_AsBytes)(nil),\n\t\t(*Body_AsString)(nil),\n\t}\n}", "func (*TagField) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TagField_DoubleValue)(nil),\n\t\t(*TagField_StringValue)(nil),\n\t\t(*TagField_BoolValue)(nil),\n\t\t(*TagField_TimestampValue)(nil),\n\t\t(*TagField_EnumValue_)(nil),\n\t}\n}", "func (*DatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*DatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*GatewayMsg) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GatewayMsg_Demand)(nil),\n\t\t(*GatewayMsg_Supply)(nil),\n\t\t(*GatewayMsg_Target)(nil),\n\t\t(*GatewayMsg_Mbus)(nil),\n\t\t(*GatewayMsg_MbusMsg)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Chunk)(nil),\n\t\t(*Message_Status)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*BlobDiff) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BlobDiff_Dataset)(nil),\n\t\t(*BlobDiff_Environment)(nil),\n\t\t(*BlobDiff_Code)(nil),\n\t\t(*BlobDiff_Config)(nil),\n\t}\n}", "func (*DataType) XXX_OneofWrappers() []interface{} {\r\n\treturn []interface{}{\r\n\t\t(*DataType_ListElementType)(nil),\r\n\t\t(*DataType_StructType)(nil),\r\n\t\t(*DataType_TimeFormat)(nil),\r\n\t}\r\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Prepare)(nil),\n\t\t(*Message_Promise)(nil),\n\t\t(*Message_Accept)(nil),\n\t\t(*Message_Accepted)(nil),\n\t\t(*Message_Alert)(nil),\n\t}\n}", "func (*BWP_DownlinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_DownlinkCommon_ReleasePdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdcch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_ReleasePdsch_ConfigCommon)(nil),\n\t\t(*BWP_DownlinkCommon_SetupPdsch_ConfigCommon)(nil),\n\t}\n}", "func (*Test) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Test_Get)(nil),\n\t\t(*Test_Create)(nil),\n\t\t(*Test_Set)(nil),\n\t\t(*Test_Update)(nil),\n\t\t(*Test_UpdatePaths)(nil),\n\t\t(*Test_Delete)(nil),\n\t\t(*Test_Query)(nil),\n\t\t(*Test_Listen)(nil),\n\t}\n}", "func (*DownlinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DownlinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_FskModulationInfo)(nil),\n\t\t(*DownlinkTXInfo_ImmediatelyTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_DelayTimingInfo)(nil),\n\t\t(*DownlinkTXInfo_GpsEpochTimingInfo)(nil),\n\t}\n}", "func (*RpcMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RpcMessage_RequestHeader)(nil),\n\t\t(*RpcMessage_ResponseHeader)(nil),\n\t}\n}", "func (*Domain_Attribute) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Domain_Attribute_BoolValue)(nil),\n\t\t(*Domain_Attribute_IntValue)(nil),\n\t}\n}", "func (*CellStatusResp) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusResp_CellStatus)(nil),\n\t\t(*CellStatusResp_ErrorMsg)(nil),\n\t}\n}", "func (*ClientAuctionMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ClientAuctionMessage_Commit)(nil),\n\t\t(*ClientAuctionMessage_Subscribe)(nil),\n\t\t(*ClientAuctionMessage_Accept)(nil),\n\t\t(*ClientAuctionMessage_Reject)(nil),\n\t\t(*ClientAuctionMessage_Sign)(nil),\n\t\t(*ClientAuctionMessage_Recover)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*GrpcService) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*GrpcService_EnvoyGrpc_)(nil),\n\t\t(*GrpcService_GoogleGrpc_)(nil),\n\t}\n}", "func (*Replay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Replay_Http)(nil),\n\t\t(*Replay_Sqs)(nil),\n\t\t(*Replay_Amqp)(nil),\n\t\t(*Replay_Kafka)(nil),\n\t}\n}", "func (*ReportConfigInterRAT) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReportConfigInterRAT_Periodical)(nil),\n\t\t(*ReportConfigInterRAT_EventTriggered)(nil),\n\t\t(*ReportConfigInterRAT_ReportCGI)(nil),\n\t}\n}", "func (*Class) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Class_PerInstance)(nil),\n\t\t(*Class_Lumpsum)(nil),\n\t}\n}", "func (*OneOfMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OneOfMessage_BinaryValue)(nil),\n\t\t(*OneOfMessage_StringValue)(nil),\n\t\t(*OneOfMessage_BooleanValue)(nil),\n\t\t(*OneOfMessage_IntValue)(nil),\n\t\t(*OneOfMessage_Int64Value)(nil),\n\t\t(*OneOfMessage_DoubleValue)(nil),\n\t\t(*OneOfMessage_FloatValue)(nil),\n\t\t(*OneOfMessage_MsgValue)(nil),\n\t}\n}", "func (*ServiceSpec) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ServiceSpec_Replicated)(nil),\n\t\t(*ServiceSpec_Global)(nil),\n\t\t(*ServiceSpec_ReplicatedJob)(nil),\n\t\t(*ServiceSpec_GlobalJob)(nil),\n\t}\n}", "func (*ReceiveReply) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ReceiveReply_Record_)(nil),\n\t\t(*ReceiveReply_LiiklusEventRecord_)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_PexRequest)(nil),\n\t\t(*Message_PexAddrs)(nil),\n\t}\n}", "func (*ChangeResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*ChangeResponse_Ok)(nil),\n\t\t(*ChangeResponse_Error)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_ExecStarted)(nil),\n\t\t(*Message_ExecCompleted)(nil),\n\t\t(*Message_ExecOutput)(nil),\n\t\t(*Message_LogEntry)(nil),\n\t\t(*Message_Error)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*HealthCheck_Payload) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*HealthCheck_Payload_Text)(nil),\n\t\t(*HealthCheck_Payload_Binary)(nil),\n\t}\n}", "func (*RequestCreateGame) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*RequestCreateGame_LocalMap)(nil),\n\t\t(*RequestCreateGame_BattlenetMapName)(nil),\n\t}\n}", "func (*CellStatusReq) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CellStatusReq_IsPlayer)(nil),\n\t\t(*CellStatusReq_CellStatus)(nil),\n\t}\n}", "func (*Message) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Message_Request)(nil),\n\t\t(*Message_Response)(nil),\n\t}\n}", "func (*CreateDatasetVersion) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CreateDatasetVersion_RawDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_PathDatasetVersionInfo)(nil),\n\t\t(*CreateDatasetVersion_QueryDatasetVersionInfo)(nil),\n\t}\n}", "func (*InputMessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InputMessage_Init)(nil),\n\t\t(*InputMessage_Data)(nil),\n\t}\n}", "func (*UplinkTXInfo) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*UplinkTXInfo_LoraModulationInfo)(nil),\n\t\t(*UplinkTXInfo_FskModulationInfo)(nil),\n\t\t(*UplinkTXInfo_LrFhssModulationInfo)(nil),\n\t}\n}", "func (*APool) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*APool_DisableHealthCheck)(nil),\n\t\t(*APool_HealthCheck)(nil),\n\t}\n}", "func (*BWP_UplinkCommon) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*BWP_UplinkCommon_ReleaseRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupRach_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPusch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_ReleasePucch_ConfigCommon)(nil),\n\t\t(*BWP_UplinkCommon_SetupPucch_ConfigCommon)(nil),\n\t}\n}", "func (*M) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_OneofInt32)(nil),\n\t\t(*M_OneofInt64)(nil),\n\t}\n}", "func (*LoadParams) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*LoadParams_ClosedLoop)(nil),\n\t\t(*LoadParams_Poisson)(nil),\n\t}\n}", "func (*TestnetPacketData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*TestnetPacketData_NoData)(nil),\n\t\t(*TestnetPacketData_FooPacket)(nil),\n\t}\n}", "func (*M_Submessage) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*M_Submessage_SubmessageOneofInt32)(nil),\n\t\t(*M_Submessage_SubmessageOneofInt64)(nil),\n\t}\n}", "func (*CodebookSubType_MultiPanel) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*CodebookSubType_MultiPanel_TwoTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoEightOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourFourOne_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_TwoFourTwo_TypeI_MultiPanel_Restriction)(nil),\n\t\t(*CodebookSubType_MultiPanel_FourTwoTwo_TypeI_MultiPanel_Restriction)(nil),\n\t}\n}", "func (*Packet) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Packet_PacketPing)(nil),\n\t\t(*Packet_PacketPong)(nil),\n\t\t(*Packet_PacketMsg)(nil),\n\t}\n}", "func (*MetricsData) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*MetricsData_BoolValue)(nil),\n\t\t(*MetricsData_StringValue)(nil),\n\t\t(*MetricsData_Int64Value)(nil),\n\t\t(*MetricsData_DoubleValue)(nil),\n\t\t(*MetricsData_DistributionValue)(nil),\n\t}\n}", "func (*FieldType) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*FieldType_PrimitiveType_)(nil),\n\t\t(*FieldType_EnumType_)(nil),\n\t}\n}", "func (*InstructionResponse) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*InstructionResponse_Register)(nil),\n\t\t(*InstructionResponse_ProcessBundle)(nil),\n\t\t(*InstructionResponse_ProcessBundleProgress)(nil),\n\t\t(*InstructionResponse_ProcessBundleSplit)(nil),\n\t\t(*InstructionResponse_FinalizeBundle)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*OpenStatusUpdate) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*OpenStatusUpdate_ChanPending)(nil),\n\t\t(*OpenStatusUpdate_ChanOpen)(nil),\n\t\t(*OpenStatusUpdate_PsbtFund)(nil),\n\t}\n}", "func (*Tracing) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*Tracing_Zipkin_)(nil),\n\t\t(*Tracing_Lightstep_)(nil),\n\t\t(*Tracing_Datadog_)(nil),\n\t\t(*Tracing_Stackdriver_)(nil),\n\t}\n}", "func (*DynamicReplay) XXX_OneofWrappers() []interface{} {\n\treturn []interface{}{\n\t\t(*DynamicReplay_AuthRequest)(nil),\n\t\t(*DynamicReplay_AuthResponse)(nil),\n\t\t(*DynamicReplay_OutboundMessage)(nil),\n\t\t(*DynamicReplay_ReplayMessage)(nil),\n\t}\n}" ]
[ "0.88214165", "0.88021713", "0.8743008", "0.8743008", "0.8743008", "0.8743008", "0.8717406", "0.8717406", "0.8714167", "0.8713824", "0.8700613", "0.8700613", "0.87001115", "0.86874217", "0.86787724", "0.8675455", "0.8672273", "0.86698306", "0.8665908", "0.86512536", "0.8646821", "0.86386365", "0.86342514", "0.86329716", "0.863169", "0.8628287", "0.86180717", "0.8614283", "0.86121434", "0.86077875", "0.86043906", "0.8599478", "0.8591721", "0.85891396", "0.8585715", "0.8585715", "0.8585715", "0.85808307", "0.85788", "0.8578621", "0.85712314", "0.85646266", "0.85642725", "0.8562125", "0.85597765", "0.85593873", "0.8556165", "0.855444", "0.85466284", "0.85466284", "0.85466284", "0.8544794", "0.8544425", "0.85434425", "0.8543189", "0.8542546", "0.8541232", "0.85399264", "0.85389084", "0.85375434", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.8535147", "0.85265565", "0.85229486", "0.85182756", "0.85167336", "0.8515576", "0.8515508", "0.85137737", "0.85115725", "0.85110307", "0.85106057", "0.85106057", "0.85106057", "0.85106057", "0.8505778", "0.8503764", "0.85026187", "0.8500881", "0.8497405", "0.84928215", "0.84917736", "0.84903145", "0.84880537", "0.84871894", "0.84863424", "0.8485251", "0.8484042", "0.8483205", "0.8482806", "0.84800684", "0.8479984", "0.847473", "0.847473", "0.847473", "0.8472139", "0.847054" ]
0.0
-1
Serialize returns the serialized byte stream of Store
func (in *Store) Serialize() ([]byte, error) { return proto.Marshal(in.ToProto()) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Store) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"defaultLanguageTag\", m.GetDefaultLanguageTag())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLanguageTags() != nil {\n err = writer.WriteCollectionOfStringValues(\"languageTags\", m.GetLanguageTags())\n if err != nil {\n return err\n }\n }\n if m.GetSets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSets())\n err = writer.WriteCollectionOfObjectValues(\"sets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (s *StoredChannel) serialize() ([]byte, error) {\n\tbuffer := &bytes.Buffer{}\n\tencoder := gob.NewEncoder(buffer)\n\terr := encoder.Encode(s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (r *SbProxy) Serialize() rotator.Object {\n\tr.RLock()\n\tdefer r.RUnlock()\n\treturn r.serialize()\n}", "func (s *State) Serialize() []byte {\n\treturn s.serializer.Serialize(s.structure())\n}", "func (ds *DepositToStake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(ds.Proto()))\n}", "func (m *ExactMatchDataStore) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.ExactMatchDataStoreBase.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetSessions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSessions()))\n for i, v := range m.GetSessions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sessions\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (defaultStorage) Serialize() (string, error) {\n\tpanic(noConfigStorage)\n}", "func (m *AndroidManagedStoreApp) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.MobileApp.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"appIdentifier\", m.GetAppIdentifier())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"appStoreUrl\", m.GetAppStoreUrl())\n if err != nil {\n return err\n }\n }\n if m.GetAppTracks() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAppTracks()))\n for i, v := range m.GetAppTracks() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"appTracks\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isPrivate\", m.GetIsPrivate())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"isSystemApp\", m.GetIsSystemApp())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"packageId\", m.GetPackageId())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"supportsOemConfig\", m.GetSupportsOemConfig())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"totalLicenseCount\", m.GetTotalLicenseCount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"usedLicenseCount\", m.GetUsedLicenseCount())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (rs *Restake) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(rs.Proto()))\n}", "func (s *Store) String() string {\n\ts.access.RLock()\n\tdefer s.access.RUnlock()\n\n\tvar b bytes.Buffer\n\tb.WriteString(\"Store(\")\n\tms := fmt.Sprint(s.data)\n\tms = strings.TrimLeft(ms, \"map[\")\n\tms = strings.TrimRight(ms, \"]\")\n\tb.WriteString(ms)\n\tb.WriteString(\")\")\n\treturn b.String()\n}", "func (p *PublicKey) Serialize() []byte {\n\treturn p.pk().SerializeCompressed()\n}", "func (m *saMap) serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func Serialize(data interface{}, typ string, registry Registry) ([]byte, error) {\n\tserde, err := registry.GetSerde(typ)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn serde.Serialize(data)\n}", "func (k *KeyStore) serialize(w io.Writer) error {\n\tenc := json.NewEncoder(w)\n\treturn enc.Encode(k.Values)\n}", "func (m *RegistryKeyState) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n if m.GetHive() != nil {\n cast := (*m.GetHive()).String()\n err := writer.WriteStringValue(\"hive\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"key\", m.GetKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"@odata.type\", m.GetOdataType())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"oldKey\", m.GetOldKey())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"oldValueData\", m.GetOldValueData())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"oldValueName\", m.GetOldValueName())\n if err != nil {\n return err\n }\n }\n if m.GetOperation() != nil {\n cast := (*m.GetOperation()).String()\n err := writer.WriteStringValue(\"operation\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteInt32Value(\"processId\", m.GetProcessId())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"valueData\", m.GetValueData())\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteStringValue(\"valueName\", m.GetValueName())\n if err != nil {\n return err\n }\n }\n if m.GetValueType() != nil {\n cast := (*m.GetValueType()).String()\n err := writer.WriteStringValue(\"valueType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err := writer.WriteAdditionalData(m.GetAdditionalData())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (store_m StoreModule) ToJSON() []byte {\n\tjsonStr, _ := json.Marshal(store_m)\n\treturn jsonStr\n}", "func Serialize(o interface{}) ([]byte, error) {\n\tautil.TODO(\"CBOR-serialization\")\n\treturn nil, nil\n}", "func (m *SAMap) Serialize() ([]byte, error) {\n\tm.RLock()\n\tdefer m.RUnlock()\n\treturn json.Marshal(m.ma)\n}", "func (ws *WalletStore) Save() {\n\tvar buffer bytes.Buffer\n\tgob.Register(elliptic.P256())\n\tencoder := gob.NewEncoder(&buffer)\n\terr := encoder.Encode(ws.Wallets)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfile := ws.Config.GetWalletStoreFile(ws.NodeID)\n\terr = ioutil.WriteFile(file, buffer.Bytes(), 0644)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (e *Entity) Serialize(w io.Writer) error {\n\terr := e.PrimaryKey.Serialize(w)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, ident := range e.Identities {\n\t\terr = ident.UserId.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = ident.SelfSignature.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, sig := range ident.Signatures {\n\t\t\terr = sig.Serialize(w)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\tfor _, subkey := range e.Subkeys {\n\t\terr = subkey.PublicKey.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\terr = subkey.Sig.Serialize(w)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (b *block) Serialize() []byte {\n\tvar res bytes.Buffer\n\tencoder := gob.NewEncoder(&res) // address\n\terr := encoder.Encode(b) // here b is the source\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn res.Bytes()\n}", "func (sh *ServerPropertiesHandle) Serialized() string {\n\tsh.Serialize(sh.serverProperties)\n\treturn sh.String()\n}", "func (g *Generic) Serialize() ([]byte, error) {\n\tlog.Println(\"DEPRECATED: MarshalBinary instead\")\n\treturn g.MarshalBinary()\n}", "func (record *SessionRecord) Serialize() ([]byte, error) {\n\trs := &protobuf.RecordStructure{}\n\trs.CurrentSession = record.sessionState.SS\n\tfor _, s := range record.PreviousStates {\n\t\trs.PreviousSessions = append(rs.PreviousSessions, s.SS)\n\t}\n\tb, err := proto.Marshal(rs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (this *Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(this)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (bk *Bookkeeper) Serialize(w io.Writer) error {\n\tpk := keypair.SerializePublicKey(bk.PubKey)\n\tvar bkvb = &serialize.VarBytes{\n\t\tLen: uint64(len(pk)),\n\t\tBytes: pk,\n\t}\n\tif err := bkvb.Serialize(w); err != nil {\n\t\treturn err\n\t}\n\tbinary.Write(w, binary.LittleEndian, bk.Action)\n\tvar certvb = &serialize.VarBytes{\n\t\tLen: uint64(len(bk.Cert)),\n\t\tBytes: bk.Cert,\n\t}\n\tif err := certvb.Serialize(w); err != nil {\n\t\treturn err\n\t}\n\tissuer := keypair.SerializePublicKey(bk.Issuer)\n\tvar issuservb = &serialize.VarBytes{\n\t\tLen: uint64(len(issuer)),\n\t\tBytes: issuer,\n\t}\n\treturn issuservb.Serialize(w)\n}", "func (f *OpenStreamRequest) Serialize(buffer []byte) []byte {\n\tbuffer = f.Stream.Serialize(buffer)\n\treturn buffer\n}", "func (s TrustStore) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (self *ResTransaction)Serialize()[]byte{\n data, err := json.Marshal(self)\n if err != nil {\n fmt.Println(err)\n }\n return data\n}", "func (m *Workbook) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"application\", m.GetApplication())\n if err != nil {\n return err\n }\n }\n if m.GetComments() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetComments())\n err = writer.WriteCollectionOfObjectValues(\"comments\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"functions\", m.GetFunctions())\n if err != nil {\n return err\n }\n }\n if m.GetNames() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetNames())\n err = writer.WriteCollectionOfObjectValues(\"names\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetTables() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetTables())\n err = writer.WriteCollectionOfObjectValues(\"tables\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetWorksheets() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetWorksheets())\n err = writer.WriteCollectionOfObjectValues(\"worksheets\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (ts *TagSet) Serialization() []byte {\n\treturn ts.serialization\n}", "func (sigInfo *TxSignature) Serialize() []byte {\n\tecSig := sigInfo.Signature.Serialize()\n\tecSig = append(ecSig, byte(int(sigInfo.HashType)))\n\treturn ecSig\n}", "func (b Bytes) Serialize() ([]byte, error) {\n\treturn b, nil\n}", "func (s *Session) Serialize() string {\n\tvar str string\n\n\tfor _, tv := range []*Table{s.Filter, s.Nat, s.Mangle} {\n\t\tstr += fmt.Sprintf(\"*%s\\n\", tv.name)\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tstr += fmt.Sprintf(\":%s %s [0:0]\\n\", cv.name, cv.policy)\n\t\t\t}\n\t\t}\n\t\tfor _, cv := range tv.Chains {\n\t\t\tif cv != nil {\n\t\t\t\tif cv.rules != nil {\n\t\t\t\t\tfor _, rv := range cv.rules {\n\t\t\t\t\t\tstr += rv + \"\\n\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tstr += fmt.Sprintf(\"COMMIT\\n\")\n\t}\n\n\treturn str\n}", "func (msg *Block) Serialize(w io.Writer) (e error) {\n\t// At the current time, there is no difference between the wire encoding at\n\t// protocol version 0 and the stable long-term storage format. As a result, make\n\t// use of BtcEncode. Passing WitnessEncoding as the encoding type here indicates\n\t// that each of the transactions should be serialized using the witness\n\t// serialization structure defined in BIP0141.\n\treturn msg.BtcEncode(w, 0, BaseEncoding)\n}", "func (m *MicrosoftStoreForBusinessApp) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.MobileApp.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetContainedApps() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetContainedApps()))\n for i, v := range m.GetContainedApps() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"containedApps\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetLicenseType() != nil {\n cast := (*m.GetLicenseType()).String()\n err = writer.WriteStringValue(\"licenseType\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"licensingType\", m.GetLicensingType())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"packageIdentityName\", m.GetPackageIdentityName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"productKey\", m.GetProductKey())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"totalLicenseCount\", m.GetTotalLicenseCount())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteInt32Value(\"usedLicenseCount\", m.GetUsedLicenseCount())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (l *Layer) Serialize() ([]byte, error) {\n\treturn json.Marshal(l)\n}", "func (s CreateVariantStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *Store) Save() error {\n\tbk, err := os.OpenFile(filepath.Join(s.rwDirPath, storeBkName), os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\tdefer bk.Close()\n\n\tdst, err := os.OpenFile(filepath.Join(s.rwDirPath, storeName), os.O_RDWR|os.O_CREATE, 0666)\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\tdefer dst.Close()\n\n\t// backing up current store\n\t_, err = io.Copy(bk, dst)\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\n\tenc := gob.NewEncoder(dst)\n\tbook := s.Clone()\n\terr = enc.Encode(book)\n\tif err != nil {\n\t\treturn errors.Wrap(err, err.Error())\n\t}\n\treturn nil\n}", "func (pb *PutBlock) Serialize() []byte {\n\treturn byteutil.Must(proto.Marshal(pb.Proto()))\n}", "func Serialize(input interface{}) (msg []byte, err error) {\n\tbuffer, err := json.Marshal(input)\n\treturn buffer, err\n\n\t// TODO: Do we really need wire here?\n\t/*\n\t\tvar count int\n\n\t\tbuffer := new(bytes.Buffer)\n\n\t\twire.WriteBinary(input, buffer, &count, &err)\n\n\t\treturn buffer.Bytes(), err\n\t*/\n}", "func (s *Store) WriteTo(w io.Writer) (int64, error) {\n\t// Write current file version.\n\tuint32Bytes := make([]byte, 4)\n\tbinary.LittleEndian.PutUint32(uint32Bytes, versCurrent)\n\tn, err := w.Write(uint32Bytes)\n\tn64 := int64(n)\n\tif err != nil {\n\t\treturn n64, err\n\t}\n\n\t// Write all backing transactions.\n\tfor btx, tx := range s.txs {\n\t\t// Write backing tx header.\n\t\tn, err = w.Write([]byte{backingTxHeader})\n\t\tn64 += int64(n)\n\t\tif err != nil {\n\t\t\treturn n64, err\n\t\t}\n\n\t\t// Write block height.\n\t\tbinary.LittleEndian.PutUint32(uint32Bytes, uint32(btx.height))\n\t\tn, err = w.Write(uint32Bytes)\n\t\tn64 += int64(n)\n\t\tif err != nil {\n\t\t\treturn n64, err\n\t\t}\n\n\t\t// Write serialized transaction\n\t\ttxN, err := (*msgTx)(tx.MsgTx()).writeTo(w)\n\t\tn64 += txN\n\t\tif err != nil {\n\t\t\treturn n64, err\n\t\t}\n\t}\n\n\t// Write each record. The byte header is dependant on the\n\t// underlying type.\n\tfor e := s.sorted.Front(); e != nil; e = e.Next() {\n\t\tv := e.Value.(txRecord)\n\t\tswitch v.(type) {\n\t\tcase *recvTxOut:\n\t\t\tn, err = w.Write([]byte{recvTxOutHeader})\n\t\tcase *signedTx:\n\t\t\tn, err = w.Write([]byte{signedTxHeader})\n\t\t}\n\t\tn64 += int64(n)\n\t\tif err != nil {\n\t\t\treturn n64, err\n\t\t}\n\n\t\trecordN, err := v.writeTo(w)\n\t\tn64 += recordN\n\t\tif err != nil {\n\t\t\treturn n64, err\n\t\t}\n\t}\n\n\treturn n64, nil\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\ttmp := []string{}\n\ts(root, &tmp)\n\tthis.SerializeStr = strings.Join(tmp, \",\")\n\treturn this.SerializeStr\n}", "func (vertice *Vertice) SerializeToAllModelStore() {\n\n\tAllModelStore.Vertices = append(AllModelStore.Vertices, vertice)\n\n}", "func (prkg *KeyIterator) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\tif err := gob.NewEncoder(buf).Encode(prkg); nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (in *Store) ToProto() *iotextypes.BlockStore {\n\treceipts := []*iotextypes.Receipt{}\n\tfor _, r := range in.Receipts {\n\t\treceipts = append(receipts, r.ConvertToReceiptPb())\n\t}\n\treturn &iotextypes.BlockStore{\n\t\tBlock: in.Block.ConvertToBlockPb(),\n\t\tReceipts: receipts,\n\t}\n}", "func (s CreateSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\tthis.s(root)\n\treturn \"[\" + strings.Join(this.data, \",\") + \"]\"\n}", "func (bm *BlockMeta) Serialize() ([]byte, error) {\n\tpb, err := bm.Proto()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn proto.Marshal(pb)\n}", "func (s GetVariantStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (b *Block) Serialize() []byte {\n\tvar res bytes.Buffer\n\tencoder := gob.NewEncoder(&res)\n\n\terr := encoder.Encode(b)\n\n\tHandle(err)\n\n\treturn res.Bytes()\n}", "func (b *Block) Serialize() []byte {\n\tvar res bytes.Buffer\n\tencoder := gob.NewEncoder(&res)\n\n\terr := encoder.Encode(b)\n\n\tHandle(err)\n\n\treturn res.Bytes()\n}", "func (m *IdentityProviderBase) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (m *ExternalConnection) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"configuration\", m.GetConfiguration())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"description\", m.GetDescription())\n if err != nil {\n return err\n }\n }\n if m.GetGroups() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetGroups())\n err = writer.WriteCollectionOfObjectValues(\"groups\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"schema\", m.GetSchema())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (mu *MuHash) Serialize() *SerializedMuHash {\n\tvar out SerializedMuHash\n\tmu.serializeInner(&out)\n\treturn &out\n}", "func (h HMSketch) Serialize() ([]byte, error) {\n\tvar outbytes bytes.Buffer\n\tenc := gob.NewEncoder(&outbytes)\n\terr := enc.Encode(h)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn outbytes.Bytes(), nil\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\te := gob.NewEncoder(&encoded)\n\terr := e.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn encoded.Bytes()\n}", "func (m *MacOSSoftwareUpdateStateSummary) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteTimeValue(\"lastUpdatedDateTime\", m.GetLastUpdatedDateTime())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"productKey\", m.GetProductKey())\n if err != nil {\n return err\n }\n }\n if m.GetState() != nil {\n cast := (*m.GetState()).String()\n err = writer.WriteStringValue(\"state\", &cast)\n if err != nil {\n return err\n }\n }\n if m.GetUpdateCategory() != nil {\n cast := (*m.GetUpdateCategory()).String()\n err = writer.WriteStringValue(\"updateCategory\", &cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"updateVersion\", m.GetUpdateVersion())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (msg *MsgInv) Serialize(w io.Writer, pver uint32) error {\n\terr := writeCompactSize(w, pver, msg.InvCount())\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, inv := range msg.Inventory {\n\t\terr := inv.Serialize(w, pver)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s Store) Save(param ParameterSet) error {\n\tbytes, err := json.MarshalIndent(param, \"\", \" \")\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn s.backingStore.Save(ItemType, \"\", param.Name, bytes)\n}", "func (s CreateVariantStoreInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (txn *Transaction) Serialize() utils.Gob {\n\t// Encode the blockheader as a gob and return it\n\treturn utils.GobEncode(txn)\n}", "func (s CreateTrustStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s GetSequenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (block *Block) Serialize() []byte {\n\tvar buff bytes.Buffer\n\n\tencoder := gob.NewEncoder(&buff)\n\n\terr := encoder.Encode(block)\n\n\tHandle(err)\n\n\treturn buff.Bytes()\n}", "func (u *walletIdentity) Serialize() ([]byte, error) {\n\tserializedIdentity := &pb_msp.SerializedIdentity{\n\t\tMspid: u.mspID,\n\t\tIdBytes: u.enrollmentCertificate,\n\t}\n\tidentity, err := proto.Marshal(serializedIdentity)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"marshal serializedIdentity failed\")\n\t}\n\treturn identity, nil\n}", "func (r *RequestStore) String() string {\n\treturn fmt.Sprintf(\"id: %s, type: store, key: %s\"+\n\t\t\", data: %v, expire_time: %s\",\n\t\tr.ID, r.Key, r.Data, r.ExpireTime)\n}", "func (b *Block) Serialize() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\tencoder.Encode(b)\n\treturn result.Bytes()\n}", "func (b *Block) Serialize() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\n\tencoder.Encode(b)\n\n\treturn result.Bytes()\n}", "func (m *WorkbookOperation) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteObjectValue(\"error\", m.GetError())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"resourceLocation\", m.GetResourceLocation())\n if err != nil {\n return err\n }\n }\n if m.GetStatus() != nil {\n cast := (*m.GetStatus()).String()\n err = writer.WriteStringValue(\"status\", &cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (s *DataStore) Write(w io.Writer) error {\n\terr := json.NewEncoder(w).Encode(&s.model)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (p Registered) Serialize() common.JSON {\n\treturn common.JSON{\n\t\t\"ID\": p.ID,\n\t\t\"Date\": p.Date,\n\t\t\"Riders\": p.Riders,\n\t\t\"RidersID\": p.RidersID,\n\t\t\"Events\": p.Events,\n\t\t\"EventsID\": p.EventsID,\n\t\t\"StartNumber\": p.StartNumber,\n\t}\n}", "func (s GetVariantStoreInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (ths *TreeHashStack) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\tif err := gob.NewEncoder(buf).Encode(ths); nil != err {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (m *List) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.BaseItem.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetColumns() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetColumns())\n err = writer.WriteCollectionOfObjectValues(\"columns\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetContentTypes() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetContentTypes())\n err = writer.WriteCollectionOfObjectValues(\"contentTypes\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"displayName\", m.GetDisplayName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"drive\", m.GetDrive())\n if err != nil {\n return err\n }\n }\n if m.GetItems() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetItems())\n err = writer.WriteCollectionOfObjectValues(\"items\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"list\", m.GetList())\n if err != nil {\n return err\n }\n }\n if m.GetOperations() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetOperations())\n err = writer.WriteCollectionOfObjectValues(\"operations\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"sharepointIds\", m.GetSharepointIds())\n if err != nil {\n return err\n }\n }\n if m.GetSubscriptions() != nil {\n cast := i2ae4187f7daee263371cb1c977df639813ab50ffa529013b7437480d1ec0158f.CollectionCast[i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable](m.GetSubscriptions())\n err = writer.WriteCollectionOfObjectValues(\"subscriptions\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"system\", m.GetSystem())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (tx Transaction) Serialize() []byte {\n\tvar encoded bytes.Buffer\n\n\tenc := gob.NewEncoder(&encoded)\n\terr := enc.Encode(tx)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn encoded.Bytes()\n}", "func (m *ShareCommon) Serialize() ([]byte, error) {\n\tbuf := new(bytes.Buffer)\n\n\t// Version (uint8)\n\t{\n\t\tif err := write(buf, m.Version); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// TransferLockout (Timestamp)\n\t{\n\t\tif err := write(buf, m.TransferLockout); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Ticker (string)\n\t{\n\t\tif err := WriteFixedChar(buf, m.Ticker, 5); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// ISIN (string)\n\t{\n\t\tif err := WriteFixedChar(buf, m.ISIN, 12); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Description (string)\n\t{\n\t\tif err := WriteVarChar(buf, m.Description, 16); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (a *AddMixer) Serialize() ([]byte, error) {\n\treturn serializer.SerializeAny(a.In1, a.In2, a.Out)\n}", "func (b *Block) Serialize() []byte {\n\tvar res bytes.Buffer\n\tencoder := gob.NewEncoder(&res)\n\terr := encoder.Encode(b)\n\n\tif err != nil {\n\t\tlog.Println(\"cannot serialize \" + err.Error())\n\t\treturn nil\n\t}\n\n\treturn res.Bytes()\n}", "func (r *TxRecord) Serialize() (err error) {\n\tr.RawTx, err = json.Marshal(r.Tx)\n\treturn\n}", "func (s GetSequenceStoreInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *Store) String() string {\n\treturn redact.StringWithoutMarkers(s)\n}", "func (out *TransactionOutput) Serialize(bw *io.BinaryWriter) {\n\tbw.WriteLE(out.AssetId)\n\tbw.WriteLE(out.Value)\n\tbw.WriteLE(out.ScriptHash)\n}", "func Serialize(msgTx *wire.MsgTx) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\n\terr := msgTx.Serialize(&buffer)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot serialize transaction [%s]\", err)\n\t}\n\n\treturn buffer.Bytes(), nil\n}", "func (s CreateSequenceStoreInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *Store) GobEncode() ([]byte, error) {\n\ts.access.RLock()\n\tdefer s.access.RUnlock()\n\n\tbuf := new(bytes.Buffer)\n\n\tencoder := gob.NewEncoder(buf)\n\terr := encoder.Encode(storeVersion)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = encoder.Encode(s.data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn buf.Bytes(), nil\n}", "func (query *Query) Serialize() []byte {\n bytes := make([]byte, 32, 32)\n\n bytes[0] = query.action\n bytes[1] = query.empty\n binary.BigEndian.PutUint32(bytes[2:6], query.replyIp)\n binary.BigEndian.PutUint16(bytes[6:8], query.replyPort)\n binary.BigEndian.PutUint64(bytes[8:16], query.key)\n binary.BigEndian.PutUint64(bytes[16:24], query.value)\n binary.BigEndian.PutUint32(bytes[24:28], query.timeToLive)\n binary.BigEndian.PutUint32(bytes[28:32], query.requestId)\n\n return bytes\n}", "func Serialize(v interface{}) ([]byte, error) {\n\tbuf := bytes.NewBuffer(make([]byte, 0))\n\tif err := gob.NewEncoder(buf).Encode(v); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}", "func (m *VirtualEndpoint) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n if m.GetAuditEvents() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetAuditEvents()))\n for i, v := range m.GetAuditEvents() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"auditEvents\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetBulkActions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetBulkActions()))\n for i, v := range m.GetBulkActions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"bulkActions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetCloudPCs() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetCloudPCs()))\n for i, v := range m.GetCloudPCs() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"cloudPCs\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"crossCloudGovernmentOrganizationMapping\", m.GetCrossCloudGovernmentOrganizationMapping())\n if err != nil {\n return err\n }\n }\n if m.GetDeviceImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetDeviceImages()))\n for i, v := range m.GetDeviceImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"deviceImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetExternalPartnerSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetExternalPartnerSettings()))\n for i, v := range m.GetExternalPartnerSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"externalPartnerSettings\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetFrontLineServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetFrontLineServicePlans()))\n for i, v := range m.GetFrontLineServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"frontLineServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetGalleryImages() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetGalleryImages()))\n for i, v := range m.GetGalleryImages() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"galleryImages\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetOnPremisesConnections() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetOnPremisesConnections()))\n for i, v := range m.GetOnPremisesConnections() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"onPremisesConnections\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"organizationSettings\", m.GetOrganizationSettings())\n if err != nil {\n return err\n }\n }\n if m.GetProvisioningPolicies() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetProvisioningPolicies()))\n for i, v := range m.GetProvisioningPolicies() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"provisioningPolicies\", cast)\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"reports\", m.GetReports())\n if err != nil {\n return err\n }\n }\n if m.GetServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetServicePlans()))\n for i, v := range m.GetServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"servicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSharedUseServicePlans() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSharedUseServicePlans()))\n for i, v := range m.GetSharedUseServicePlans() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"sharedUseServicePlans\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSnapshots() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSnapshots()))\n for i, v := range m.GetSnapshots() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"snapshots\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetSupportedRegions() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetSupportedRegions()))\n for i, v := range m.GetSupportedRegions() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"supportedRegions\", cast)\n if err != nil {\n return err\n }\n }\n if m.GetUserSettings() != nil {\n cast := make([]i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, len(m.GetUserSettings()))\n for i, v := range m.GetUserSettings() {\n if v != nil {\n cast[i] = v.(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable)\n }\n }\n err = writer.WriteCollectionOfObjectValues(\"userSettings\", cast)\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (block *Block) Serialize() []byte {\n\tvar result bytes.Buffer\n\tencoder := gob.NewEncoder(&result)\n\terr := encoder.Encode(block)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn result.Bytes()\n}", "func (s *SigningIdentity) Serialize() ([]byte, error) {\n\t// serialize identities by prepending the MSPID and appending\n\t// the ASN.1 DER content of the cert\n\tsID := &msp.SerializedIdentity{Mspid: s.mspID, IdBytes: s.pemCert}\n\tidBytes, err := proto.Marshal(sID)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to marshal serialized indentity: %v\", err)\n\t}\n\n\treturn idBytes, nil\n}", "func (z ZSTDStore) Store(path string, data []byte) error {\n\td, err := zstd.Compress(nil, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn ioutil.WriteFile(gzPath(path), d, 0644)\n}", "func (m *WorkbookNamedItem) Serialize(writer i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.SerializationWriter)(error) {\n err := m.Entity.Serialize(writer)\n if err != nil {\n return err\n }\n {\n err = writer.WriteStringValue(\"comment\", m.GetComment())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"name\", m.GetName())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"scope\", m.GetScope())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteStringValue(\"type\", m.GetTypeEscaped())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"value\", m.GetValue())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteBoolValue(\"visible\", m.GetVisible())\n if err != nil {\n return err\n }\n }\n {\n err = writer.WriteObjectValue(\"worksheet\", m.GetWorksheet())\n if err != nil {\n return err\n }\n }\n return nil\n}", "func (u *UndoBlock) Serialize(w io.Writer) error {\n\terr := binary.Write(w, binary.BigEndian, u.numAdds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.BigEndian, uint64(len(u.positions)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.BigEndian, u.positions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = binary.Write(w, binary.BigEndian, uint64(len(u.hashes)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, hash := range u.hashes {\n\t\tn, err := w.Write(hash[:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif n != 32 {\n\t\t\terr := fmt.Errorf(\"UndoBlock Serialize supposed to write 32 bytes but wrote %d bytes\", n)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s CreateReferenceStoreOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o *A_2) Serialize(\r\n\tbyteOrder binary.ByteOrder,\r\n\tstream io.Writer,\r\n) error {\r\n\t//TODO: implement\r\n\t/*\r\n\t\tif err := o.cursor.Serialize(byteOrder, stream); err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\t\tif err := o.limit.Serialize(byteOrder, stream); err != nil {\r\n\t\t\t\treturn err\r\n\t\t\t}\r\n\t*/\r\n\treturn fmt.Errorf(\"not yet implemented\")\r\n}", "func (n Name) Serialize() []byte {\n\tnameData := make([]byte, 0, len(n)+5)\n\tfor _, label := range n.getLabels() {\n\t\tnameData = append(nameData, encodeLabel(label)...)\n\t}\n\t//terminate labels\n\tnameData = append(nameData, byte(0))\n\n\treturn nameData\n}", "func (this *Codec) serialize(root *TreeNode) string {\n\treturn dfsSerial(root, \"\")\n}" ]
[ "0.70957446", "0.65975136", "0.65526986", "0.6497997", "0.6186319", "0.61185783", "0.6036918", "0.5970338", "0.5967055", "0.59363616", "0.59057254", "0.5893347", "0.58872765", "0.5878474", "0.58523244", "0.58031774", "0.5770452", "0.5769023", "0.5768738", "0.5750052", "0.57499576", "0.5745281", "0.57450855", "0.57429004", "0.57123935", "0.5670098", "0.5660878", "0.5645549", "0.5627254", "0.5614375", "0.5594502", "0.55884004", "0.55842304", "0.5578335", "0.5568554", "0.5568407", "0.55593914", "0.5552329", "0.55484873", "0.55392724", "0.553401", "0.55320656", "0.55297226", "0.55186206", "0.5515125", "0.55014807", "0.550106", "0.5499541", "0.5496331", "0.54946065", "0.5492922", "0.5492922", "0.5487966", "0.54848236", "0.5472872", "0.5448183", "0.5443071", "0.54393184", "0.5438401", "0.5428178", "0.54276294", "0.542069", "0.5419823", "0.5415562", "0.5411777", "0.5411166", "0.5409837", "0.54091364", "0.54058474", "0.539932", "0.53975993", "0.538866", "0.5383759", "0.5381591", "0.53802663", "0.53800684", "0.53800684", "0.53800684", "0.5373027", "0.5371654", "0.5370257", "0.5363833", "0.53441954", "0.5343505", "0.53417724", "0.53409183", "0.5337238", "0.53351414", "0.5330896", "0.53281856", "0.5326304", "0.5326241", "0.53235507", "0.5323351", "0.53226113", "0.5322029", "0.53217435", "0.5321367", "0.53202033", "0.5319055" ]
0.8122401
0
ToProto converts to proto message
func (in *Store) ToProto() *iotextypes.BlockStore { receipts := []*iotextypes.Receipt{} for _, r := range in.Receipts { receipts = append(receipts, r.ConvertToReceiptPb()) } return &iotextypes.BlockStore{ Block: in.Block.ConvertToBlockPb(), Receipts: receipts, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (m *Mutate) ToProto() proto.Message {\n\tp, _, _ := m.toProto(false, nil)\n\treturn p\n}", "func (sb *SetBalancer) ToProto() proto.Message {\n\treturn sb.req\n}", "func (p *PlayerSpeech) ToProto() *pb.PlayerSpeech {\n\tplayerSpeech := &pb.PlayerSpeech{}\n\tplayerSpeech.Id = p.ID\n\tplayerSpeech.From = p.From\n\tplayerSpeech.To = p.To\n\tplayerSpeech.Frommessage = p.Frommessage\n\tplayerSpeech.Minstatus = p.Minstatus\n\tplayerSpeech.Guilddbid = p.Guilddbid\n\tplayerSpeech.Type = p.Type\n\tplayerSpeech.Timerecorded = p.Timerecorded.Unix()\n\treturn playerSpeech\n}", "func (p Pipeline) ToProto(pb *pipelinepb.AppliedPipeline) error {\n\tnumOps := len(p.Operations)\n\tif cap(pb.Ops) >= numOps {\n\t\tpb.Ops = pb.Ops[:numOps]\n\t} else {\n\t\tpb.Ops = make([]pipelinepb.AppliedPipelineOp, numOps)\n\t}\n\tfor i := 0; i < numOps; i++ {\n\t\tif err := p.Operations[i].ToProto(&pb.Ops[i]); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (t *Tree) ToProto() *pbMerkle.Tree {\n\treturn &pbMerkle.Tree{\n\t\tDepth: int64(t.depth),\n\t\tRootNode: t.rootNode.toProto(),\n\t}\n}", "func (t *Trade) ToProto() *pb.Trade {\n\ttrade := &pb.Trade{}\n\ttrade.Id = t.ID\n\ttrade.Time = t.Time.Unix()\n\ttrade.Char1Id = t.Char1id\n\ttrade.Char1Pp = t.Char1pp\n\ttrade.Char1Gp = t.Char1gp\n\ttrade.Char1Sp = t.Char1sp\n\ttrade.Char1Cp = t.Char1cp\n\ttrade.Char1Items = t.Char1items\n\ttrade.Char2Id = t.Char2id\n\ttrade.Char2Pp = t.Char2pp\n\ttrade.Char2Gp = t.Char2gp\n\ttrade.Char2Sp = t.Char2sp\n\ttrade.Char2Cp = t.Char2cp\n\ttrade.Char2Items = t.Char2items\n\treturn trade\n}", "func (m MessageType) ToBytes() []byte {\n\treturn []byte{byte(m)}\n}", "func ToProto(sandbox *Sandbox) *types.Sandbox {\n\textensions := make(map[string]*gogo_types.Any)\n\tfor k, v := range sandbox.Extensions {\n\t\textensions[k] = protobuf.FromAny(v)\n\t}\n\treturn &types.Sandbox{\n\t\tSandboxID: sandbox.ID,\n\t\tRuntime: &types.Sandbox_Runtime{\n\t\t\tName: sandbox.Runtime.Name,\n\t\t\tOptions: protobuf.FromAny(sandbox.Runtime.Options),\n\t\t},\n\t\tLabels: sandbox.Labels,\n\t\tCreatedAt: protobuf.ToTimestamp(sandbox.CreatedAt),\n\t\tUpdatedAt: protobuf.ToTimestamp(sandbox.UpdatedAt),\n\t\tExtensions: extensions,\n\t\tSpec: protobuf.FromAny(sandbox.Spec),\n\t}\n}", "func (t *trade) ToProto() *datastreams_pb.Trade {\n\treturn &datastreams_pb.Trade{\n\t\tTradePrice: t.tradePrice,\n\t\tTradeQuantity: t.tradeQuantity,\n\t\tTradeTime: t.tradeTime,\n\t}\n}", "func (g *gnmiPath) ToProto() (*gnmipb.Path, error) {\n\tif !g.isValid() {\n\t\treturn nil, errors.New(\"invalid path\")\n\t}\n\n\tif g.Len() == 0 {\n\t\treturn nil, nil\n\t}\n\n\tif g.isStringSlicePath() {\n\t\treturn &gnmipb.Path{Element: g.stringSlicePath}, nil\n\t}\n\treturn &gnmipb.Path{Elem: g.pathElemPath}, nil\n}", "func (tn *ListNamespaceDescriptors) ToProto() proto.Message {\n\treturn &pb.ListNamespaceDescriptorsRequest{\n\t}\n}", "func AsProtoMessage(v starlark.Value) (proto.Message, bool) {\n\treturn protomodule.AsProtoMessage(v)\n}", "func ChatDBToProto(chat *db.Chat) *models.Message {\n\treturn &models.Message{\n\t\tId: chat.ID,\n\t\tFrom: chat.From,\n\t\tBody: chat.Body,\n\t\tTo: chat.To,\n\t\tTime: chat.Time,\n\t}\n}", "func (m *MockCall) ToProto() protoreflect.ProtoMessage {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ToProto\")\n\tret0, _ := ret[0].(protoreflect.ProtoMessage)\n\treturn ret0\n}", "func (e *Email) ToProto() *emailService.Email {\n\treturn &emailService.Email{\n\t\tEmailID: e.EmailID.String(),\n\t\tFrom: e.From,\n\t\tTo: e.To,\n\t\tSubject: e.Subject,\n\t\tMessage: e.Subject,\n\t\tCreatedAt: timestamppb.New(e.CreatedAt),\n\t}\n}", "func (*RawMessage) ProtoMessage() {}", "func TimeToProto(t time.Time) *logutilpb.Time {\n\tseconds := t.Unix()\n\tnanos := int64(t.Sub(time.Unix(seconds, 0)))\n\treturn &logutilpb.Time{\n\t\tSeconds: seconds,\n\t\tNanoseconds: int32(nanos),\n\t}\n}", "func (data *Data) ToProto() tmproto.Data {\n\ttp := new(tmproto.Data)\n\n\tif len(data.Txs) > 0 {\n\t\ttxBzs := make([][]byte, len(data.Txs))\n\t\tfor i := range data.Txs {\n\t\t\ttxBzs[i] = data.Txs[i]\n\t\t}\n\t\ttp.Txs = txBzs\n\t}\n\n\treturn *tp\n}", "func (data *Data) ToProto() tmproto.Data {\n\ttp := new(tmproto.Data)\n\n\tif len(data.Txs) > 0 {\n\t\ttxBzs := make([][]byte, len(data.Txs))\n\t\tfor i := range data.Txs {\n\t\t\ttxBzs[i] = data.Txs[i]\n\t\t}\n\t\ttp.Txs = txBzs\n\t}\n\n\treturn *tp\n}", "func (m *Message) ToProtobuf() *PBDHTMessage {\n\tpmes := new(PBDHTMessage)\n\tif m.Value != nil {\n\t\tpmes.Value = m.Value\n\t}\n\n\tpmes.Type = &m.Type\n\tpmes.Key = &m.Key\n\tpmes.Response = &m.Response\n\tpmes.Id = &m.ID\n\tpmes.Success = &m.Success\n\tfor _, p := range m.Peers {\n\t\tpmes.Peers = append(pmes.Peers, peerInfo(p))\n\t}\n\n\treturn pmes\n}", "func (op *Operation) ToProto(wrappedID string) *api.UploadOperation {\n\tvar ref *api.ObjectRef\n\tif op.Status == api.UploadStatus_PUBLISHED {\n\t\tref = &api.ObjectRef{\n\t\t\tHashAlgo: op.HashAlgo,\n\t\t\tHexDigest: op.HexDigest,\n\t\t}\n\t}\n\treturn &api.UploadOperation{\n\t\tOperationId: wrappedID,\n\t\tUploadUrl: op.UploadURL,\n\t\tStatus: op.Status,\n\t\tObject: ref,\n\t\tErrorMessage: op.Error,\n\t}\n}", "func Marshal(pb proto.Message) ([]byte, error) {\n\treturn proto.Marshal(pb)\n}", "func Marshal(pb proto.Message) ([]byte, error) {\n\treturn proto.Marshal(pb)\n}", "func yamlToProto(path string, v proto.Message) error {\n\tyamlBytes, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tjsonBytes, err := yaml.YAMLToJSONStrict(yamlBytes)\n\tif err != nil {\n\t\treturn errors.Trace(err)\n\t}\n\tr := bytes.NewReader(jsonBytes)\n\terr = pbjson.NewDecoder(r).Decode(v)\n\treturn errors.Trace(err)\n}", "func protoEnc(in T) ([]byte, error) {\n\tvar p protoreflect.ProtoMessage\n\tswitch it := in.(type) {\n\tcase protoreflect.ProtoMessage:\n\t\tp = it\n\tcase protov1.Message:\n\t\tp = protov1.MessageV2(it)\n\t}\n\tb, err := protov2.MarshalOptions{Deterministic: true}.Marshal(p)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn b, nil\n}", "func (me *Model) ToRPCMsg(escape bool) *rpc.Message {\n\tret := &rpc.Message{\n\t\tId: me.ID.Hex(),\n\t\tTopicId: me.TopicID.Hex(),\n\t\tSenderName: me.SenderName,\n\t\tPostTime: &timestamp.Timestamp{\n\t\t\tSeconds: me.PostTime.Unix(),\n\t\t\tNanos: int32(me.PostTime.Nanosecond()),\n\t\t},\n\t\tMessage: me.Message,\n\t\tBump: me.Bump,\n\t}\n\tif escape {\n\t\tret.SenderName = html.EscapeString(me.SenderName)\n\t\tret.Message = html.EscapeString(me.Message)\n\t}\n\treturn ret\n}", "func (commit *Commit) ToProto() *tmproto.Commit {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\n\tc := new(tmproto.Commit)\n\n\tc.Height = commit.Height\n\tc.Round = commit.Round\n\tc.BlockID = commit.BlockID.ToProto()\n\tc.StateID = commit.StateID.ToProto()\n\n\tc.ThresholdStateSignature = commit.ThresholdStateSignature\n\tc.ThresholdBlockSignature = commit.ThresholdBlockSignature\n\n\tc.QuorumHash = commit.QuorumHash\n\n\treturn c\n}", "func (d *Dense) ToProto() *bb84pb.DenseBitArray {\n\treturn &bb84pb.DenseBitArray{\n\t\tBits: d.Data(),\n\t\tLen: int32(d.len),\n\t}\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\t// PartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func (b *BalanceAs) toProto() (*proto.Balance, error) {\n\tpb := &proto.Balance{\n\t\tSymbol: b.CoinBalance.Symbol,\n\t\tExchange: b.Exchange,\n\t\tFree: float32(b.Free),\n\t\tLocked: float32(b.Locked),\n\t\tTotal: float32(b.Total),\n\t\tAs: string(b.As),\n\t\tPrice: float32(b.Price),\n\t\tValue: float32(b.Value),\n\t\tPrice24H: float32(b.Price24H),\n\t\tValue24H: float32(b.Value24H),\n\t\tChange24H: float32(b.Change24H),\n\t\tChangePct24H: float32(b.ChangePct24H),\n\t}\n\n\tts, err := tspb.TimestampProto(b.At)\n\tif err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tpb.At = ts\n\t}\n\n\tif b.BuyStrategy != nil {\n\t\tif pb.BuyStrategy, err = strategyToProto(b.BuyStrategy); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif b.SellStrategy != nil {\n\t\tif pb.SellStrategy, err = strategyToProto(b.SellStrategy); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn pb, nil\n}", "func ProtobufToJSON(message protoreflect.ProtoMessage) ([]byte, error) {\n\tmarshaler := protojson.MarshalOptions{\n\t\tIndent: \"\",\n\t\tUseProtoNames: false,\n\t\tEmitUnpopulated: false,\n\t}\n\treturn marshaler.Marshal(message)\n}", "func (st *Account) ToProto() *iproto.AccountPb {\n\tacPb := &iproto.AccountPb{}\n\tacPb.Nonce = st.Nonce\n\tif st.Balance != nil {\n\t\tacPb.Balance = st.Balance.Bytes()\n\t}\n\tacPb.Root = make([]byte, hash.HashSize)\n\tcopy(acPb.Root, st.Root[:])\n\tacPb.CodeHash = make([]byte, len(st.CodeHash))\n\tcopy(acPb.CodeHash, st.CodeHash)\n\tacPb.IsCandidate = st.IsCandidate\n\tif st.VotingWeight != nil {\n\t\tacPb.VotingWeight = st.VotingWeight.Bytes()\n\t}\n\tacPb.Votee = st.Votee\n\treturn acPb\n}", "func (vc *VehicleContainer) AsProto() *gtfsrt.FeedMessage {\n\tmsg := util.MakeFeedMessage(vc.SyncTime)\n\tmsg.Entity = make([]*gtfsrt.FeedEntity, 0, len(vc.Vehicles))\n\tfor _, veh := range vc.Vehicles {\n\t\tmsg.Entity = append(msg.Entity, veh.AsProto())\n\t}\n\treturn msg\n}", "func (stateID *StateID) ToProto() tmproto.StateID {\n\tif stateID == nil {\n\t\treturn tmproto.StateID{}\n\t}\n\n\treturn tmproto.StateID{\n\t\tLastAppHash: stateID.LastAppHash,\n\t}\n}", "func SignatureToProto(sig interfaces.Signature) *Signature {\n\tif sig == nil {\n\t\treturn nil\n\t}\n\tpb := NewEmptySignature()\n\tpb.Raw = sig.Serialize()\n\treturn pb\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\tPartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func (blockID *BlockID) ToProto() tmproto.BlockID {\n\tif blockID == nil {\n\t\treturn tmproto.BlockID{}\n\t}\n\n\treturn tmproto.BlockID{\n\t\tHash: blockID.Hash,\n\t\tPartSetHeader: blockID.PartSetHeader.ToProto(),\n\t}\n}", "func _proto_marshal(obj proto.Message) []byte {\n\tbuf, err := proto.Marshal(obj)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn buf\n}", "func (commit *Commit) ToProto() *tmproto.Commit {\n\tif commit == nil {\n\t\treturn nil\n\t}\n\n\tc := new(tmproto.Commit)\n\tsigs := make([]tmproto.CommitSig, len(commit.Signatures))\n\tfor i := range commit.Signatures {\n\t\tsigs[i] = *commit.Signatures[i].ToProto()\n\t}\n\tc.Signatures = sigs\n\n\tc.Height = commit.Height\n\tc.Round = commit.Round\n\tc.BlockID = commit.BlockID.ToProto()\n\n\treturn c\n}", "func (g *Group) ToProto(version commonutils.Version) *proto.GroupPacket {\n\tvar out = new(proto.GroupPacket)\n\tvar ids = make([]*proto.Node, len(g.Nodes))\n\n\tfor i, id := range g.Nodes {\n\t\tkey, _ := id.Key.MarshalBinary()\n\t\tids[i] = &proto.Node{\n\t\t\tPublic: &proto.Identity{\n\t\t\t\tAddress: id.Address(),\n\t\t\t\tTls: id.IsTLS(),\n\t\t\t\tKey: key,\n\t\t\t\tSignature: id.Signature,\n\t\t\t},\n\t\t\tIndex: id.Index,\n\t\t}\n\t}\n\n\tout.Nodes = ids\n\tout.Period = uint32(g.Period.Seconds())\n\tout.CatchupPeriod = uint32(g.CatchupPeriod.Seconds())\n\tout.Threshold = uint32(g.Threshold)\n\tout.GenesisTime = uint64(g.GenesisTime)\n\tout.TransitionTime = uint64(g.TransitionTime)\n\tout.GenesisSeed = g.GetGenesisSeed()\n\tout.SchemeID = g.Scheme.Name\n\n\tout.Metadata = common.NewMetadata(version.ToProto())\n\tout.Metadata.BeaconID = commonutils.GetCanonicalBeaconID(g.ID)\n\n\tif g.PublicKey != nil {\n\t\tvar coeffs = make([][]byte, len(g.PublicKey.Coefficients))\n\t\tfor i, c := range g.PublicKey.Coefficients {\n\t\t\tbuff, _ := c.MarshalBinary()\n\t\t\tcoeffs[i] = buff\n\t\t}\n\t\tout.DistKey = coeffs\n\t}\n\treturn out\n}", "func ProtobufToJSON(message proto.Message) (string, error) {\n\tmarshaler := protojson.MarshalOptions{\n\t\tEmitUnpopulated: true,\n\t\tUseProtoNames: true,\n\t\tIndent: \" \",\n\t}\n\n\tb, err := marshaler.Marshal(message)\n\treturn string(b), err\n}", "func (c Cluster) ToProto() *vtadminpb.Cluster {\n\treturn &vtadminpb.Cluster{\n\t\tId: c.ID,\n\t\tName: c.Name,\n\t}\n}", "func (fieldMask *WatchServiceRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func BigIntToProto(x *big.Int) *BigInt {\n\tif x == nil {\n\t\treturn nil\n\t}\n\tpb := new(BigInt)\n\tpb.Raw = x.Bytes()\n\treturn pb\n}", "func (op RollupOp) ToProto(pb *pipelinepb.AppliedRollupOp) error {\n\top.AggregationID.ToProto(&pb.AggregationId)\n\tpb.Id = op.ID\n\treturn nil\n}", "func (s Message) ToBytes() ([]byte, error) {\n\tj, e := json.Marshal(s)\n\treturn j, e\n}", "func (fieldMask *Metric_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func SubscriptionToProto(resource *pubsublite.Subscription) *pubsublitepb.PubsubliteSubscription {\n\tp := &pubsublitepb.PubsubliteSubscription{\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tTopic: dcl.ValueOrEmptyString(resource.Topic),\n\t\tDeliveryConfig: PubsubliteSubscriptionDeliveryConfigToProto(resource.DeliveryConfig),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t\tLocation: dcl.ValueOrEmptyString(resource.Location),\n\t}\n\n\treturn p\n}", "func (fieldMask *WatchServiceResponse_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (z *Zone) ToProto() *pb.Zone {\n\tzone := &pb.Zone{}\n\tzone.Shortname = z.Shortname.String\n\tzone.Id = z.ID\n\tzone.Filename = z.Filename.String\n\tzone.Longname = z.Longname\n\tzone.Mapfilename = z.Mapfilename.String\n\tzone.Safex = z.Safex\n\tzone.Safey = z.Safey\n\tzone.Safez = z.Safez\n\tzone.Graveyardid = z.Graveyardid\n\tzone.Minlevel = z.Minlevel\n\tzone.Minstatus = z.Minstatus\n\tzone.Zoneidnumber = z.Zoneidnumber\n\tzone.Version = z.Version\n\tzone.Timezone = z.Timezone\n\tzone.Maxclients = z.Maxclients\n\tzone.Ruleset = z.Ruleset\n\tzone.Note = z.Note.String\n\tzone.Underworld = z.Underworld\n\tzone.Minclip = z.Minclip\n\tzone.Maxclip = z.Maxclip\n\tzone.Fogminclip = z.Fogminclip\n\tzone.Fogmaxclip = z.Fogmaxclip\n\tzone.Fogblue = z.Fogblue\n\tzone.Fogred = z.Fogred\n\tzone.Foggreen = z.Foggreen\n\tzone.Sky = z.Sky\n\tzone.Ztype = z.Ztype\n\tzone.Zoneexpmultiplier = z.Zoneexpmultiplier\n\tzone.Walkspeed = z.Walkspeed\n\tzone.Timetype = z.Timetype\n\tzone.Fogred1 = z.Fogred1\n\tzone.Foggreen1 = z.Foggreen1\n\tzone.Fogblue1 = z.Fogblue1\n\tzone.Fogminclip1 = z.Fogminclip1\n\tzone.Fogmaxclip1 = z.Fogmaxclip1\n\tzone.Fogred2 = z.Fogred2\n\tzone.Foggreen2 = z.Foggreen2\n\tzone.Fogblue2 = z.Fogblue2\n\tzone.Fogminclip2 = z.Fogminclip2\n\tzone.Fogmaxclip2 = z.Fogmaxclip2\n\tzone.Fogred3 = z.Fogred3\n\tzone.Foggreen3 = z.Foggreen3\n\tzone.Fogblue3 = z.Fogblue3\n\tzone.Fogminclip3 = z.Fogminclip3\n\tzone.Fogmaxclip3 = z.Fogmaxclip3\n\tzone.Fogred4 = z.Fogred4\n\tzone.Foggreen4 = z.Foggreen4\n\tzone.Fogblue4 = z.Fogblue4\n\tzone.Fogminclip4 = z.Fogminclip4\n\tzone.Fogmaxclip4 = z.Fogmaxclip4\n\tzone.Fogdensity = z.Fogdensity\n\tzone.Flagneeded = z.Flagneeded\n\tzone.Canbind = z.Canbind\n\tzone.Cancombat = z.Cancombat\n\tzone.Canlevitate = z.Canlevitate\n\tzone.Castoutdoor = z.Castoutdoor\n\tzone.Hotzone = z.Hotzone\n\tzone.Insttype = z.Insttype\n\tzone.Shutdowndelay = z.Shutdowndelay\n\tzone.Peqzone = z.Peqzone\n\tzone.Expansion = z.Expansion\n\tzone.Suspendbuffs = z.Suspendbuffs\n\tzone.Rainchance1 = z.Rainchance1\n\tzone.Rainchance2 = z.Rainchance2\n\tzone.Rainchance3 = z.Rainchance3\n\tzone.Rainchance4 = z.Rainchance4\n\tzone.Rainduration1 = z.Rainduration1\n\tzone.Rainduration2 = z.Rainduration2\n\tzone.Rainduration3 = z.Rainduration3\n\tzone.Rainduration4 = z.Rainduration4\n\tzone.Snowchance1 = z.Snowchance1\n\tzone.Snowchance2 = z.Snowchance2\n\tzone.Snowchance3 = z.Snowchance3\n\tzone.Snowchance4 = z.Snowchance4\n\tzone.Snowduration1 = z.Snowduration1\n\tzone.Snowduration2 = z.Snowduration2\n\tzone.Snowduration3 = z.Snowduration3\n\tzone.Snowduration4 = z.Snowduration4\n\tzone.Gravity = z.Gravity\n\tzone.Type = z.Type\n\tzone.Skylock = z.Skylock\n\tzone.Fastregenhp = z.Fastregenhp\n\tzone.Fastregenmana = z.Fastregenmana\n\tzone.Fastregenendurance = z.Fastregenendurance\n\tzone.Npcmaxaggrodist = z.Npcmaxaggrodist\n\tzone.Maxmovementupdaterange = z.Maxmovementupdaterange\n\treturn zone\n}", "func BigqueryRoutineArgumentsToProto(o *bigquery.RoutineArguments) *bigquerypb.BigqueryRoutineArguments {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArguments{}\n\tp.SetName(dcl.ValueOrEmptyString(o.Name))\n\tp.SetArgumentKind(BigqueryRoutineArgumentsArgumentKindEnumToProto(o.ArgumentKind))\n\tp.SetMode(BigqueryRoutineArgumentsModeEnumToProto(o.Mode))\n\tp.SetDataType(BigqueryRoutineArgumentsDataTypeToProto(o.DataType))\n\treturn p\n}", "func ProtobufToJSON(message proto.Message) (string, error) {\n\tmarshaler, err := protojson.Marshal(message)\n\treturn string(marshaler), err\n}", "func (fieldMask *AcceptRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (mb *MutableBag) ToProto(output *mixerpb.CompressedAttributes, globalDict map[string]int32, globalWordCount int) {\n\tds := newDictState(globalDict, globalWordCount)\n\tkeys := mb.Names()\n\n\tfor _, k := range keys {\n\t\tindex := ds.assignDictIndex(k)\n\t\tv, _ := mb.Get(k) // if not found, nil return will be ignored by the switch below\n\n\t\tswitch t := v.(type) {\n\t\tcase string:\n\t\t\tif output.Strings == nil {\n\t\t\t\toutput.Strings = make(map[int32]int32)\n\t\t\t}\n\t\t\toutput.Strings[index] = ds.assignDictIndex(t)\n\n\t\tcase int64:\n\t\t\tif output.Int64S == nil {\n\t\t\t\toutput.Int64S = make(map[int32]int64)\n\t\t\t}\n\t\t\toutput.Int64S[index] = t\n\n\t\tcase int:\n\t\t\tif output.Int64S == nil {\n\t\t\t\toutput.Int64S = make(map[int32]int64)\n\t\t\t}\n\t\t\toutput.Int64S[index] = int64(t)\n\n\t\tcase float64:\n\t\t\tif output.Doubles == nil {\n\t\t\t\toutput.Doubles = make(map[int32]float64)\n\t\t\t}\n\t\t\toutput.Doubles[index] = t\n\n\t\tcase bool:\n\t\t\tif output.Bools == nil {\n\t\t\t\toutput.Bools = make(map[int32]bool)\n\t\t\t}\n\t\t\toutput.Bools[index] = t\n\n\t\tcase time.Time:\n\t\t\tif output.Timestamps == nil {\n\t\t\t\toutput.Timestamps = make(map[int32]time.Time)\n\t\t\t}\n\t\t\toutput.Timestamps[index] = t\n\n\t\tcase time.Duration:\n\t\t\tif output.Durations == nil {\n\t\t\t\toutput.Durations = make(map[int32]time.Duration)\n\t\t\t}\n\t\t\toutput.Durations[index] = t\n\n\t\tcase []byte:\n\t\t\tif output.Bytes == nil {\n\t\t\t\toutput.Bytes = make(map[int32][]byte)\n\t\t\t}\n\t\t\toutput.Bytes[index] = t\n\n\t\tcase map[string]string:\n\t\t\tsm := make(map[int32]int32, len(t))\n\t\t\tfor smk, smv := range t {\n\t\t\t\tsm[ds.assignDictIndex(smk)] = ds.assignDictIndex(smv)\n\t\t\t}\n\n\t\t\tif output.StringMaps == nil {\n\t\t\t\toutput.StringMaps = make(map[int32]mixerpb.StringMap)\n\t\t\t}\n\t\t\toutput.StringMaps[index] = mixerpb.StringMap{Entries: sm}\n\n\t\tdefault:\n\t\t\tpanic(fmt.Errorf(\"cannot convert value:%v of type:%T\", v, v))\n\t\t}\n\t}\n\n\toutput.Words = ds.getMessageWordList()\n}", "func (fieldMask *TypedValue_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (l *EmailsList) ToProto() []*emailService.Email {\n\tmails := make([]*emailService.Email, 0, len(l.Emails))\n\tfor _, e := range l.Emails {\n\t\tmails = append(mails, e.ToProto())\n\t}\n\treturn mails\n}", "func BigqueryRoutineArgumentsDataTypeStructTypeToProto(o *bigquery.RoutineArgumentsDataTypeStructType) *bigquerypb.BigqueryRoutineArgumentsDataTypeStructType {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArgumentsDataTypeStructType{}\n\tsFields := make([]*bigquerypb.BigqueryRoutineArgumentsDataTypeStructTypeFields, len(o.Fields))\n\tfor i, r := range o.Fields {\n\t\tsFields[i] = BigqueryRoutineArgumentsDataTypeStructTypeFieldsToProto(&r)\n\t}\n\tp.SetFields(sFields)\n\treturn p\n}", "func (u OpUnion) ToProto(pb *pipelinepb.AppliedPipelineOp) error {\n\tpb.Reset()\n\tswitch u.Type {\n\tcase pipeline.TransformationOpType:\n\t\tpb.Type = pipelinepb.AppliedPipelineOp_TRANSFORMATION\n\t\treturn u.Transformation.ToProto(&pb.Transformation)\n\tcase pipeline.RollupOpType:\n\t\tpb.Type = pipelinepb.AppliedPipelineOp_ROLLUP\n\t\treturn u.Rollup.ToProto(&pb.Rollup)\n\tdefault:\n\t\treturn errUnknownOpType\n\t}\n}", "func (h *Header) ToProto() *tmproto.Header {\n\tif h == nil {\n\t\treturn nil\n\t}\n\n\treturn &tmproto.Header{\n\t\tVersion: h.Version,\n\t\tChainID: h.ChainID,\n\t\tHeight: h.Height,\n\t\tTime: h.Time,\n\t\tLastBlockId: h.LastBlockID.ToProto(),\n\t\tValidatorsHash: h.ValidatorsHash,\n\t\tNextValidatorsHash: h.NextValidatorsHash,\n\t\tConsensusHash: h.ConsensusHash,\n\t\tAppHash: h.AppHash,\n\t\tDataHash: h.DataHash,\n\t\tEvidenceHash: h.EvidenceHash,\n\t\tLastResultsHash: h.LastResultsHash,\n\t\tLastCommitHash: h.LastCommitHash,\n\t\tProposerAddress: h.ProposerAddress,\n\t}\n}", "func (fieldMask *MonitoredResource_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func marshalProto(message protoutil.Message) (tree.Datum, error) {\n\tdata := make([]byte, message.Size())\n\tif _, err := message.MarshalTo(data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn tree.NewDBytes(tree.DBytes(data)), nil\n}", "func BigqueryRoutineArgumentsDataTypeToProto(o *bigquery.RoutineArgumentsDataType) *bigquerypb.BigqueryRoutineArgumentsDataType {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &bigquerypb.BigqueryRoutineArgumentsDataType{}\n\tp.SetTypeKind(BigqueryRoutineArgumentsDataTypeTypeKindEnumToProto(o.TypeKind))\n\tp.SetArrayElementType(BigqueryRoutineArgumentsDataTypeToProto(o.ArrayElementType))\n\tp.SetStructType(BigqueryRoutineArgumentsDataTypeStructTypeToProto(o.StructType))\n\treturn p\n}", "func ContainerClusterConditionsToProto(o *container.ClusterConditions) *containerpb.ContainerClusterConditions {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterConditions{\n\t\tCode: dcl.ValueOrEmptyString(o.Code),\n\t\tMessage: dcl.ValueOrEmptyString(o.Message),\n\t}\n\treturn p\n}", "func (c *channel) pubMsgToMsgProto(pm *pb.PubMsg, seq uint64) *pb.MsgProto {\n\tm := &pb.MsgProto{\n\t\tSequence: seq,\n\t\tSubject: pm.Subject,\n\t\tReply: pm.Reply,\n\t\tData: pm.Data,\n\t\tTimestamp: time.Now().UnixNano(),\n\t}\n\tif c.lTimestamp > 0 && m.Timestamp < c.lTimestamp {\n\t\tm.Timestamp = c.lTimestamp\n\t}\n\tc.lTimestamp = m.Timestamp\n\treturn m\n}", "func (fieldMask *GetServiceRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func BrandToProto(brand *domain.Brand) *brandproto.Brand {\n\tif brand == nil {\n\t\treturn nil\n\t}\n\n\treturn &brandproto.Brand{\n\t\tId: brand.ID,\n\t\tSlug: brand.Slug,\n\t\tShortName: brand.ShortName,\n\t\tName: brand.Name,\n\t\tDescription: brand.Description,\n\t\tImageId: brand.ImageID,\n\t\tCreatedAt: util.TimeToProto(brand.CreatedAt),\n\t\tUpdatedAt: util.TimeToProto(brand.UpdatedAt),\n\t}\n}", "func ProtoToModel(p *vertexaipb.VertexaiModel) *vertexai.Model {\n\tobj := &vertexai.Model{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tVersionId: dcl.StringOrNil(p.GetVersionId()),\n\t\tVersionCreateTime: dcl.StringOrNil(p.GetVersionCreateTime()),\n\t\tVersionUpdateTime: dcl.StringOrNil(p.GetVersionUpdateTime()),\n\t\tDisplayName: dcl.StringOrNil(p.GetDisplayName()),\n\t\tDescription: dcl.StringOrNil(p.GetDescription()),\n\t\tVersionDescription: dcl.StringOrNil(p.GetVersionDescription()),\n\t\tTrainingPipeline: dcl.StringOrNil(p.GetTrainingPipeline()),\n\t\tOriginalModelInfo: ProtoToVertexaiModelOriginalModelInfo(p.GetOriginalModelInfo()),\n\t\tContainerSpec: ProtoToVertexaiModelContainerSpec(p.GetContainerSpec()),\n\t\tArtifactUri: dcl.StringOrNil(p.GetArtifactUri()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tUpdateTime: dcl.StringOrNil(p.GetUpdateTime()),\n\t\tEtag: dcl.StringOrNil(p.GetEtag()),\n\t\tEncryptionSpec: ProtoToVertexaiModelEncryptionSpec(p.GetEncryptionSpec()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t}\n\tfor _, r := range p.GetSupportedExportFormats() {\n\t\tobj.SupportedExportFormats = append(obj.SupportedExportFormats, *ProtoToVertexaiModelSupportedExportFormats(r))\n\t}\n\tfor _, r := range p.GetSupportedDeploymentResourcesTypes() {\n\t\tobj.SupportedDeploymentResourcesTypes = append(obj.SupportedDeploymentResourcesTypes, *ProtoToVertexaiModelSupportedDeploymentResourcesTypesEnum(r))\n\t}\n\tfor _, r := range p.GetSupportedInputStorageFormats() {\n\t\tobj.SupportedInputStorageFormats = append(obj.SupportedInputStorageFormats, r)\n\t}\n\tfor _, r := range p.GetSupportedOutputStorageFormats() {\n\t\tobj.SupportedOutputStorageFormats = append(obj.SupportedOutputStorageFormats, r)\n\t}\n\tfor _, r := range p.GetDeployedModels() {\n\t\tobj.DeployedModels = append(obj.DeployedModels, *ProtoToVertexaiModelDeployedModels(r))\n\t}\n\treturn obj\n}", "func (fieldMask *WatchServicesRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (fieldMask *CreateServiceRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (protocol *Protocol)Marshal() ([]byte, error) {\n buff := new(bytes.Buffer);\n binary.Write(buff, binary.BigEndian, protocol.ID);\n binary.Write(buff, binary.BigEndian, protocol.PType)\n ms, ok := protocol.Packet.(proto.Message);\n if !ok {\n\t\treturn nil, fmt.Errorf(\"Protocol error not valid protobuff\");\n\t}\n data, err := proto.Marshal(ms)\n if nil != err {\n return nil, fmt.Errorf(\"Packet Marshal Error\");\n }\n buff.Write(data);\n return buff.Bytes(), nil\n}", "func SqlInstanceMaxDiskSizeToProto(o *sql.InstanceMaxDiskSize) *sqlpb.SqlInstanceMaxDiskSize {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &sqlpb.SqlInstanceMaxDiskSize{\n\t\tValue: dcl.ValueOrEmptyInt64(o.Value),\n\t}\n\treturn p\n}", "func (fieldMask *GetMonitoredResourceDescriptorRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (sh *SignedHeader) ToProto() *types.SignedHeaderProto {\n\tif sh == nil {\n\t\treturn nil\n\t}\n\n\tpsh := new(types.SignedHeaderProto)\n\tif sh.TendermintBlockHeader != nil {\n\t\tpsh.Header = sh.TendermintBlockHeader.ToProtoHeader()\n\t}\n\tif sh.Commit != nil {\n\t\tpsh.Commit = sh.Commit.ToProto()\n\t}\n\n\treturn psh\n}", "func (h *Header) ToProto() *tmproto.Header {\n\tif h == nil {\n\t\treturn nil\n\t}\n\n\treturn &tmproto.Header{\n\t\tVersion: h.Version,\n\t\tChainID: h.ChainID,\n\t\tHeight: h.Height,\n\t\tCoreChainLockedHeight: h.CoreChainLockedHeight,\n\t\tTime: h.Time,\n\t\tLastBlockId: h.LastBlockID.ToProto(),\n\t\tValidatorsHash: h.ValidatorsHash,\n\t\tNextValidatorsHash: h.NextValidatorsHash,\n\t\tConsensusHash: h.ConsensusHash,\n\t\tAppHash: h.AppHash,\n\t\tDataHash: h.DataHash,\n\t\tEvidenceHash: h.EvidenceHash,\n\t\tLastResultsHash: h.LastResultsHash,\n\t\tLastCommitHash: h.LastCommitHash,\n\t\tProposerProTxHash: h.ProposerProTxHash,\n\t}\n}", "func (fieldMask *ListenRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (fieldMask *Ping_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (fieldMask *Data_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func CryptoKeyToProto(resource *beta.CryptoKey) *betapb.CloudkmsBetaCryptoKey {\n\tp := &betapb.CloudkmsBetaCryptoKey{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetPrimary(CloudkmsBetaCryptoKeyPrimaryToProto(resource.Primary))\n\tp.SetPurpose(CloudkmsBetaCryptoKeyPurposeEnumToProto(resource.Purpose))\n\tp.SetCreateTime(dcl.ValueOrEmptyString(resource.CreateTime))\n\tp.SetNextRotationTime(dcl.ValueOrEmptyString(resource.NextRotationTime))\n\tp.SetRotationPeriod(dcl.ValueOrEmptyString(resource.RotationPeriod))\n\tp.SetVersionTemplate(CloudkmsBetaCryptoKeyVersionTemplateToProto(resource.VersionTemplate))\n\tp.SetImportOnly(dcl.ValueOrEmptyBool(resource.ImportOnly))\n\tp.SetDestroyScheduledDuration(dcl.ValueOrEmptyString(resource.DestroyScheduledDuration))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetLocation(dcl.ValueOrEmptyString(resource.Location))\n\tp.SetKeyRing(dcl.ValueOrEmptyString(resource.KeyRing))\n\tmLabels := make(map[string]string, len(resource.Labels))\n\tfor k, r := range resource.Labels {\n\t\tmLabels[k] = r\n\t}\n\tp.SetLabels(mLabels)\n\n\treturn p\n}", "func (m *Message) ToBytes() []byte {\n\tdata := make([]byte, 0, 0)\n\n\tdata = append(data, m.Header.ToBytes()...)\n\tdata = append(data, m.Question.ToBytes()...)\n\n\tfor _, answer := range m.Answers {\n\t\tdata = append(data, answer.ToBytes()...)\n\t}\n\n\tfor _, authority := range m.Authority {\n\t\tdata = append(data, authority.ToBytes()...)\n\t}\n\n\tfor _, additional := range m.Additional {\n\t\tdata = append(data, additional.ToBytes()...)\n\t}\n\n\treturn data\n}", "func (sm *ServerMetrics) toLoadReportProto() *v3orcapb.OrcaLoadReport {\n\tret := &v3orcapb.OrcaLoadReport{\n\t\tUtilization: sm.Utilization,\n\t\tRequestCost: sm.RequestCost,\n\t\tNamedMetrics: sm.NamedMetrics,\n\t}\n\tif sm.CPUUtilization != -1 {\n\t\tret.CpuUtilization = sm.CPUUtilization\n\t}\n\tif sm.MemUtilization != -1 {\n\t\tret.MemUtilization = sm.MemUtilization\n\t}\n\tif sm.AppUtilization != -1 {\n\t\tret.ApplicationUtilization = sm.AppUtilization\n\t}\n\tif sm.QPS != -1 {\n\t\tret.RpsFractional = sm.QPS\n\t}\n\tif sm.EPS != -1 {\n\t\tret.Eps = sm.EPS\n\t}\n\treturn ret\n}", "func (fieldMask *Ack_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func ProtoToCryptoKey(p *betapb.CloudkmsBetaCryptoKey) *beta.CryptoKey {\n\tobj := &beta.CryptoKey{\n\t\tName: dcl.StringOrNil(p.GetName()),\n\t\tPrimary: ProtoToCloudkmsBetaCryptoKeyPrimary(p.GetPrimary()),\n\t\tPurpose: ProtoToCloudkmsBetaCryptoKeyPurposeEnum(p.GetPurpose()),\n\t\tCreateTime: dcl.StringOrNil(p.GetCreateTime()),\n\t\tNextRotationTime: dcl.StringOrNil(p.GetNextRotationTime()),\n\t\tRotationPeriod: dcl.StringOrNil(p.GetRotationPeriod()),\n\t\tVersionTemplate: ProtoToCloudkmsBetaCryptoKeyVersionTemplate(p.GetVersionTemplate()),\n\t\tImportOnly: dcl.Bool(p.GetImportOnly()),\n\t\tDestroyScheduledDuration: dcl.StringOrNil(p.GetDestroyScheduledDuration()),\n\t\tProject: dcl.StringOrNil(p.GetProject()),\n\t\tLocation: dcl.StringOrNil(p.GetLocation()),\n\t\tKeyRing: dcl.StringOrNil(p.GetKeyRing()),\n\t}\n\treturn obj\n}", "func (fieldMask *MonitoredResourceMetadata_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (u *UnknownPathAttribute) ToProto() *api.UnknownPathAttribute {\n\ta := &api.UnknownPathAttribute{\n\t\tOptional: u.Optional,\n\t\tTransitive: u.Transitive,\n\t\tPartial: u.Partial,\n\t\tTypeCode: uint32(u.TypeCode),\n\t\tValue: make([]byte, len(u.Value)),\n\t}\n\n\tcopy(a.Value, u.Value)\n\treturn a\n}", "func ComputeFirewallLogConfigToProto(o *compute.FirewallLogConfig) *computepb.ComputeFirewallLogConfig {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &computepb.ComputeFirewallLogConfig{\n\t\tEnable: dcl.ValueOrEmptyBool(o.Enable),\n\t}\n\treturn p\n}", "func RoutineToProto(resource *bigquery.Routine) *bigquerypb.BigqueryRoutine {\n\tp := &bigquerypb.BigqueryRoutine{}\n\tp.SetEtag(dcl.ValueOrEmptyString(resource.Etag))\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetDataset(dcl.ValueOrEmptyString(resource.Dataset))\n\tp.SetRoutineType(BigqueryRoutineRoutineTypeEnumToProto(resource.RoutineType))\n\tp.SetCreationTime(dcl.ValueOrEmptyInt64(resource.CreationTime))\n\tp.SetLastModifiedTime(dcl.ValueOrEmptyInt64(resource.LastModifiedTime))\n\tp.SetLanguage(BigqueryRoutineLanguageEnumToProto(resource.Language))\n\tp.SetReturnType(BigqueryRoutineArgumentsDataTypeToProto(resource.ReturnType))\n\tp.SetDefinitionBody(dcl.ValueOrEmptyString(resource.DefinitionBody))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetDeterminismLevel(BigqueryRoutineDeterminismLevelEnumToProto(resource.DeterminismLevel))\n\tp.SetStrictMode(dcl.ValueOrEmptyBool(resource.StrictMode))\n\tsArguments := make([]*bigquerypb.BigqueryRoutineArguments, len(resource.Arguments))\n\tfor i, r := range resource.Arguments {\n\t\tsArguments[i] = BigqueryRoutineArgumentsToProto(&r)\n\t}\n\tp.SetArguments(sArguments)\n\tsImportedLibraries := make([]string, len(resource.ImportedLibraries))\n\tfor i, r := range resource.ImportedLibraries {\n\t\tsImportedLibraries[i] = r\n\t}\n\tp.SetImportedLibraries(sImportedLibraries)\n\n\treturn p\n}", "func (u *User) ToProto() *api.StateUser {\n\tuser := new(api.StateUser)\n\tuser.Host = string(u.Host)\n\tuser.Realname = u.Realname\n\n\treturn user\n}", "func ChatProtoToDB(msg *models.Message) *db.Chat {\n\treturn &db.Chat{\n\t\tID: msg.Id,\n\t\tFrom: msg.From,\n\t\tTo: msg.To,\n\t\tBody: msg.Body,\n\t\tTime: msg.Time,\n\t}\n}", "func ContainerClusterAddonsConfigHttpLoadBalancingToProto(o *container.ClusterAddonsConfigHttpLoadBalancing) *containerpb.ContainerClusterAddonsConfigHttpLoadBalancing {\n\tif o == nil {\n\t\treturn nil\n\t}\n\tp := &containerpb.ContainerClusterAddonsConfigHttpLoadBalancing{\n\t\tDisabled: dcl.ValueOrEmptyBool(o.Disabled),\n\t}\n\treturn p\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func FromProto(s *spb.Status) *Status {\n\treturn status.FromProto(s)\n}", "func BigqueryRoutineLanguageEnumToProto(e *bigquery.RoutineLanguageEnum) bigquerypb.BigqueryRoutineLanguageEnum {\n\tif e == nil {\n\t\treturn bigquerypb.BigqueryRoutineLanguageEnum(0)\n\t}\n\tif v, ok := bigquerypb.BigqueryRoutineLanguageEnum_value[\"RoutineLanguageEnum\"+string(*e)]; ok {\n\t\treturn bigquerypb.BigqueryRoutineLanguageEnum(v)\n\t}\n\treturn bigquerypb.BigqueryRoutineLanguageEnum(0)\n}", "func FirewallToProto(resource *compute.Firewall) *computepb.ComputeFirewall {\n\tp := &computepb.ComputeFirewall{\n\t\tCreationTimestamp: dcl.ValueOrEmptyString(resource.CreationTimestamp),\n\t\tDescription: dcl.ValueOrEmptyString(resource.Description),\n\t\tDirection: ComputeFirewallDirectionEnumToProto(resource.Direction),\n\t\tDisabled: dcl.ValueOrEmptyBool(resource.Disabled),\n\t\tId: dcl.ValueOrEmptyString(resource.Id),\n\t\tLogConfig: ComputeFirewallLogConfigToProto(resource.LogConfig),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tNetwork: dcl.ValueOrEmptyString(resource.Network),\n\t\tPriority: dcl.ValueOrEmptyInt64(resource.Priority),\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tProject: dcl.ValueOrEmptyString(resource.Project),\n\t}\n\tfor _, r := range resource.Allowed {\n\t\tp.Allowed = append(p.Allowed, ComputeFirewallAllowedToProto(&r))\n\t}\n\tfor _, r := range resource.Denied {\n\t\tp.Denied = append(p.Denied, ComputeFirewallDeniedToProto(&r))\n\t}\n\tfor _, r := range resource.DestinationRanges {\n\t\tp.DestinationRanges = append(p.DestinationRanges, r)\n\t}\n\tfor _, r := range resource.SourceRanges {\n\t\tp.SourceRanges = append(p.SourceRanges, r)\n\t}\n\tfor _, r := range resource.SourceServiceAccounts {\n\t\tp.SourceServiceAccounts = append(p.SourceServiceAccounts, r)\n\t}\n\tfor _, r := range resource.SourceTags {\n\t\tp.SourceTags = append(p.SourceTags, r)\n\t}\n\tfor _, r := range resource.TargetServiceAccounts {\n\t\tp.TargetServiceAccounts = append(p.TargetServiceAccounts, r)\n\t}\n\tfor _, r := range resource.TargetTags {\n\t\tp.TargetTags = append(p.TargetTags, r)\n\t}\n\n\treturn p\n}", "func ToCompatibleMessage(message MessageInterface) []byte {\n\tcompatibleMessage := CompatibleBaseMessage{\n\t\tPayload: message,\n\t\tMessageType: \"\",\n\t\tTimestamp: time.Now().Format(TimeFormat),\n\t}\n\treturn ToJSONByteSlice(compatibleMessage)\n\n}", "func ServiceAccountToProto(resource *iam.ServiceAccount) *iampb.IamServiceAccount {\n\tp := &iampb.IamServiceAccount{}\n\tp.SetName(dcl.ValueOrEmptyString(resource.Name))\n\tp.SetProject(dcl.ValueOrEmptyString(resource.Project))\n\tp.SetUniqueId(dcl.ValueOrEmptyString(resource.UniqueId))\n\tp.SetEmail(dcl.ValueOrEmptyString(resource.Email))\n\tp.SetDisplayName(dcl.ValueOrEmptyString(resource.DisplayName))\n\tp.SetDescription(dcl.ValueOrEmptyString(resource.Description))\n\tp.SetOauth2ClientId(dcl.ValueOrEmptyString(resource.OAuth2ClientId))\n\tp.SetActasResources(IamServiceAccountActasResourcesToProto(resource.ActasResources))\n\tp.SetDisabled(dcl.ValueOrEmptyBool(resource.Disabled))\n\n\treturn p\n}", "func (fieldMask *Allowance_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (fieldMask *AcceptResponse_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func DomainMappingToProto(resource *appengine.DomainMapping) *appenginepb.AppengineDomainMapping {\n\tp := &appenginepb.AppengineDomainMapping{\n\t\tSelfLink: dcl.ValueOrEmptyString(resource.SelfLink),\n\t\tName: dcl.ValueOrEmptyString(resource.Name),\n\t\tSslSettings: AppengineDomainMappingSslSettingsToProto(resource.SslSettings),\n\t\tApp: dcl.ValueOrEmptyString(resource.App),\n\t}\n\tfor _, r := range resource.ResourceRecords {\n\t\tp.ResourceRecords = append(p.ResourceRecords, AppengineDomainMappingResourceRecordsToProto(&r))\n\t}\n\n\treturn p\n}", "func (fieldMask *MetricSelector_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}", "func (fieldMask *BatchGetServicesRequest_FieldMask) ToProtoFieldMask() *fieldmaskpb.FieldMask {\n\tprotoFieldMask := &fieldmaskpb.FieldMask{}\n\tfor _, path := range fieldMask.Paths {\n\t\tprotoFieldMask.Paths = append(protoFieldMask.Paths, path.String())\n\t}\n\treturn protoFieldMask\n}" ]
[ "0.7775685", "0.69496596", "0.67862177", "0.66381854", "0.66279733", "0.6605977", "0.6603572", "0.65668726", "0.6514659", "0.6494565", "0.6482546", "0.64253646", "0.6416292", "0.63974524", "0.6359205", "0.6348943", "0.63153917", "0.6254846", "0.6254846", "0.625118", "0.6216999", "0.6172249", "0.6172249", "0.6170846", "0.61336756", "0.6104629", "0.6089235", "0.60849005", "0.6083135", "0.6073853", "0.6061692", "0.60578907", "0.6049848", "0.6043088", "0.60396224", "0.60171056", "0.60171056", "0.60149276", "0.60147595", "0.60124606", "0.5985934", "0.5983921", "0.59747905", "0.5974301", "0.59715927", "0.59663475", "0.5913808", "0.5912271", "0.59088206", "0.59084177", "0.5908028", "0.5905813", "0.5904916", "0.5893491", "0.5888388", "0.58868736", "0.5886584", "0.58769304", "0.5875215", "0.5860714", "0.5860234", "0.5851344", "0.584712", "0.5845735", "0.58435345", "0.5841453", "0.58411163", "0.5839264", "0.5836013", "0.58318496", "0.5826729", "0.5823583", "0.5820342", "0.5817689", "0.5815682", "0.5811543", "0.5807136", "0.58042294", "0.5802598", "0.5790665", "0.5789907", "0.57852834", "0.5783965", "0.5782819", "0.57698834", "0.57684606", "0.5766641", "0.5757196", "0.5754712", "0.5752745", "0.5752745", "0.57472825", "0.5743704", "0.5743002", "0.57359415", "0.57313776", "0.5722438", "0.5717413", "0.57093996", "0.5703294" ]
0.58804363
57
DeserializeBlockStoresPb decode byte stream into BlockStores pb message
func DeserializeBlockStoresPb(buf []byte) (*iotextypes.BlockStores, error) { pbStores := &iotextypes.BlockStores{} if err := proto.Unmarshal(buf, pbStores); err != nil { return nil, err } return pbStores, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (bm *BlockMeta) Deserialize(buf []byte) error {\n\tepochMetapb := &blockmetapb.BlockMeta{}\n\tif err := proto.Unmarshal(buf, epochMetapb); err != nil {\n\t\treturn errors.Wrap(err, \"failed to unmarshal blocklist\")\n\t}\n\treturn bm.LoadProto(epochMetapb)\n}", "func (b *Block) FromBytes(bits []byte) error {\n\tvar rb RawBlock\n\terr := proto.Unmarshal(bits, &rb)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttxs := make([]*Tx, len(rb.Transactions))\n\tvar eg errgroup.Group\n\tfor i := range rb.Transactions {\n\t\ti := i\n\t\teg.Go(func() error {\n\t\t\ttx, err := NewTx(rb.Transactions[i].Program, rb.Transactions[i].Version, rb.Transactions[i].Runlimit)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif !tx.Finalized {\n\t\t\t\treturn txvm.ErrUnfinalized\n\t\t\t}\n\t\t\ttxs[i] = tx\n\t\t\treturn nil\n\t\t})\n\t}\n\terr = eg.Wait()\n\tif err != nil {\n\t\treturn err\n\t}\n\tb.UnsignedBlock = &UnsignedBlock{\n\t\tBlockHeader: rb.Header,\n\t\tTransactions: txs,\n\t}\n\tfor _, arg := range rb.Arguments {\n\t\tswitch arg.Type {\n\t\tcase DataType_BYTES:\n\t\t\tb.Arguments = append(b.Arguments, arg.Bytes)\n\t\tcase DataType_INT:\n\t\t\tb.Arguments = append(b.Arguments, arg.Int)\n\t\tcase DataType_TUPLE:\n\t\t\tb.Arguments = append(b.Arguments, arg.Tuple)\n\t\t}\n\t}\n\treturn nil\n}", "func (in *Store) ToProto() *iotextypes.BlockStore {\n\treceipts := []*iotextypes.Receipt{}\n\tfor _, r := range in.Receipts {\n\t\treceipts = append(receipts, r.ConvertToReceiptPb())\n\t}\n\treturn &iotextypes.BlockStore{\n\t\tBlock: in.Block.ConvertToBlockPb(),\n\t\tReceipts: receipts,\n\t}\n}", "func DeserializeBlock(d []byte) *Block {\n\n\tblock := &Block{}\n\n\terr := proto.Unmarshal(d, block)\n\tif err != nil {\n\t\tlog.Println(\"block-deserialize: protobuf decoding error: \", err)\n\t}\n\n\treturn block\n\n}", "func deserializeBlockUndoData(b []byte) ([]UndoTicketData, error) {\n\tif b != nil && len(b) == 0 {\n\t\treturn make([]UndoTicketData, 0), nil\n\t}\n\n\tif len(b) < undoTicketDataSize {\n\t\treturn nil, ticketDBError(ErrUndoDataShortRead, \"short read when \"+\n\t\t\t\"deserializing block undo data\")\n\t}\n\n\tif len(b)%undoTicketDataSize != 0 {\n\t\treturn nil, ticketDBError(ErrUndoDataCorrupt, \"corrupt data found \"+\n\t\t\t\"when deserializing block undo data\")\n\t}\n\n\tentries := len(b) / undoTicketDataSize\n\tutds := make([]UndoTicketData, entries)\n\n\toffset := 0\n\tfor i := 0; i < entries; i++ {\n\t\thash, err := chainhash.NewHash(\n\t\t\tb[offset : offset+chainhash.HashSize])\n\t\tif err != nil {\n\t\t\treturn nil, ticketDBError(ErrUndoDataCorrupt, \"corrupt hash found \"+\n\t\t\t\t\"when deserializing block undo data\")\n\t\t}\n\t\toffset += chainhash.HashSize\n\n\t\theight := dbnamespace.ByteOrder.Uint32(b[offset : offset+4])\n\t\toffset += 4\n\n\t\tmissed, revoked, spent, expired := undoBitFlagsFromByte(b[offset])\n\t\toffset++\n\n\t\tutds[i] = UndoTicketData{\n\t\t\tTicketHash: *hash,\n\t\t\tTicketHeight: height,\n\t\t\tMissed: missed,\n\t\t\tRevoked: revoked,\n\t\t\tSpent: spent,\n\t\t\tExpired: expired,\n\t\t}\n\t}\n\n\treturn utds, nil\n}", "func (u *UndoBlock) Deserialize(r io.Reader) error {\n\terr := binary.Read(r, binary.BigEndian, &u.numAdds)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar posCount uint64\n\terr = binary.Read(r, binary.BigEndian, &posCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\tu.positions = make([]uint64, posCount)\n\n\terr = binary.Read(r, binary.BigEndian, u.positions)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar hashCount uint64\n\terr = binary.Read(r, binary.BigEndian, &hashCount)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.hashes = make([]Hash, hashCount)\n\n\tfor i := uint64(0); i < hashCount; i++ {\n\t\tn, err := r.Read(u.hashes[i][:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif n != 32 {\n\t\t\terr := fmt.Errorf(\"UndoBlock Deserialize supposed to read 32 bytes but read %d bytes\", n)\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (msg *Block) Deserialize(r io.Reader) (e error) {\n\t// At the current time, there is no difference between the wire encoding at\n\t// protocol version 0 and the stable long-term storage format. As a result, make\n\t// use of BtcDecode. Passing an encoding type of WitnessEncoding to BtcEncode\n\t// for the MessageEncoding parameter indicates that the transactions within the\n\t// block are expected to be serialized according to the new serialization\n\t// structure defined in BIP0141.\n\treturn msg.BtcDecode(r, 0, BaseEncoding)\n}", "func NewStoreFromProtos(msgs ...proto.Message) *Store {\n\ts := NewStore()\n\tfor _, msg := range msgs {\n\t\tany, err := anypb.New(msg)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\n\t\trecord := new(databroker.Record)\n\t\trecord.ModifiedAt = timestamppb.Now()\n\t\trecord.Version = cryptutil.NewRandomUInt64()\n\t\trecord.Id = uuid.New().String()\n\t\trecord.Data = any\n\t\trecord.Type = any.TypeUrl\n\t\tif hasID, ok := msg.(interface{ GetId() string }); ok {\n\t\t\trecord.Id = hasID.GetId()\n\t\t}\n\n\t\ts.UpdateRecord(record)\n\t}\n\treturn s\n}", "func (bh *BlockHeader) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the protos encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of readBlockHeader.\n\tif err := serialization.ReadUint32(r, (*uint32)(unsafe.Pointer(&bh.Version))); err != nil {\n\t\treturn err\n\t}\n\tif err := serialization.ReadNBytes(r, bh.PrevBlock[:], common.HashLength); err != nil {\n\t\treturn err\n\t}\n\tif err := serialization.ReadNBytes(r, bh.MerkleRoot[:], common.HashLength); err != nil {\n\t\treturn err\n\t}\n\tif err := serialization.ReadUint64(r, (*uint64)(unsafe.Pointer(&bh.Timestamp))); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadNBytes(r, bh.StateRoot[:], common.HashLength); err != nil {\n\t\treturn err\n\t}\n\tif err := serialization.ReadUint64(r, &bh.GasLimit); err != nil {\n\t\treturn err\n\t}\n\tif err := serialization.ReadUint64(r, &bh.GasUsed); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadUint32(r, &bh.Round); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadUint16(r, &bh.SlotIndex); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadUint16(r, &bh.Weight); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadNBytes(r, bh.PoaHash[:], common.HashLength); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadUint32(r, (*uint32)(unsafe.Pointer(&bh.Height))); err != nil {\n\t\treturn err\n\t}\n\n\tif err := serialization.ReadNBytes(r, bh.CoinBase[:], common.AddressLength); err != nil {\n\t\treturn err\n\t}\n\n\terr := serialization.ReadNBytes(r, bh.SigData[:], HashSignLen)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func Deserialize(buffer []byte) *block {\n\tvar b block\n\tdecoder := gob.NewDecoder(bytes.NewReader(buffer)) // convert []byte to io.Reader\n\terr := decoder.Decode(&b) // here b is the dest\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\treturn &b\n}", "func DeserializeBlock(serializedBlock []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(serializedBlock))\n\tdecoder.Decode(&block)\n\n\treturn &block\n}", "func Deserialize(data []byte) *Block {\n\tvar block Block\n\tdecoder := gob.NewDecoder(bytes.NewReader(data))\n\n\terr := decoder.Decode(&block)\n\n\tHandle(err)\n\n\treturn &block\n\n}", "func DeserializeBlock(encodedBlock []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(encodedBlock))\n\terr := decoder.Decode(&block)\n\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn &block\n}", "func Deserialize(data []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(data))\n\n\terr := decoder.Decode(&block)\n\n\tHandle(err)\n\n\treturn &block\n}", "func Deserialize(data []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(data))\n\n\terr := decoder.Decode(&block)\n\n\tHandle(err)\n\n\treturn &block\n}", "func Deserialize(data []byte) *Block {\n\tvar block Block\n\tdecoder := gob.NewDecoder(bytes.NewReader(data))\n\terr := decoder.Decode(&block)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn &block\n}", "func Parse(s *bytes.Reader) *Block {\n\tblock := new(Block)\n\tbuffer4 := make([]byte, 4)\n\tbuffer32 := make([]byte, 32)\n\ts.Read(buffer4)\n\tblock.Version = util.LittleEndianToInt32(buffer4)\n\ts.Read(buffer32)\n\tcopy(block.PrevBlock[:], util.ReverseByteArray(buffer32))\n\ts.Read(buffer32)\n\tcopy(block.MerkleRoot[:], util.ReverseByteArray(buffer32))\n\ts.Read(buffer4)\n\tblock.Timestamp = util.LittleEndianToInt32(buffer4)\n\ts.Read(buffer4)\n\tcopy(block.Bits[:], buffer4)\n\ts.Read(buffer4)\n\tcopy(block.Nonce[:], buffer4)\n\treturn block\n}", "func DecodeBlock(data []byte) *StBlock {\n\tout := new(StBlock)\n\tout.sign = data[1 : data[0]+1]\n\tbData := data[data[0]+1:]\n\tn := runtime.Decode(bData, &out.Block)\n\tstream := bData[n:]\n\tif len(stream)%HashLen != 0 {\n\t\treturn nil\n\t}\n\tif out.Index < 1 {\n\t\treturn nil\n\t}\n\n\trst := wallet.Recover(out.Producer[:], out.sign, bData)\n\tif !rst {\n\t\tlog.Printf(\"fail to recover block,producer:%x\\n\", out.Producer)\n\t\treturn nil\n\t}\n\th := runtime.GetHash(data)\n\truntime.Decode(h, &out.Key)\n\n\treturn out\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func (h *BlockHeader) Deserialize(r io.Reader) error { //TODO parse blockheader data\n\t// At the current time, there is no difference between the wire encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of readBlockHeader.\n\treturn nil\n}", "func FromBytes(byteData []byte) (Data, error) {\n\tvar data Data\n\tif err := yaml.Unmarshal(byteData, &data); err != nil {\n\t\treturn data, fmt.Errorf(\"could not unmarshal config data: %w\", err)\n\t}\n\treturn data, nil\n}", "func (eb *EBlock) UnmarshalBinary(data []byte) error {\n\tif len(data) < EBlockMinTotalLen {\n\t\treturn fmt.Errorf(\"insufficient length\")\n\t}\n\tif len(data) > EBlockMaxTotalLen {\n\t\treturn fmt.Errorf(\"invalid length\")\n\t}\n\tif eb.ChainID == nil {\n\t\teb.ChainID = new(Bytes32)\n\t}\n\teb.ChainID = eb.ChainID\n\ti := copy(eb.ChainID[:], data[:len(eb.ChainID)])\n\teb.BodyMR = new(Bytes32)\n\ti += copy(eb.BodyMR[:], data[i:i+len(eb.BodyMR)])\n\teb.PrevKeyMR = new(Bytes32)\n\ti += copy(eb.PrevKeyMR[:], data[i:i+len(eb.PrevKeyMR)])\n\teb.PrevFullHash = new(Bytes32)\n\ti += copy(eb.PrevFullHash[:], data[i:i+len(eb.PrevFullHash)])\n\teb.Sequence = binary.BigEndian.Uint32(data[i : i+4])\n\ti += 4\n\teb.Height = binary.BigEndian.Uint32(data[i : i+4])\n\ti += 4\n\teb.ObjectCount = binary.BigEndian.Uint32(data[i : i+4])\n\ti += 4\n\tif len(data[i:]) != int(eb.ObjectCount*32) {\n\t\treturn fmt.Errorf(\"invalid length\")\n\t}\n\n\t// Parse all objects into Bytes32\n\tobjects := make([]Bytes32, eb.ObjectCount)\n\tmaxMinute := Bytes32{31: 10}\n\tvar numMins int\n\tfor oi := range objects {\n\t\tobj := &objects[len(objects)-1-oi] // Reverse object order\n\t\ti += copy(obj[:], data[i:i+len(obj)])\n\t\tif bytes.Compare(obj[:], maxMinute[:]) <= 0 {\n\t\t\tnumMins++\n\t\t}\n\t}\n\tif bytes.Compare(objects[0][:], maxMinute[:]) > 0 {\n\t\treturn fmt.Errorf(\"invalid minute marker\")\n\t}\n\n\t// Populate Entries from objects.\n\teb.Entries = make([]Entry, int(eb.ObjectCount)-numMins)\n\tei := len(eb.Entries) - 1\n\tvar ts time.Time\n\tfor _, obj := range objects {\n\t\tif bytes.Compare(obj[:], maxMinute[:]) <= 0 {\n\t\t\tts = eb.Timestamp.\n\t\t\t\tAdd(time.Duration(obj[31]) * time.Minute)\n\t\t\tcontinue\n\t\t}\n\t\te := &eb.Entries[ei]\n\t\te.Timestamp = ts\n\t\te.ChainID = eb.ChainID\n\t\te.Height = eb.Height\n\t\tobj := obj\n\t\te.Hash = &obj\n\t\tei--\n\t}\n\treturn nil\n}", "func BlockFromProto(bp *tmproto.Block) (*Block, error) {\n\tif bp == nil {\n\t\treturn nil, errors.New(\"nil block\")\n\t}\n\n\tb := new(Block)\n\th, err := HeaderFromProto(&bp.Header)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Header = h\n\tdata, err := DataFromProto(&bp.Data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tb.Data = data\n\tif err := b.Evidence.FromProto(&bp.Evidence); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcoreChainLock, err := CoreChainLockFromProto(bp.CoreChainLock)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tb.CoreChainLock = coreChainLock\n\n\tif bp.LastCommit != nil {\n\t\tlc, err := CommitFromProto(bp.LastCommit)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tb.LastCommit = lc\n\t}\n\n\treturn b, b.ValidateBasic()\n}", "func ParseBytes(b []byte) (*Config, error) {\n\tout := new(Config)\n\terr := yaml.Unmarshal(b, out)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn out, nil\n}", "func DeserializeBlock(d []byte) *Block {\n\tvar block Block\n\tdecoder := gob.NewDecoder(bytes.NewReader(d))\n\tdecoder.Decode(&block)\n\treturn &block\n}", "func parseBlocks(r *bufio.Reader, s *SOR) error {\n\tvar mb Block\n\tmb.ID = \"Map\"\n\n\t// no map is 'Map' on v1 so skip past it\n\tif s.Version == SORv2 {\n\t\t_, _ = readNBytes(r, 4)\n\t}\n\n\tbinary.Read(r, binary.LittleEndian, &mb.Version)\n\tbinary.Read(r, binary.LittleEndian, &mb.Bytes)\n\n\tvar blocks int16\n\tbinary.Read(r, binary.LittleEndian, &blocks)\n\n\ts.Blocks = append(s.Blocks, mb)\n\n\t// parse remaining blocks\n\tfor i := 1; i < int(blocks); i++ {\n\t\tvar m Block\n\t\tblock_name, _ := r.ReadBytes('\\x00')\n\t\tm.ID = string(bytes.Trim(block_name, \"\\x00\"))\n\t\tbinary.Read(r, binary.LittleEndian, &m.Version)\n\t\tbinary.Read(r, binary.LittleEndian, &m.Bytes)\n\t\ts.Blocks = append(s.Blocks, m)\n\t}\n\n\treturn nil\n}", "func DeserializeBlock(d []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(d))\n\terr := decoder.Decode(&block)\n\n\treturn &block\n}", "func DeserializeBlock(d []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(d))\n\tdecoder.Decode(&block)\n\n\treturn &block\n}", "func ReadConfigFromByteArray(configYaml []byte) *Config {\n\tc := &Config{}\n\n\terr := yaml.Unmarshal(configYaml, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"Invalid configuration: %v\", err)\n\t\treturn nil\n\t}\n\n\tc.Vars.init()\n\treturn c\n}", "func LoadFromBytes(raw []byte) (Mapper, error) {\n\t// Handle studybox files\n\tif bytes.Equal(raw[:4], []byte(\"STBX\")) {\n\t\treturn NewStudyBox(raw, true)\n\t}\n\n\theader, err := ines.ParseHeader(raw)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// TODO: NES2 submapper IDs\n\tinit, exists := availableMappers[int(header.Mapper)]\n\tif !exists {\n\t\treturn nil, fmt.Errorf(\"Mapper with ID %d not implemented\")\n\t}\n\n\t// Assume all mappers have PRGRAM until parsing this info from a\n\t// NES2 header is implemented.\n\treturn init(raw[16:int(header.PrgSize+16)], true)\n}", "func (p *PCOPayload) DecodeFromBytes(b []byte) error {\r\n\tp.ConfigurationProtocol = b[0] & 0x07\r\n\r\n\toffset := 1\r\n\tfor {\r\n\t\tif offset >= len(b) {\r\n\t\t\treturn nil\r\n\t\t}\r\n\t\topt, err := DecodeConfigurationProtocolOption(b[offset:])\r\n\t\tif err != nil {\r\n\t\t\treturn err\r\n\t\t}\r\n\t\tp.ConfigurationProtocolOptions = append(p.ConfigurationProtocolOptions, opt)\r\n\t}\r\n}", "func DockstoreComposeFromBytes(yamlBytes []byte) (model *ComposeFull, err error) {\n\tmodel = &ComposeFull{}\n\terr = yaml.Unmarshal(yamlBytes, model)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\treturn model, model.Sanitize()\n}", "func deserializeSStxRecord(serializedSStxRecord []byte, dbVersion uint32) (*sstxRecord, error) {\n\tswitch {\n\tcase dbVersion < 3:\n\t\trecord := new(sstxRecord)\n\n\t\tcurPos := 0\n\n\t\t// Read MsgTx size (as a uint64).\n\t\tmsgTxLen := int(binary.LittleEndian.Uint64(\n\t\t\tserializedSStxRecord[curPos : curPos+int64Size]))\n\t\tcurPos += int64Size\n\n\t\t// Pretend to read the pkScrLoc for the 0th output pkScript.\n\t\tcurPos += int32Size\n\n\t\t// Read the intended voteBits and extended voteBits length (uint8).\n\t\trecord.voteBitsSet = false\n\t\tvoteBitsLen := int(serializedSStxRecord[curPos])\n\t\tif voteBitsLen != 0 {\n\t\t\trecord.voteBitsSet = true\n\t\t}\n\t\tcurPos += int8Size\n\n\t\t// Read the assumed 2 byte VoteBits as well as the extended\n\t\t// votebits (75 bytes max).\n\t\trecord.voteBits = binary.LittleEndian.Uint16(\n\t\t\tserializedSStxRecord[curPos : curPos+int16Size])\n\t\tcurPos += int16Size\n\t\tif voteBitsLen != 0 {\n\t\t\trecord.voteBitsExt = make([]byte, voteBitsLen-int16Size)\n\t\t\tcopy(record.voteBitsExt, serializedSStxRecord[curPos:curPos+voteBitsLen-int16Size])\n\t\t}\n\t\tcurPos += stake.MaxSingleBytePushLength - int16Size\n\n\t\t// Prepare a buffer for the msgTx.\n\t\tbuf := bytes.NewBuffer(serializedSStxRecord[curPos : curPos+msgTxLen])\n\t\tcurPos += msgTxLen\n\n\t\t// Deserialize transaction.\n\t\tmsgTx := new(wire.MsgTx)\n\t\terr := msgTx.Deserialize(buf)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, io.EOF) {\n\t\t\t\terr = io.ErrUnexpectedEOF\n\t\t\t}\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create and save the dcrutil.Tx of the read MsgTx and set its index.\n\t\ttx := dcrutil.NewTx(msgTx)\n\t\ttx.SetIndex(dcrutil.TxIndexUnknown)\n\t\ttx.SetTree(wire.TxTreeStake)\n\t\trecord.tx = tx\n\n\t\t// Read received unix time (int64).\n\t\treceived := int64(binary.LittleEndian.Uint64(\n\t\t\tserializedSStxRecord[curPos : curPos+int64Size]))\n\t\trecord.ts = time.Unix(received, 0)\n\n\t\treturn record, nil\n\n\tcase dbVersion >= 3:\n\t\t// Don't need to read the pkscript location, so first four bytes are\n\t\t// skipped.\n\t\tserializedSStxRecord = serializedSStxRecord[4:]\n\n\t\tvar tx wire.MsgTx\n\t\terr := tx.Deserialize(bytes.NewReader(serializedSStxRecord))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tunixTime := int64(binary.LittleEndian.Uint64(serializedSStxRecord[tx.SerializeSize():]))\n\t\treturn &sstxRecord{tx: dcrutil.NewTx(&tx), ts: time.Unix(unixTime, 0)}, nil\n\n\tdefault:\n\t\tpanic(\"unreachable\")\n\t}\n}", "func DeserializeBlock(d []byte) *Block {\n\tvar block Block\n\n\tdecoder := gob.NewDecoder(bytes.NewReader(d))\n\terr := decoder.Decode(&block)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn &block\n}", "func FromBytes(b []byte) (*raft.Log, error) {\n\tvar l raft.Log\n\tif len(b) == 0 {\n\t\treturn nil, fmt.Errorf(\"invalid raft.Log message: 0 bytes\")\n\t}\n\tif b[0] == 'p' {\n\t\tvar p pb.RaftLog\n\t\tif err := proto.Unmarshal(b[1:], &p); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tl.Index = p.Index\n\t\tl.Term = p.Term\n\t\tl.Type = raft.LogType(p.Type)\n\t\tl.Data = p.Data\n\t\tl.Extensions = p.Extensions\n\t} else {\n\t\t// XXX(1.0): delete this branch, proto is used everywhere\n\t\tif err := json.Unmarshal(b, &l); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn &l, nil\n}", "func (bc BlockChain) deserializeBlock(o []byte) *Block {\r\n\tif !json.Valid(o) {\r\n\t\tpanic(\"Input is not a valid json object for block\")\r\n\t}\r\n\r\n\tvar jsonBlock Block\r\n\tvar b Block\r\n\t/**\r\n\tdec := json.NewDecoder(strings.NewReader(string(\to)))\r\n\tif err := dec.Decode(&jsonBlock); err == io.EOF {\r\n\t} else if err != nil {\r\n\t\tlog.Fatal(err)\r\n\t}\r\n\t**/\r\n\terr := json.Unmarshal(o, &jsonBlock)\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n\t//fmt.Println(\"new block is \" + jsonBlock.Serialize())\r\n\r\n\tbalances := make(map[string]int)\r\n\tchainLength := jsonBlock.ChainLength\r\n\ttimestamp := jsonBlock.Timestamp\r\n\r\n\tif jsonBlock.IsGenesisBlock() {\r\n\t\t//fmt.Println(\"setting balances\")\r\n\t\t//fmt.Println(jsonBlock.Balances)\r\n\t\tfor client, amount := range jsonBlock.Balances {\r\n\t\t\tbalances[client] = amount\r\n\t\t}\r\n\t\tb.Balances = balances\r\n\t} else {\r\n\t\tprevBlockHash := jsonBlock.PrevBlockHash\r\n\t\tproof := jsonBlock.Proof\r\n\t\trewardAddr := jsonBlock.RewardAddr\r\n\t\ttransactions := make(map[string]*Transaction)\r\n\t\tif jsonBlock.Transactions != nil {\r\n\t\t\tfor id, tx := range jsonBlock.Transactions {\r\n\t\t\t\ttransactions[id] = tx\r\n\t\t\t}\r\n\t\t}\r\n\t\t//GOTTA FIX THIS WHEN YOU IMPLEMENT CONSTANTS\r\n\t\tb = *bc.MakeBlock(rewardAddr, nil, nil, nil)\r\n\t\tb.ChainLength = chainLength\r\n\t\tb.Timestamp = timestamp\r\n\t\tb.PrevBlockHash = prevBlockHash\r\n\t\tb.Proof = proof\r\n\t\tb.Transactions = transactions\r\n\t}\r\n\treturn &b\r\n}", "func (pd *pymtData) Deserialize(b []byte) error {\n\terr := json.Unmarshal(b, pd)\n\tif err != nil {\n\t\treturn errors.Wrap(err, ErrInvalidFormatBlob)\n\t}\n\n\treturn nil\n}", "func (b *MicroBlock) Deserialize(r io.Reader) error {\n return readBlock(r, 0, b)\n}", "func (msg *Message) ParseBytes(data []byte) error {\n\t// Frame header\n\n\terr := msg.parseFrameHeaderBytes(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Echonet Format1 Header\n\n\terr = msg.parseFormat1HeaderBytes(data[FrameHeaderSize:])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Propety data\n\n\terr = msg.parseFormat1PropertyBytes(data[Format1MinSize:])\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *BlockHeader) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the wire encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of readBlockHeader.\n\treturn readBlockHeader(r, 0, h)\n}", "func (h *BlockHeader) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the wire encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of readBlockHeader.\n\treturn readBlockHeader(r, 0, h)\n}", "func (wcm *WzGenericMessage) LoadBytes(data []byte) error {\n\treturn msgpack.Unmarshal(data, wcm)\n}", "func BlockFromBytes(data []byte) (Block, error) {\n\tvar b Block\n\treturn b, encoder.DeserializeRaw(data, &b)\n}", "func NewBlockFromBytes(b []byte) (*Block, error) {\r\n\tif len(b) == 0 {\r\n\t\treturn nil, errors.New(\"block cannot be empty\")\r\n\t}\r\n\r\n\tvar offset int\r\n\tbh, err := NewBlockHeaderFromBytes(b[:80])\r\n\tif err != nil {\r\n\t\treturn nil, err\r\n\t}\r\n\toffset += 80\r\n\r\n\ttxCount, size := bt.DecodeVarInt(b[offset:])\r\n\toffset += size\r\n\r\n\tvar txs []*bt.Tx\r\n\tfor i := 0; i < int(txCount); i++ {\r\n\t\ttx, size, err := bt.NewTxFromStream(b[offset:])\r\n\t\tif err != nil {\r\n\t\t\treturn nil, err\r\n\t\t}\r\n\t\ttxs = append(txs, tx)\r\n\t\toffset += size\r\n\t}\r\n\r\n\treturn &Block{\r\n\t\tBlockHeader: bh,\r\n\t\tTxs: txs,\r\n\t}, nil\r\n}", "func (p *Parser) LoadFromBytes(buffer []byte, filetype string) error {\n\tp.Viper.SetConfigType(filetype)\n\tp.defaults()\n\tif err := p.Viper.ReadConfig(bytes.NewBuffer(buffer)); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (flush *FuseFlushIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 24 {\n\t\treturn ErrDataLen\n\t}\n\n\tcommon.ParseBinary(bcontent, flush)\n\n\treturn nil\n}", "func deserializeOutpoints(serializedOuts []btcjson.OutPoint) ([]*wire.OutPoint, error) {\n\toutpoints := make([]*wire.OutPoint, 0, len(serializedOuts))\n\tfor i := range serializedOuts {\n\t\tblockHash, err := chainhash.NewHashFromStr(serializedOuts[i].Hash)\n\t\tif err != nil {\n\t\t\treturn nil, rpcDecodeHexError(serializedOuts[i].Hash)\n\t\t}\n\t\tindex := serializedOuts[i].Index\n\t\toutpoints = append(outpoints, wire.NewOutPoint(blockHash, index))\n\t}\n\n\treturn outpoints, nil\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\t// ph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\n\t// blockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func DeserializeBlock(d []byte) *Block1 {\n\tvar block Block1 \n\n\tdecoder := gob.NewDecoder(bytes.NewReader(d))\n\terr := decoder.Decode(&block)\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n\n\treturn &block\n}", "func (txn *Transaction) Deserialize(gobdata utils.Gob) {\n\t// Decode the gob data into the blockheader\n\tutils.GobDecode(gobdata, txn)\n}", "func ParseBytes(b []byte) ([]byte, error) {\n\treturn ParseString(string(b))\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\tph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func BlockIDFromProto(bID *tmproto.BlockID) (*BlockID, error) {\n\tif bID == nil {\n\t\treturn nil, errors.New(\"nil BlockID\")\n\t}\n\n\tblockID := new(BlockID)\n\tph, err := PartSetHeaderFromProto(&bID.PartSetHeader)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tblockID.PartSetHeader = *ph\n\tblockID.Hash = bID.Hash\n\n\treturn blockID, blockID.ValidateBasic()\n}", "func ParseBytes(b []byte) (Sections, error) {\n\ttree, err := ParseASTBytes(b)\n\tif err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\tv := NewDefaultVisitor()\n\tif err = Walk(tree, v); err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\treturn v.Sections, nil\n}", "func ParseBytes(b []byte) (Sections, error) {\n\ttree, err := ParseASTBytes(b)\n\tif err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\tv := NewDefaultVisitor()\n\tif err = Walk(tree, v); err != nil {\n\t\treturn Sections{}, err\n\t}\n\n\treturn v.Sections, nil\n}", "func receiveBlock(ws *WrappedStream) (*Block, error) {\n\tvar block Block\n\terr := ws.dec.Decode(&block)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"unable to read block from stream\")\n\t}\n\treturn &block, nil\n}", "func BlockDecode(packed []byte, number uint64, decodeTxs bool) (*blockResult, error) {\n\n\tbr := blockrecord.Get()\n\n\theader, digest, data, err := br.ExtractHeader(packed, number, false)\n\tif nil != err {\n\t\treturn nil, err\n\t}\n\n\tif !decodeTxs {\n\t\tresult := &blockResult{\n\t\t\tDigest: &digest,\n\t\t\tHeader: header,\n\t\t\tTransactions: nil,\n\t\t\tPacked: packed,\n\t\t}\n\n\t\treturn result, nil\n\t}\n\n\ttxs := make([]transactionItem, header.TransactionCount)\nloop:\n\tfor i := 1; true; i += 1 {\n\t\ttransaction, n, err := transactionrecord.Packed(data).Unpack(mode.IsTesting())\n\t\tif nil != err {\n\t\t\treturn nil, err\n\t\t}\n\t\tname, _ := transactionrecord.RecordName(transaction)\n\t\ttxs[i-1] = transactionItem{\n\t\t\tIndex: i,\n\t\t\tTxId: merkle.NewDigest(data[:n]),\n\t\t\tType: name,\n\t\t\tData: transaction,\n\t\t}\n\t\tdata = data[n:]\n\t\tif 0 == len(data) {\n\t\t\tbreak loop\n\t\t}\n\t}\n\n\tresult := &blockResult{\n\t\tDigest: &digest,\n\t\tHeader: header,\n\t\tTransactions: txs,\n\t\tPacked: packed,\n\t}\n\n\treturn result, nil\n}", "func decodeMessage(bz []byte) (msgType byte, msg interface{}) {\n\tn, err := new(int64), new(error)\n\t// log.Debug(\"decoding msg bytes: %X\", bz)\n\tmsgType = bz[0]\n\tswitch msgType {\n\tcase msgTypeBlockPart:\n\t\tmsg = readBlockPartMessage(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeKnownBlockParts:\n\t\tmsg = readKnownBlockPartsMessage(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVote:\n\t\tmsg = ReadVote(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVoteAskRank:\n\t\tmsg = ReadVote(bytes.NewReader(bz[1:]), n, err)\n\tcase msgTypeVoteRank:\n\t\tmsg = readVoteRankMessage(bytes.NewReader(bz[1:]), n, err)\n\tdefault:\n\t\tmsg = nil\n\t}\n\treturn\n}", "func ParseBytes(data []byte) (Config, error) {\n\tc, err := parseConfig(data)\n\tif err != nil {\n\t\treturn Config{}, err\n\t}\n\treturn c, nil\n}", "func (block *Block) Parse(reader *bytes.Reader) *Block {\n\tbuffer4 := make([]byte, 4)\n\tbuffer32 := make([]byte, 32)\n\treader.Read(buffer4)\n\tblock.Version = util.LittleEndianToInt32(buffer4)\n\treader.Read(buffer32)\n\tcopy(block.PrevBlock[:32], util.ReverseByteArray(buffer32))\n\treader.Read(buffer32)\n\tcopy(block.MerkleRoot[:32], util.ReverseByteArray(buffer32))\n\treader.Read(buffer4)\n\tblock.Timestamp = util.LittleEndianToInt32(buffer4)\n\treader.Read(buffer4)\n\tcopy(block.Bits[:4], buffer4)\n\treader.Read(buffer4)\n\tcopy(block.Nonce[:4], buffer4)\n\treader.Read(buffer4)\n\tblock.Total = util.LittleEndianToInt32(buffer4)\n\tnumHashes := util.ReadVarInt(reader)\n\thashes := make([][]byte, numHashes)\n\tfor i := range hashes {\n\t\treader.Read(buffer32)\n\t\thashes[i] = make([]byte, 32)\n\t\tcopy(hashes[i], util.ReverseByteArray(buffer32))\n\t}\n\tblock.Hashes = hashes\n\tflagLength := util.ReadVarInt(reader)\n\tblock.Flags = make([]byte, flagLength)\n\treader.Read(block.Flags)\n\treturn block\n}", "func ParseValidationBlock(contents []byte) (ValidationMap, error) {\n\tblock := ValidationMap{}\n\terr := yaml.Unmarshal(contents, &block)\n\treturn block, err\n}", "func (bm *BlockMeta) LoadProto(pb *blockmetapb.BlockMeta) error {\n\tif err := pb.GetBlockTime().CheckValid(); err != nil {\n\t\treturn err\n\t}\n\tmintTime := pb.GetBlockTime().AsTime()\n\tbm.Height = pb.GetBlockHeight()\n\tbm.Producer = pb.GetBlockProducer()\n\tbm.MintTime = mintTime.UTC()\n\treturn nil\n}", "func ParseMerkleBlock(merkleblockdump string) *MerkleBlock {\n\tbuf, err := hex.DecodeString(merkleblockdump)\n\tif err != nil {\n\t\tfmt.Println(\"Failed to parse decode merkleblock string into bytes\")\n\t}\n\t// Empty variables to hold the values\n\tvar Version [4]byte\n\tvar PrevBlock [32]byte\n\tvar MerkleRoot [32]byte\n\tvar TimeStamp [4]byte\n\tvar Bits [4]byte\n\tvar Nonce [4]byte\n\tvar Total [4]byte\n\t// Copy from the txDump bytearray\n\tverBuf := buf[0:4]\n\tprevBlkBuf := buf[4:36]\n\tmerkleRootBuf := buf[36:68]\n\ttimeStampBuf := buf[68:72]\n\tbitBuf := buf[72:76]\n\tnonceBuf := buf[76:80]\n\ttotalBuf := buf[80:84]\n\n\tutils.Reverse(&verBuf)\n\tutils.Reverse(&prevBlkBuf)\n\tutils.Reverse(&merkleRootBuf)\n\tutils.Reverse(&timeStampBuf)\n\tutils.Reverse(&totalBuf)\n\n\tcopy(Version[:], verBuf)\n\tcopy(PrevBlock[:], prevBlkBuf)\n\tcopy(MerkleRoot[:], merkleRootBuf)\n\tcopy(TimeStamp[:], timeStampBuf)\n\tcopy(Bits[:], bitBuf)\n\tcopy(Nonce[:], nonceBuf)\n\tcopy(Total[:], totalBuf)\n\n\t// Now handle the hashes\n\tnumHashes, newString := utils.ReadVarInt(hex.EncodeToString(buf[84:]))\n\t// Empty array to hold the hashes\n\thashesBuf := [][32]byte{}\n\tfor i := uint64(0); i < numHashes; i++ {\n\t\trawBytes, _ := hex.DecodeString(newString)\n\t\t// 32byte bytearray to hold the raw bytes\n\t\tvar tempHashBuf [32]byte\n\t\ttempHash := rawBytes[:32]\n\t\tutils.Reverse(&tempHash)\n\t\tcopy(tempHashBuf[:], tempHash)\n\t\thashesBuf = append(hashesBuf, tempHashBuf)\n\t\t// need to change new string\n\t\tnewString = hex.EncodeToString(rawBytes[32:])\n\t}\n\tflagLength, newString := utils.ReadVarInt(newString)\n\tnewStringBytes, _ := hex.DecodeString(newString)\n\tflag := newStringBytes[:flagLength]\n\treturn &MerkleBlock{\n\t\tVersion,\n\t\tPrevBlock,\n\t\tMerkleRoot,\n\t\tTimeStamp,\n\t\tBits,\n\t\tNonce,\n\t\tTotal,\n\t\thashesBuf,\n\t\tflag,\n\t}\n}", "func (msg *MsgTx) Deserialize(r io.Reader) error {\n\t// At the current time, there is no difference between the protos encoding\n\t// at protocol version 0 and the stable long-term storage format. As\n\t// a result, make use of VVSDecode.\n\treturn msg.VVSDecode(r, 0, BaseEncoding)\n}", "func (c *CloudConfig) LoadFromBytes(content []byte) *CloudConfig {\n\terr := yaml.Unmarshal(content, c)\n\tif err != nil {\n\t\tlog.Fatalf(\"%s\", err)\n\t}\n\treturn c\n}", "func (b *Block) UnmarshalSia(r io.Reader) error {\n\tif build.DEBUG {\n\t\t// Sanity check: compare against the old decoding\n\t\tbuf := new(bytes.Buffer)\n\t\tr = io.TeeReader(r, buf)\n\n\t\tdefer func() {\n\t\t\tcheckB := new(Block)\n\t\t\tif err := encoding.UnmarshalAll(buf.Bytes(),\n\t\t\t\t&checkB.ParentID,\n\t\t\t\t&checkB.Nonce,\n\t\t\t\t&checkB.Timestamp,\n\t\t\t\t&checkB.MinerPayouts,\n\t\t\t\t&checkB.Transactions,\n\t\t\t); err != nil {\n\t\t\t\t// don't check invalid blocks\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif crypto.HashObject(b) != crypto.HashObject(checkB) {\n\t\t\t\tpanic(\"decoding differs!\")\n\t\t\t}\n\t\t}()\n\t}\n\n\td := encoding.NewDecoder(r)\n\td.ReadFull(b.ParentID[:])\n\td.ReadFull(b.Nonce[:])\n\tb.Timestamp = Timestamp(d.NextUint64())\n\t// MinerPayouts\n\tb.MinerPayouts = make([]SiacoinOutput, d.NextPrefix(unsafe.Sizeof(SiacoinOutput{})))\n\tfor i := range b.MinerPayouts {\n\t\tb.MinerPayouts[i].UnmarshalSia(d)\n\t}\n\t// Transactions\n\tb.Transactions = make([]Transaction, d.NextPrefix(unsafe.Sizeof(Transaction{})))\n\tfor i := range b.Transactions {\n\t\tb.Transactions[i].UnmarshalSia(d)\n\t}\n\treturn d.Err()\n}", "func Decode(d []byte) (msgs []*MessageExt, err error) {\n\tbuf := buf.WrapBytes(binary.BigEndian, d)\n\nAGAIN:\n\tif buf.Len() == 0 {\n\t\treturn\n\t}\n\tm := &MessageExt{}\n\tm.StoreSize, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\tbuf.GetInt32() // MagicCode\n\tm.BodyCRC, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tqueueID, err := buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\tm.QueueID = uint8(queueID)\n\n\tm.Flag, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.QueueOffset, err = buf.GetInt64()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.CommitLogOffset, err = buf.GetInt64()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.SysFlag, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.BornTimestamp, err = buf.GetInt64()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbs, err := buf.GetBytes(4)\n\tif err != nil {\n\t\treturn\n\t}\n\tport, err := buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\tm.BornHost.Host, m.BornHost.Port = bs, uint16(port)\n\n\tm.StoreTimestamp, err = buf.GetInt64()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbs, err = buf.GetBytes(4)\n\tif err != nil {\n\t\treturn\n\t}\n\tport, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\tm.StoreHost.Host, m.StoreHost.Port = bs, uint16(port)\n\n\tm.ReconsumeTimes, err = buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.PreparedTransactionOffset, err = buf.GetInt64()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbodyLen, err := buf.GetInt32()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tif bodyLen > 0 {\n\t\tbs, err = buf.GetBytes(int(bodyLen))\n\t\tif (m.SysFlag & Compress) == Compress {\n\t\t\tz, err := zlib.NewReader(bytes.NewReader(bs))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tbs, err = ioutil.ReadAll(z)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tz.Close()\n\t\t}\n\t\tm.Body = bs\n\t}\n\n\ttopicLen, err := buf.GetInt8()\n\tbs, err = buf.GetBytes(int(topicLen))\n\tif err != nil {\n\t\treturn\n\t}\n\tm.Topic = string(bs)\n\n\tpropertiesLen, err := buf.GetInt16()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbs, err = buf.GetBytes(int(propertiesLen))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tm.Properties = String2Properties(string(bs))\n\tm.MsgID = CreateMessageID(&m.StoreHost, m.CommitLogOffset)\n\n\tmsgs = append(msgs, m)\n\tgoto AGAIN\n}", "func FromBytes(rawBytes []byte, p Packet) error {\n\t// interface smuggling\n\tif pp, ok := p.(encoding.BinaryUnmarshaler); ok {\n\t\treturn pp.UnmarshalBinary(rawBytes)\n\t}\n\treader := bytes.NewReader(rawBytes)\n\treturn binary.Read(reader, binary.BigEndian, p)\n}", "func LoadFromYamlBytes(raw []byte, cfg conf.Config) (types.ProjectionMapping, error) {\n\t/**\n\t\tvar aux struct {\n\t\t\tName string `yaml:\"name\"`\n\t\t\tNamespace string `yaml:\"namespace\"`\n\t\t\tData []struct {\n\t\t\t\tName string `yaml:\"name\"`\n\t\t\t\tSource struct {\n\t\t\t\t\tJSON string `yaml:\"json\"`\n\t\t\t\t\tYAML string `yaml:\"yaml\"`\n\t\t\t\t\tRaw string `yaml:\"raw\"`\n\t\t\t\t\tJSONPath string `yaml:\"jsonpath\"`\n\t\t\t\t} `yaml:\"source\"`\n\t\t\t} `yaml:\"data\"`\n\t\t}\n\t **/\n\tvar m ProjectionMapping\n\tm.c = cfg\n\terr := yaml.UnmarshalStrict(raw, &m)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// setup the crypter. if no module requested, skip setting this up (we will bail if any items asked to be\n\t// encrypted but didnt specify the module)\n\tif m.Encryption.Module != \"\" {\n\t\tif m.Encryption.CredsKeysFilePath == \"\" {\n\t\t\t// override with the value from cfg\n\t\t\tm.Encryption.CredsKeysFilePath = cfg.CredsEncryptionKeyFile()\n\t\t}\n\t\tif m.Encryption.KeysDecrypterFilePath == \"\" {\n\t\t\t// override with the value from cfg\n\t\t\tm.Encryption.KeysDecrypterFilePath = cfg.CredsKeyDecryptionKeyFile()\n\t\t}\n\t\tc, err := encryption.NewModuleFromEncryptionConfig(m.Encryption)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tm.crypter = c\n\t}\n\treturn &m, nil\n}", "func (b *OldBlock) DecodeRLP(s *rlp.Stream) error {\n\tvar eb extoldblock\n\t_, size, _ := s.Kind()\n\tif err := s.Decode(&eb); err != nil {\n\t\treturn err\n\t}\n\tb.header, b.uncles, b.currencies = eb.Header, eb.Uncles, eb.Currencies\n\n\tb.size.Store(common.StorageSize(rlp.ListSize(size)))\n\treturn nil\n}", "func (w *Workspace) FromBytes(b []byte) error {\n\n\t// Convert XML to Structure\n\txml.Unmarshal(b, &w)\n\n\t// Return Cleanly\n\treturn nil\n}", "func FromBytes(bytes []byte) (Manifest, error) {\n\tmanifest := &manifest{}\n\n\t// Preserve the raw manifest so that manifest.Bytes() returns bytes in\n\t// the same order that they were passed to this function\n\tmanifest.raw = make([]byte, len(bytes))\n\tcopy(manifest.raw, bytes)\n\n\tsigned, _ := clearsign.Decode(bytes)\n\tif signed != nil {\n\t\tsignature, err := ioutil.ReadAll(signed.ArmoredSignature.Body)\n\t\tif err != nil {\n\t\t\treturn nil, util.Errorf(\"Could not read signature from pod manifest: %s\", err)\n\t\t}\n\t\tmanifest.signature = signature\n\n\t\t// the original plaintext is in signed.Plaintext, but the signature\n\t\t// corresponds to signed.Bytes, so that's what we need to save\n\t\tmanifest.plaintext = signed.Bytes\n\n\t\t// parse YAML from the message's plaintext instead\n\t\tbytes = signed.Plaintext\n\t}\n\n\tif err := yaml.Unmarshal(bytes, manifest); err != nil {\n\t\treturn nil, util.Errorf(\"Could not read pod manifest: %s\", err)\n\t}\n\tif err := ValidManifest(manifest); err != nil {\n\t\treturn nil, util.Errorf(\"invalid manifest: %s\", err)\n\t}\n\treturn manifest, nil\n}", "func (h *Handler) UpdateFromBytes(data []byte) (*appsv1.StatefulSet, error) {\n\tstsJson, err := yaml.ToJSON(data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsts := &appsv1.StatefulSet{}\n\tif err = json.Unmarshal(stsJson, sts); err != nil {\n\t\treturn nil, err\n\t}\n\treturn h.updateStatefulset(sts)\n}", "func (s *State) ParseBlock(b []byte) (snowman.Block, error) {\n\t// See if we've cached this block's ID by its byte repr.\n\tblkIDIntf, blkIDCached := s.bytesToIDCache.Get(string(b))\n\tif blkIDCached {\n\t\tblkID := blkIDIntf.(ids.ID)\n\t\t// See if we have this block cached\n\t\tif cachedBlk, ok := s.getCachedBlock(blkID); ok {\n\t\t\treturn cachedBlk, nil\n\t\t}\n\t}\n\n\t// We don't have this block cached by its byte repr.\n\t// Parse the block from bytes\n\tblk, err := s.unmarshalBlock(b)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tblkID := blk.ID()\n\ts.bytesToIDCache.Put(string(b), blkID)\n\n\t// Only check the caches if we didn't do so above\n\tif !blkIDCached {\n\t\t// Check for an existing block, so we can return a unique block\n\t\t// if processing or simply allow this block to be immediately\n\t\t// garbage collected if it is already cached.\n\t\tif cachedBlk, ok := s.getCachedBlock(blkID); ok {\n\t\t\treturn cachedBlk, nil\n\t\t}\n\t}\n\n\ts.missingBlocks.Evict(blkID)\n\n\t// Since this block is not in consensus, addBlockOutsideConsensus\n\t// is called to add [blk] to the correct cache.\n\treturn s.addBlockOutsideConsensus(blk)\n}", "func FromBytes(byts []byte) ([]*JSON, error) {\n\tr := readFromBytes(byts)\n\treturn parseAll(r)\n}", "func (b *UpdatesBox) Decode(buf *bin.Buffer) error {\n\tif b == nil {\n\t\treturn fmt.Errorf(\"unable to decode UpdatesBox to nil\")\n\t}\n\tv, err := DecodeUpdates(buf)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to decode boxed value: %w\", err)\n\t}\n\tb.Updates = v\n\treturn nil\n}", "func ParseBlock(d *drawing.Drawing, data [][2]string) error {\n\tb := block.NewBlock(\"\", \"\")\n\tvar err error\n\tfor _, dt := range data {\n\t\tswitch dt[0] {\n\t\tcase \"2\":\n\t\t\tb.Name = dt[1]\n\t\tcase \"1\": // 4?\n\t\t\tb.Description = dt[1]\n\t\tcase \"8\":\n\t\t\tlayer, err := d.Layer(dt[1], false)\n\t\t\tif err == nil {\n\t\t\t\tb.SetLayer(layer)\n\t\t\t}\n\t\tcase \"10\":\n\t\t\terr = setFloat(dt, func(val float64) { b.Coord[0] = val })\n\t\tcase \"20\":\n\t\t\terr = setFloat(dt, func(val float64) { b.Coord[1] = val })\n\t\tcase \"30\":\n\t\t\terr = setFloat(dt, func(val float64) { b.Coord[2] = val })\n\t\tcase \"70\":\n\t\t\tval, err := strconv.ParseInt(strings.TrimSpace(dt[1]), 10, 64)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tb.Flag = int(val)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func sigstoreFromBlobChunk(blobChunk []byte) (Sigstore, error) {\n\tvar v sigstoreJSONRepresentation\n\tif err := json.Unmarshal(blobChunk, &v); err != nil {\n\t\treturn Sigstore{}, err\n\t}\n\treturn SigstoreFromComponents(v.UntrustedMIMEType,\n\t\tv.UntrustedPayload,\n\t\tv.UntrustedAnnotations), nil\n}", "func (poll *FusePollIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 24 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, poll)\n\n\treturn err\n}", "func (s *Store) eventsFromBytes(data []byte) ([]core.Event, error) {\n\treturn s.eventcodec.EventsFromBytes(data)\n}", "func (b *Block) Parse() error {\n\tstartPos := uint64(0)\n\tb.subelements = []*Block{}\n\tfor startPos < uint64(len(b.value)) {\n\t\tblock, blockLen, err := DecodeBlock(b.value[startPos:])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tb.subelements = append(b.subelements, block)\n\t\tstartPos += blockLen\n\t}\n\treturn nil\n}", "func (bmap *FuseBmapIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 16 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, bmap)\n\n\treturn err\n}", "func (setxattr *FuseSetxattrIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 8 {\n\t\treturn ErrDataLen\n\t}\n\n\tcommon.ParseBinary(bcontent[:4], &setxattr.Size)\n\tcommon.ParseBinary(bcontent[4:8], &setxattr.Flags)\n\n\tarray := bytes.Split(bcontent[8:], []byte{0})\n\n\tif len(array) < 2 {\n\t\treturn ErrDataLen\n\t}\n\n\tsetxattr.Name = string(array[0])\n\tsetxattr.Value = string(array[1])\n\n\treturn nil\n}", "func (lk *FuseLkIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 48 {\n\t\treturn ErrDataLen\n\t}\n\n\tcommon.ParseBinary(bcontent, lk)\n\n\treturn nil\n}", "func DeserializeBytes(d []byte) (Bytes, error) {\n\treturn d, nil\n}", "func deserialize(src *[]byte, obj interface{}) error {\n\tglog.Infof(\"Deserialization\")\n\n\t// make a copy of the bytes as this comes from bolt and the object will be used outside\n\t// of the transaction\n\tb := make([]byte, len(*src))\n\tcopy(b, *src)\n\n\tbuf := bytes.NewBuffer(b)\n\tdec := gob.NewDecoder(buf)\n\n\terr := dec.Decode(obj)\n\tif err != nil {\n\t\tglog.Infof(\"Failed to deserialize object: %s\", err)\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func ParseBytes(bytes []byte) (*JSONData, error) {\n\tdata := JSONData{}\n\treturn &data, json.Unmarshal(bytes, &data.value)\n}", "func (f *Footer) ConvertFromBlockFooterPb(pb *iotextypes.BlockFooter) error {\n\tf.commitTimestamp = pb.GetCommitTimestamp()\n\tpbEndorsements := pb.GetEndorsements()\n\tif pbEndorsements == nil {\n\t\treturn nil\n\t}\n\tf.endorsements = &endorsement.Set{}\n\n\treturn f.endorsements.FromProto(pbEndorsements)\n}", "func (init *FuseInitIn) ParseBinary(bcontent []byte) error {\n\terr := common.ParseBinary(bcontent, init)\n\n\treturn err\n}", "func (a *Parser) ParseBytes(b []byte) error {\n\terr := a.parseBytes(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn a.verify()\n}", "func (imp *dbImporter) ImportDecodedBlock(blockContainer *types.EncodedBlockCert) (txCount int, err error) {\n\ttxCount = 0\n\tproto, err := types.Protocol(string(blockContainer.Block.CurrentProtocol))\n\tif err != nil {\n\t\treturn txCount, fmt.Errorf(\"block %d, %v\", blockContainer.Block.Round, err)\n\t}\n\terr = imp.db.StartBlock()\n\tif err != nil {\n\t\treturn txCount, fmt.Errorf(\"error starting block, %v\", err)\n\t}\n\tblock := blockContainer.Block\n\tround := uint64(block.Round)\n\tfor intra := range block.Payset {\n\t\tstxn := &block.Payset[intra]\n\t\ttxtypeenum, ok := idb.GetTypeEnum(stxn.Txn.Type)\n\t\tif !ok {\n\t\t\treturn txCount,\n\t\t\t\tfmt.Errorf(\"%d:%d unknown txn type %v\", round, intra, stxn.Txn.Type)\n\t\t}\n\t\tassetid := uint64(0)\n\t\tswitch txtypeenum {\n\t\tcase 3:\n\t\t\tassetid = uint64(stxn.Txn.ConfigAsset)\n\t\t\tif assetid == 0 {\n\t\t\t\tassetid = block.TxnCounter - uint64(len(block.Payset)) + uint64(intra) + 1\n\t\t\t}\n\t\tcase 4:\n\t\t\tassetid = uint64(stxn.Txn.XferAsset)\n\t\tcase 5:\n\t\t\tassetid = uint64(stxn.Txn.FreezeAsset)\n\t\tcase 6:\n\t\t\tassetid = uint64(stxn.Txn.ApplicationID)\n\t\t\tif assetid == 0 {\n\t\t\t\tassetid = block.TxnCounter - uint64(len(block.Payset)) + uint64(intra) + 1\n\t\t\t}\n\t\t}\n\t\tif stxn.HasGenesisID {\n\t\t\tstxn.Txn.GenesisID = block.GenesisID\n\t\t}\n\t\tif stxn.HasGenesisHash || proto.RequireGenesisHash {\n\t\t\tstxn.Txn.GenesisHash = block.GenesisHash\n\t\t}\n\t\tstxnad := stxn.SignedTxnWithAD\n\t\tparticipants := make([][]byte, 0, 10)\n\t\tparticipants = participate(participants, stxn.Txn.Sender[:])\n\t\tparticipants = participate(participants, stxn.Txn.Receiver[:])\n\t\tparticipants = participate(participants, stxn.Txn.CloseRemainderTo[:])\n\t\tparticipants = participate(participants, stxn.Txn.AssetSender[:])\n\t\tparticipants = participate(participants, stxn.Txn.AssetReceiver[:])\n\t\tparticipants = participate(participants, stxn.Txn.AssetCloseTo[:])\n\t\tparticipants = participate(participants, stxn.Txn.FreezeAccount[:])\n\t\terr = imp.db.AddTransaction(\n\t\t\tround, intra, int(txtypeenum), assetid, stxnad, participants)\n\t\tif err != nil {\n\t\t\treturn txCount, fmt.Errorf(\"error importing txn r=%d i=%d, %v\", round, intra, err)\n\t\t}\n\t\ttxCount++\n\t}\n\tblockheaderBytes := msgpack.Encode(block.BlockHeader)\n\terr = imp.db.CommitBlock(round, block.TimeStamp, block.RewardsLevel, blockheaderBytes)\n\tif err != nil {\n\t\treturn txCount, fmt.Errorf(\"error committing block, %v\", err)\n\t}\n\treturn\n}", "func (fallocate *FuseFallocateIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 32 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, fallocate)\n\n\treturn err\n}", "func (skb *SubdirectoryKeyBlock) FromBlock(block disk.Block) error {\n\tskb.Prev = binary.LittleEndian.Uint16(block[0x0:0x2])\n\tskb.Next = binary.LittleEndian.Uint16(block[0x2:0x4])\n\tskb.Header.fromBytes(block[0x04:0x2b])\n\tfor i := range skb.Descriptors {\n\t\tskb.Descriptors[i].fromBytes(block[0x2b+i*0x27 : 0x2b+(i+1)*0x27])\n\t}\n\tskb.Extra = block[511]\n\treturn nil\n}", "func (pb *PutBlock) LoadProto(putBlockPb *iotextypes.PutBlock) error {\n\tif putBlockPb == nil {\n\t\treturn errors.New(\"empty action proto to load\")\n\t}\n\tif pb == nil {\n\t\treturn errors.New(\"nil action to load proto\")\n\t}\n\t*pb = PutBlock{}\n\n\tpb.subChainAddress = putBlockPb.SubChainAddress\n\tpb.height = putBlockPb.Height\n\n\tpb.roots = make(map[string]hash.Hash256)\n\tfor _, r := range putBlockPb.Roots {\n\t\tpb.roots[r.Name] = hash.BytesToHash256(r.Value)\n\t}\n\treturn nil\n}", "func (st *StatMicMsgBody) ReadBlock(_is *codec.Reader, tag byte, require bool) error {\r\n\tvar err error\r\n\tvar have bool\r\n\tst.resetDefault()\r\n\r\n\terr, have = _is.SkipTo(codec.STRUCT_BEGIN, tag, require)\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\tif !have {\r\n\t\tif require {\r\n\t\t\treturn fmt.Errorf(\"require StatMicMsgBody, but not exist. tag %d\", tag)\r\n\t\t}\r\n\t\treturn nil\r\n\r\n\t}\r\n\r\n\tst.ReadFrom(_is)\r\n\r\n\terr = _is.SkipToStructEnd()\r\n\tif err != nil {\r\n\t\treturn err\r\n\t}\r\n\t_ = have\r\n\treturn nil\r\n}", "func (vm *BFVM) LoadFromStream(reader io.Reader) error {\n\tbuf := new(bytes.Buffer)\n\tif _, err := buf.ReadFrom(parser.Parse(reader)); err != nil {\n\t\treturn err\n\t}\n\n\tvm.commands = buf.Bytes()\n\tvm.position = 0\n\n\ts := newStack()\n\n\tfor i, cmd := range vm.commands {\n\t\tcmd, qty := parser.ExtractCommand(cmd)\n\n\t\tif qty > 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch cmd {\n\t\tcase parser.CmdJump:\n\t\t\ts.push(i)\n\t\tcase parser.CmdReturn:\n\t\t\taddr, err := s.pop()\n\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tvm.jumps[addr] = i\n\t\t\tvm.jumps[i] = addr\n\t\t}\n\t}\n\n\treturn nil\n}", "func (forget *FuseForgetIn) ParseBinary(bcontent []byte) error {\n\terr := common.ParseBinary(bcontent, forget)\n\n\treturn err\n}", "func (bk *Bookkeeper) Deserialize(r io.Reader) error {\n\tvar pkvb serialize.VarBytes\n\tif err := pkvb.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\tvar err error\n\tbk.PubKey, err = keypair.DeserializePublicKey(pkvb.Bytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbinary.Read(r, binary.LittleEndian, &bk.Action)\n\tvar certvb serialize.VarBytes\n\tif err := certvb.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\tbk.Cert = certvb.Bytes\n\tvar issuevb serialize.VarBytes\n\tif err := issuevb.Deserialize(r); err != nil {\n\t\treturn err\n\t}\n\tbk.Issuer, err = keypair.DeserializePublicKey(issuevb.Bytes)\n\treturn err\n}", "func (cuseInit *CuseInitIn) ParseBinary(bcontent []byte) error {\n\n\tlength := len(bcontent)\n\n\tif length < 16 {\n\t\treturn ErrDataLen\n\t}\n\n\terr := common.ParseBinary(bcontent, cuseInit)\n\n\treturn err\n}", "func (o *CloseSessionResponse) DecodeFromBytes(b []byte) error {\n\tvar offset = 0\n\to.TypeID = &datatypes.ExpandedNodeID{}\n\tif err := o.TypeID.DecodeFromBytes(b[offset:]); err != nil {\n\t\treturn err\n\t}\n\toffset += o.TypeID.Len()\n\n\to.ResponseHeader = &ResponseHeader{}\n\treturn o.ResponseHeader.DecodeFromBytes(b[offset:])\n}" ]
[ "0.5924995", "0.5796838", "0.57845896", "0.57589436", "0.5676126", "0.56502134", "0.55452293", "0.55295134", "0.5465833", "0.5421135", "0.5401756", "0.5390105", "0.53619224", "0.53610873", "0.53610873", "0.5347636", "0.52967626", "0.5295075", "0.5273441", "0.52605575", "0.5249155", "0.52433854", "0.5233733", "0.5208828", "0.5204456", "0.5191402", "0.5186602", "0.5167518", "0.5144102", "0.51416445", "0.51365334", "0.5136287", "0.5133543", "0.5127362", "0.51257324", "0.512453", "0.51175386", "0.51104474", "0.51000357", "0.50860536", "0.50860536", "0.5031079", "0.50283617", "0.5019048", "0.5012365", "0.500705", "0.50010276", "0.49756393", "0.49747097", "0.49721584", "0.49570128", "0.49564806", "0.49564806", "0.49503943", "0.49503943", "0.49395198", "0.4935837", "0.4935734", "0.49034044", "0.4898963", "0.48799428", "0.48717493", "0.4849925", "0.48438162", "0.4843441", "0.48354203", "0.48300108", "0.48263103", "0.48135018", "0.48083293", "0.48006207", "0.47993842", "0.47979", "0.47886077", "0.47853765", "0.47846746", "0.4779428", "0.4777461", "0.4776779", "0.4774287", "0.47727987", "0.4768615", "0.47661403", "0.47652087", "0.47623128", "0.47616717", "0.47557852", "0.47500908", "0.4748674", "0.47348243", "0.47348017", "0.47330812", "0.47322863", "0.47308275", "0.47283727", "0.4723849", "0.47236812", "0.4721982", "0.4720314", "0.47182563" ]
0.8108555
0
Stat is a page handler for stat
func Stat(ds *ds.Datastore) echo.HandlerFunc { return func(c echo.Context) error { return c.String(http.StatusOK, fmt.Sprintf(`{ "total": %d }`, ds.TotalHits())) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (e *Engine) HandleStat(req *Request, res ResponseWriter) {\n\tio.WriteString(res, e.Stat.String())\n}", "func Stat(c *gin.Context) {\n\tc.JSON(200, GetStat())\n}", "func (t *TopN) Stat(ctx context.HTTPContext) {\n\tpattern := t.uca.GetPattern(ctx.Request().Path())\n\n\tt.Lock()\n\n\thttpStat, exists := t.m[pattern]\n\tif !exists {\n\t\thttpStat = httpstat.New()\n\t\tt.m[pattern] = httpStat\n\t}\n\n\tt.Unlock()\n\n\thttpStat.Stat(ctx.StatMetric())\n}", "func (d *Dao) Stat(c context.Context, mid int64, ip string) (st *growup.Stat, err error) {\n\tparams := url.Values{}\n\tparams.Set(\"mid\", strconv.FormatInt(mid, 10))\n\tparams.Set(\"ts\", strconv.FormatInt(time.Now().UnixNano()/1000000, 10))\n\tvar res struct {\n\t\tCode int `json:\"code\"`\n\t\tData *growup.Stat\n\t\tMessage string `json:\"message\"`\n\t}\n\tif err = d.client.Get(c, d.statURL, ip, params, &res); err != nil {\n\t\tlog.Error(\"growup url(%s) response(%v) error(%v)\", d.statURL+\"?\"+params.Encode(), res, err)\n\t\terr = ecode.CreativeOrderAPIErr\n\t\treturn\n\t}\n\tif res.Code != 0 {\n\t\tlog.Error(\"growup url(%s) res(%v)\", d.statURL, res)\n\t\terr = ecode.CreativeOrderAPIErr\n\t\treturn\n\t}\n\tst = res.Data\n\treturn\n}", "func (r *Router) GetStatHandler(c *gin.Context) {\n\ttype query struct {\n\t\tFrom time.Time `form:\"from\" binding:\"required\" time_format:\"2006-01-02\"`\n\t\tTo time.Time `form:\"to\" binding:\"required,gtfield=From\" time_format:\"2006-01-02\"`\n\t\tOrderBy string `form:\"orderBy\" binding:\"omitempty,oneof=date views clicks cost cpc cpm\"`\n\t}\n\n\tq := query{}\n\tif err := c.ShouldBindQuery(&q); err != nil {\n\t\trespond(c, http.StatusBadRequest, \"\", err.Error())\n\t\treturn\n\t}\n\n\tfromStr := q.From.Format(LAYOUT)\n\ttoStr := q.To.Format(LAYOUT)\n\n\tstats, err := r.store.Stat().GetInRange(fromStr, toStr, q.OrderBy)\n\tif err != nil {\n\t\trespond(c, http.StatusInternalServerError, \"\", err.Error())\n\t\treturn\n\t}\n\n\trespond(c, http.StatusOK, stats, \"\")\n}", "func (h *ReqHandler) stat(req *protocol.StatReq) (*protocol.StatResp, error) {\n\tfile, err := h.service.File.ByID(req.DataFileID)\n\tswitch {\n\tcase err != nil:\n\t\treturn nil, mcerr.Errorf(mcerr.ErrNotFound, \"Unknown id %s\", req.DataFileID)\n\tcase !h.service.Group.HasAccess(file.Owner, h.user):\n\t\treturn nil, mcerr.Errorf(mcerr.ErrNoAccess, \"You do not have permission to access this datafile %s\", req.DataFileID)\n\tdefault:\n\t\treturn respStat(file), nil\n\t}\n}", "func handlerStatistics(w http.ResponseWriter, r *http.Request) {\n\tsetHeader(w, r)\n\treadCookies(r)\n\taction := r.URL.Query().Get(\"action\")\n\tserver := r.URL.Query().Get(\"server\")\n\ttube := r.URL.Query().Get(\"tube\")\n\tswitch action {\n\tcase \"preference\":\n\t\t_, _ = io.WriteString(w, tplStatisticSetting(tplStatisticEdit(\"\")))\n\t\treturn\n\tcase \"save\":\n\t\t_ = r.ParseForm()\n\t\tstatisticPreferenceSave(r.Form, w, r)\n\t\treturn\n\tcase \"reloader\":\n\t\t_, _ = io.WriteString(w, statisticWaitress(server, tube))\n\t\treturn\n\t}\n\t_, _ = io.WriteString(w, tplStatistic(server, tube))\n}", "func (r *Router) SaveStatHandler(c *gin.Context) {\n\n\ttype request struct {\n\t\tDate string `json:\"date\" binding:\"required,valid_date\"`\n\t\tViews uint `json:\"views,omitempty\"`\n\t\tClicks uint `json:\"clicks,omitempty\"`\n\t\tCost float64 `json:\"cost,omitempty\" binding:\"min=0\"`\n\t}\n\n\treq := request{}\n\tif err := c.ShouldBindJSON(&req); err != nil {\n\t\trespond(c, http.StatusBadRequest, \"\", err.Error())\n\t\treturn\n\t}\n\n\tdate, err := time.Parse(LAYOUT, req.Date)\n\tif err != nil {\n\t\trespond(c, http.StatusInternalServerError, \"\", err.Error())\n\t\treturn\n\t}\n\n\tstat := models.Statistics{\n\t\tDate: date,\n\t\tViews: req.Views,\n\t\tClicks: req.Clicks,\n\t\tCost: req.Cost,\n\t}\n\n\tif err := r.store.Stat().Save(&stat); err != nil {\n\t\trespond(c, http.StatusInternalServerError, \"\", \"Ошибка, статистика за эту дату уже записана\")\n\t\treturn\n\t}\n\n\trespond(c, http.StatusOK, \"готово\", \"\")\n}", "func Stats(w http.ResponseWriter, r *http.Request) {\n\tAuthorised(r)\n\tif Wow.Authorised == false {\n\t\treturn\n\t}\n\tErrorHandler(w, r, nil, 0)\n\tif r.Method == \"GET\" {\n\t\tErrorHandler(w, r, errors.New(\"page for ajax\"), 2)\n\t} else {\n\t\tvar x StatsTH\n\t\terr := json.NewDecoder(r.Body).Decode(&x)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\tID, err := strconv.Atoi(x.ThreadID)\n\t\tErrorHandler(w, r, err, 1)\n\t\tdata.AddNewValueToThread(Wow.ID, ID, x.Value)\n\t\tThread, err := data.GetThreadByID(ID)\n\t\tx.Likes = strconv.Itoa(Thread.Likes)\n\t\tx.Dislikes = strconv.Itoa(Thread.Dislikes)\n\t\tx.Liked = strconv.Itoa(data.CheckUserLikedThread(Wow.ID, ID))\n\t\ta, err := json.Marshal(x)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t}\n\t\tw.Write(a)\n\t}\n}", "func (c *Curator) stat(id core.BlobID) (core.BlobInfo, core.Error) {\n\treturn c.stateHandler.Stat(id)\n}", "func (udb *urlDB) statsHandler(w http.ResponseWriter, r *http.Request) {\n\tvar rws []Rows\n\tvar cols = []Columns{\n\t\t{\n\t\t\tLabel: \"X\",\n\t\t\tColumnType: \"date\",\n\t\t},\n\t\t{\n\t\t\tLabel: \"Daily Total\",\n\t\t\tColumnType: \"number\",\n\t\t},\n\t}\n\n\t// Select all records from the database, split the datetime into a date and group by days. Count the number of requests per day.\n\t// This needs to be changed soon to allow a date range, and possibly to also to fill in empty days if they exist.\n\trows, err := udb.db.Query(\"SELECT COUNT(*) as count, t_stamp::DATE as ts FROM url_map GROUP BY ts ORDER BY ts\")\n\tcheckDBErr(err)\n\n\tfor rows.Next() {\n\t\tvar t time.Time\n\t\tvar count int\n\t\terr := rows.Scan(&count, &t)\n\t\tcheckDBErr(err)\n\t\tconst layout = \"Jan 2, 2006\"\n\t\tdate := t.Format(layout)\n\n\t\t// Convert the date into a string for the JS structure: \"Date(YYYY,M,D)\".\n\t\t// Javascript months are zero indexed (stupid) so we must subtract one. Thanks to my lovely wife for catching that bug\n\t\tdatestr := fmt.Sprintf(\"Date(%d,%d,%d)\", t.Year(), t.Month()-1, t.Day())\n\t\tdailytotal := strconv.FormatInt(int64(count), 10)\n\n\t\trws = append(rws, Rows{\n\t\t\tC: []C2{\n\t\t\t\t{\n\t\t\t\t\tV: datestr,\n\t\t\t\t\tF: date,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tV: dailytotal,\n\t\t\t\t\tF: dailytotal,\n\t\t\t\t},\n\t\t\t},\n\t\t})\n\t}\n\n\t// Finish building our data structure\n\tchart := &Charts{Cols: cols, Rws: rws}\n\n\t// Encode into JSON and pass to our stats.html template\n\tcht, _ := json.Marshal(chart)\n\n\t// Build template data structure\n\tp := &Page{\n\t\tTitle: \"Stats\",\n\t\tContent: struct {\n\t\t\tJS interface{}\n\t\t}{\n\t\t\ttemplate.HTML(string(cht)),\n\t\t},\n\t}\n\n\trenderTemplate(w, \"stats\", p)\n}", "func MakeStats(handler http.Handler, stats *Stats) http.Handler {\r\n return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\r\n \t//Save time everytime we get a request\r\n \tstart := time.Now()\r\n\r\n //Log connection\r\n log.Printf(\"%s %s\", r.RemoteAddr, r.URL)\r\n\r\n //Print all info for request\r\n //log.Printf(\"Request: %v\", r)\r\n\r\n \t//Route and fulfil request\r\n handler.ServeHTTP(w, r)\r\n\r\n //Only count hash requests in stats (even if request is broken) from client side\r\n //This does not count the background hash-write operations as user is not aware\r\n //of these as per requirement. If requirement changes, this will need to be changed\r\n if strings.Contains(r.URL.Path, \"hash\"){\r\n //Calculate request time\r\n end := time.Now()\r\n requestTime := end.Sub(start)\r\n\r\n //Update server stats - thread-safe\r\n stats.timeLock.Lock()\r\n stats.totalTime = stats.totalTime + requestTime\r\n stats.Requests++\r\n stats.AverageTime = float32(stats.totalTime / time.Millisecond) / float32(stats.Requests)\r\n stats.timeLock.Unlock()\r\n log.Printf(\"Request Complete: %v Average: %v\",requestTime,stats.AverageTime)\r\n } \r\n })\r\n}", "func statFile(fname string, isdir bool) os.FileInfo {\n\tvar err error\n\tvar fdata os.FileInfo\n\t// check if file exists before creating page-handler\n\tif fdata, err = os.Stat(fname); os.IsNotExist(err) {\n\t\tlog.Fatalf(\"- ServeStatic: %q does NOT exist!\\n\", fname)\n\t}\n\t// check if file should not be directory\n\tif fdata.IsDir() && !isdir {\n\t\tlog.Fatalf(\"- ServeFile: %q is a Directory!\\n\", fname)\n\t}\n\t// check if file should be a directory\n\tif !fdata.IsDir() && isdir {\n\t\tlog.Fatalf(\"- ServeFile: %q is NOT a Directory!\\n\", fname)\n\t}\n\treturn fdata\n}", "func (exp *attackcost) StatusPage(w http.ResponseWriter, r *http.Request, code, message, additionalInfo string, sType web.ExpStatus) {\n\tcommonPageData := exp.commonData(r)\n\tif commonPageData == nil {\n\t\t// exp.blockData.GetTip likely failed due to empty DB.\n\t\thttp.Error(w, \"The database is initializing. Try again later.\",\n\t\t\thttp.StatusServiceUnavailable)\n\t\treturn\n\t}\n\tstr, err := exp.templates.Exec(\"status\", struct {\n\t\t*web.CommonPageData\n\t\tStatusType web.ExpStatus\n\t\tCode string\n\t\tMessage string\n\t\tAdditionalInfo string\n\t}{\n\t\tCommonPageData: commonPageData,\n\t\tStatusType: sType,\n\t\tCode: code,\n\t\tMessage: message,\n\t\tAdditionalInfo: additionalInfo,\n\t})\n\tif err != nil {\n\t\tlog.Errorf(\"Template execute failure: %v\", err)\n\t\tstr = \"Something went very wrong if you can see this, try refreshing\"\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"text/html\")\n\tswitch sType {\n\tcase web.ExpStatusDBTimeout:\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\tcase web.ExpStatusNotFound:\n\t\tw.WriteHeader(http.StatusNotFound)\n\tcase web.ExpStatusFutureBlock:\n\t\tw.WriteHeader(http.StatusOK)\n\tcase web.ExpStatusError:\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t// When blockchain sync is running, status 202 is used to imply that the\n\t// other requests apart from serving the status sync page have been received\n\t// and accepted but cannot be processed now till the sync is complete.\n\tcase web.ExpStatusSyncing:\n\t\tw.WriteHeader(http.StatusAccepted)\n\tcase web.ExpStatusNotSupported:\n\t\tw.WriteHeader(http.StatusUnprocessableEntity)\n\tcase web.ExpStatusBadRequest:\n\t\tw.WriteHeader(http.StatusBadRequest)\n\tdefault:\n\t\tw.WriteHeader(http.StatusServiceUnavailable)\n\t}\n\tio.WriteString(w, str)\n}", "func (s ForStat) ProcessStat(p StatProcessor) {\n\tp.ProcessForStat(s)\n}", "func AddHyperStatHandler(w http.ResponseWriter, req *http.Request) {\n\n\t// Get session values or redirect to Login\n\tsession, err := sessions.Store.Get(req, \"session\")\n\n\tif err != nil {\n\t\tlog.Println(\"error identifying session\")\n\t\thttp.Redirect(w, req, \"/login/\", 302)\n\t\treturn\n\t\t// in case of error\n\t}\n\n\t// Prep for user authentication\n\tsessionMap := getUserSessionValues(session)\n\n\tusername := sessionMap[\"username\"]\n\tloggedIn := sessionMap[\"loggedin\"]\n\tisAdmin := sessionMap[\"isAdmin\"]\n\n\t// Get variables from URL\n\tvars := mux.Vars(req)\n\tpk := vars[\"id\"]\n\ts := vars[\"stat\"]\n\n\tif len(pk) == 0 {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\tid, err := strconv.Atoi(pk)\n\tif err != nil {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\t// Load CharacterModel\n\tcm, err := database.PKLoadCharacterModel(db, int64(id))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// Validate that User == Author\n\tIsAuthor := false\n\n\tif username == cm.Author.UserName {\n\t\tIsAuthor = true\n\t} else {\n\t\thttp.Redirect(w, req, \"/\", 302)\n\t}\n\n\tc := cm.Character\n\n\t// Assign basic HyperStat\n\tstat := c.Statistics[s]\n\n\tstat.HyperStat = &oneroll.HyperStat{\n\t\tName: fmt.Sprintf(\"Hyper-%s\", stat.Name),\n\t\tDice: &oneroll.DiePool{\n\t\t\tNormal: 0,\n\t\t\tHard: 0,\n\t\t\tWiggle: 0,\n\t\t},\n\t\tEffect: \"\",\n\t}\n\n\ths := stat.HyperStat\n\n\ths.Qualities = []*oneroll.Quality{}\n\n\tqualities := []string{\"Attack\", \"Defend\", \"Useful\", \"\"}\n\n\t// HyperStats start with all qualities, +1 extra\n\tfor _, qs := range qualities {\n\t\tq := &oneroll.Quality{\n\t\t\tType: qs,\n\t\t\tLevel: 0,\n\t\t\tCostPerDie: 0,\n\t\t}\n\n\t\t// Add the completed quality to Power\n\t\ths.Qualities = append(hs.Qualities, q)\n\t}\n\n\t// Add Capacities (Self) to all basic Qualities\n\n\tfor _, q := range hs.Qualities {\n\t\tif q.Type != \"\" {\n\t\t\tcap := oneroll.Capacity{Type: \"Self\"}\n\t\t\tq.Capacities = append(q.Capacities, &cap)\n\t\t}\n\t}\n\n\t// Assign additional empty Qualities to populate form\n\tif len(hs.Qualities) < 4 {\n\t\tfor i := len(hs.Qualities); i < 4; i++ {\n\t\t\ttempQ := oneroll.NewQuality(\"\")\n\t\t\ths.Qualities = append(hs.Qualities, tempQ)\n\t\t}\n\t}\n\n\t// Assign additional empty Capacities to populate form\n\tfor _, q := range hs.Qualities {\n\t\tif len(q.Capacities) < 4 {\n\t\t\tfor i := len(q.Capacities); i < 4; i++ {\n\t\t\t\ttempC := oneroll.Capacity{\n\t\t\t\t\tType: \"\",\n\t\t\t\t}\n\t\t\t\tq.Capacities = append(q.Capacities, &tempC)\n\t\t\t}\n\t\t}\n\t\tif len(q.Modifiers) < 8 {\n\t\t\tfor i := len(q.Modifiers); i < 8; i++ {\n\t\t\t\ttempM := oneroll.NewModifier(\"\")\n\t\t\t\tq.Modifiers = append(q.Modifiers, tempM)\n\t\t\t}\n\t\t}\n\t}\n\n\twc := WebChar{\n\t\tCharacterModel: cm,\n\t\tIsAuthor: IsAuthor,\n\t\tSessionUser: username,\n\t\tIsLoggedIn: loggedIn,\n\t\tIsAdmin: isAdmin,\n\t\tStatistic: stat,\n\t\tModifiers: oneroll.Modifiers,\n\t\tCounter: []int{1, 2, 3, 4, 5, 6, 7, 8},\n\t\tCapacities: map[string]float32{\n\t\t\t\"Mass\": 25.0,\n\t\t\t\"Range\": 10.0,\n\t\t\t\"Speed\": 2.5,\n\t\t\t\"Self\": 0.0,\n\t\t\t\"Touch\": 0.0,\n\t\t},\n\t}\n\n\tif req.Method == \"GET\" {\n\n\t\t// Render page\n\t\tRender(w, \"templates/add_hyperstat.html\", wc)\n\n\t}\n\n\tif req.Method == \"POST\" { // POST\n\n\t\terr := req.ParseForm()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\thsName := req.FormValue(\"Name\")\n\n\t\tnd, _ := strconv.Atoi(req.FormValue(\"Normal\"))\n\t\thd, _ := strconv.Atoi(req.FormValue(\"Hard\"))\n\t\twd, _ := strconv.Atoi(req.FormValue(\"Wiggle\"))\n\n\t\tstat.HyperStat = new(oneroll.HyperStat)\n\n\t\ths = stat.HyperStat\n\n\t\ths.Name = hsName\n\n\t\ths.Dice = &oneroll.DiePool{\n\t\t\tNormal: nd,\n\t\t\tHard: hd,\n\t\t\tWiggle: wd,\n\t\t}\n\n\t\ths.Qualities = []*oneroll.Quality{}\n\n\t\ths.Effect = req.FormValue(\"Effect\")\n\n\t\tfor _, qLoop := range wc.Counter[:4] { // Quality Loop\n\n\t\t\tqType := req.FormValue(fmt.Sprintf(\"Q%d-Type\", qLoop))\n\n\t\t\tif qType != \"\" {\n\t\t\t\tl, err := strconv.Atoi(req.FormValue(fmt.Sprintf(\"Q%d-Level\", qLoop)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tl = 0\n\t\t\t\t}\n\t\t\t\tq := &oneroll.Quality{\n\t\t\t\t\tType: req.FormValue(fmt.Sprintf(\"Q%d-Type\", qLoop)),\n\t\t\t\t\tLevel: l,\n\t\t\t\t\tName: req.FormValue(fmt.Sprintf(\"Q%d-Name\", qLoop)),\n\t\t\t\t}\n\n\t\t\t\tfor _, cLoop := range wc.Counter[:4] {\n\t\t\t\t\tcType := req.FormValue(fmt.Sprintf(\"Q%d-C%d-Type\", qLoop, cLoop))\n\t\t\t\t\tif cType != \"\" {\n\t\t\t\t\t\tcap := &oneroll.Capacity{\n\t\t\t\t\t\t\tType: cType,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tq.Capacities = append(q.Capacities, cap)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tq.Modifiers = []*oneroll.Modifier{}\n\n\t\t\t\tm := new(oneroll.Modifier)\n\n\t\t\t\tfor _, mLoop := range wc.Counter { // Modifier Loop\n\t\t\t\t\tmName := req.FormValue(fmt.Sprintf(\"Q%d-M%d-Name\", qLoop, mLoop))\n\t\t\t\t\tif mName != \"\" {\n\t\t\t\t\t\tl, err := strconv.Atoi(req.FormValue(fmt.Sprintf(\"Q%d-M%d-Level\", qLoop, mLoop)))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tl = 0\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttM := oneroll.Modifiers[mName]\n\n\t\t\t\t\t\tm = &tM\n\n\t\t\t\t\t\tif m.RequiresLevel {\n\t\t\t\t\t\t\tm.Level = l\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif m.RequiresInfo {\n\t\t\t\t\t\t\tm.Info = req.FormValue(fmt.Sprintf(\"Q%d-M%d-Info\", qLoop, mLoop))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tq.Modifiers = append(q.Modifiers, m)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ths.Qualities = append(hs.Qualities, q)\n\t\t\t}\n\t\t}\n\n\t\tapply := req.FormValue(\"Apply\")\n\n\t\tif apply == \"Yes\" {\n\t\t\t// Apply Modifiers to Base\n\t\t\ths.Apply = true\n\t\t\t// Remove existing Skill Modifiers\n\t\t\tstat.Modifiers = nil\n\t\t\t// Get base description text\n\t\t\tbaseEffectText := strings.Split(hs.Effect, \"++\")\n\n\t\t\t// Add modifiers to base Skill\n\t\t\tfor _, q := range hs.Qualities {\n\t\t\t\tfor _, m := range q.Modifiers {\n\n\t\t\t\t\tstat.Modifiers = append(stat.Modifiers, m)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Update Skill Cost\n\t\t\toneroll.UpdateCost(stat)\n\t\t\t// Determine the difference from the base skill cost\n\t\t\tmodStatCost := stat.Cost - (stat.Dice.Normal * 5)\n\n\t\t\t// If difference is positive, add to descriptive text\n\t\t\tif modStatCost > 0 {\n\t\t\t\tnewModText := fmt.Sprintf(\"\\n++Added modifiers to base stat (%dpts)\",\n\t\t\t\t\tmodStatCost)\n\t\t\t\ths.Effect = baseEffectText[0] + newModText\n\t\t\t} else {\n\t\t\t\ths.Effect = baseEffectText[0]\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(c)\n\n\t\terr = database.UpdateCharacterModel(db, cm)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Println(\"Saved\")\n\t\t}\n\n\t\tfmt.Println(c)\n\n\t\turl := fmt.Sprintf(\"/view_character/%d\", cm.ID)\n\n\t\thttp.Redirect(w, req, url, http.StatusSeeOther)\n\t}\n}", "func statsHandler(w http.ResponseWriter, r *http.Request) {\n\tdata := core.GetStats()\n\tb, err := json.Marshal(data)\n\tif err != nil {\n\t\thttp.Error(w, \"Error marshalling JSON\", http.StatusInternalServerError)\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tfmt.Fprintf(w, \"%s\", b)\n}", "func MakeHandleStats(stats *Stats) func(w http.ResponseWriter, r *http.Request){\r\n return func (w http.ResponseWriter, r *http.Request){\r\n //Note totalTime does not picked up by JSON as it's lowercase\r\n jsonStats, err := json.Marshal(stats)\r\n if err != nil {\r\n sendError(w, \"404 Error getting JSON object\")\r\n return\r\n }\r\n w.Header().Set(\"Content-Type\", \"application/json\")\r\n f, err := w.Write(jsonStats)\r\n checkError(f, err)\r\n }\r\n}", "func (d *DBClient) StatsHandler(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tstats := d.Counter.Flush()\n\n\tcount, err := d.Cache.RecordsCount()\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t}\n\n\tvar sr statsResponse\n\tsr.Stats = stats\n\tsr.RecordsCount = count\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\tb, err := json.Marshal(sr)\n\n\tif err != nil {\n\t\tlog.Error(err)\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t} else {\n\t\tw.Write(b)\n\t\treturn\n\t}\n\n}", "func ModifyHyperStatHandler(w http.ResponseWriter, req *http.Request) {\n\n\t// Get session values or redirect to Login\n\tsession, err := sessions.Store.Get(req, \"session\")\n\n\tif err != nil {\n\t\tlog.Println(\"error identifying session\")\n\t\thttp.Redirect(w, req, \"/login/\", 302)\n\t\treturn\n\t\t// in case of error\n\t}\n\n\t// Prep for user authentication\n\tsessionMap := getUserSessionValues(session)\n\n\tusername := sessionMap[\"username\"]\n\tloggedIn := sessionMap[\"loggedin\"]\n\tisAdmin := sessionMap[\"isAdmin\"]\n\n\t// Get variables from URL\n\tvars := mux.Vars(req)\n\tpk := vars[\"id\"]\n\ts := vars[\"stat\"]\n\n\tif len(pk) == 0 {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\tid, err := strconv.Atoi(pk)\n\tif err != nil {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\t// Load CharacterModel\n\tcm, err := database.PKLoadCharacterModel(db, int64(id))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// Validate that User == Author\n\tIsAuthor := false\n\n\tif username == cm.Author.UserName {\n\t\tIsAuthor = true\n\t} else {\n\t\thttp.Redirect(w, req, \"/\", 302)\n\t}\n\n\tc := cm.Character\n\n\t// Assign basic HyperStat\n\tstat := c.Statistics[s]\n\n\ths := stat.HyperStat\n\n\t// Assign additional empty Qualities to populate form\n\tif len(hs.Qualities) < 4 {\n\t\tfor i := len(hs.Qualities); i < 4; i++ {\n\t\t\ttempQ := oneroll.NewQuality(\"\")\n\t\t\ths.Qualities = append(hs.Qualities, tempQ)\n\t\t}\n\t} else {\n\t\t// Always create at least 2 Qualities\n\t\tfor i := 0; i < 2; i++ {\n\t\t\ttempQ := oneroll.NewQuality(\"\")\n\t\t\ths.Qualities = append(hs.Qualities, tempQ)\n\t\t}\n\t}\n\n\t// Assign additional empty Capacities to populate form\n\tfor _, q := range hs.Qualities {\n\t\tif len(q.Capacities) < 4 {\n\t\t\tfor i := len(q.Capacities); i < 4; i++ {\n\t\t\t\ttempC := oneroll.Capacity{\n\t\t\t\t\tType: \"\",\n\t\t\t\t}\n\t\t\t\tq.Capacities = append(q.Capacities, &tempC)\n\t\t\t}\n\t\t}\n\t\tif len(q.Modifiers) < 8 {\n\t\t\tfor i := len(q.Modifiers); i < 8; i++ {\n\t\t\t\ttempM := oneroll.NewModifier(\"\")\n\t\t\t\tq.Modifiers = append(q.Modifiers, tempM)\n\t\t\t}\n\t\t}\n\t}\n\n\twc := WebChar{\n\t\tCharacterModel: cm,\n\t\tIsAuthor: IsAuthor,\n\t\tSessionUser: username,\n\t\tIsLoggedIn: loggedIn,\n\t\tIsAdmin: isAdmin,\n\t\tStatistic: stat,\n\t\tModifiers: oneroll.Modifiers,\n\t\tCounter: []int{1, 2, 3, 4, 5, 6, 7, 8},\n\t\tCapacities: map[string]float32{\n\t\t\t\"Mass\": 25.0,\n\t\t\t\"Range\": 10.0,\n\t\t\t\"Speed\": 2.5,\n\t\t\t\"Self\": 0.0,\n\t\t\t\"Touch\": 0.0,\n\t\t},\n\t}\n\n\tif req.Method == \"GET\" {\n\n\t\t// Render page\n\t\tRender(w, \"templates/modify_hyperstat.html\", wc)\n\n\t}\n\n\tif req.Method == \"POST\" { // POST\n\n\t\terr := req.ParseForm()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\thsName := req.FormValue(\"Name\")\n\n\t\tnd, _ := strconv.Atoi(req.FormValue(\"Normal\"))\n\t\thd, _ := strconv.Atoi(req.FormValue(\"Hard\"))\n\t\twd, _ := strconv.Atoi(req.FormValue(\"Wiggle\"))\n\n\t\tstat.HyperStat = new(oneroll.HyperStat)\n\n\t\ths = stat.HyperStat\n\n\t\ths.Name = hsName\n\n\t\ths.Dice = &oneroll.DiePool{\n\t\t\tNormal: nd,\n\t\t\tHard: hd,\n\t\t\tWiggle: wd,\n\t\t}\n\n\t\ths.Qualities = []*oneroll.Quality{}\n\n\t\ths.Effect = req.FormValue(\"Effect\")\n\n\t\tfor _, qLoop := range wc.Counter[:4] { // Quality Loop\n\n\t\t\tqType := req.FormValue(fmt.Sprintf(\"Q%d-Type\", qLoop))\n\n\t\t\tif qType != \"\" {\n\t\t\t\tl, err := strconv.Atoi(req.FormValue(fmt.Sprintf(\"Q%d-Level\", qLoop)))\n\t\t\t\tif err != nil {\n\t\t\t\t\tl = 0\n\t\t\t\t}\n\t\t\t\tq := &oneroll.Quality{\n\t\t\t\t\tType: req.FormValue(fmt.Sprintf(\"Q%d-Type\", qLoop)),\n\t\t\t\t\tLevel: l,\n\t\t\t\t\tName: req.FormValue(fmt.Sprintf(\"Q%d-Name\", qLoop)),\n\t\t\t\t}\n\n\t\t\t\tfor _, cLoop := range wc.Counter[:4] {\n\t\t\t\t\tcType := req.FormValue(fmt.Sprintf(\"Q%d-C%d-Type\", qLoop, cLoop))\n\t\t\t\t\tif cType != \"\" {\n\t\t\t\t\t\tcap := &oneroll.Capacity{\n\t\t\t\t\t\t\tType: cType,\n\t\t\t\t\t\t}\n\t\t\t\t\t\tq.Capacities = append(q.Capacities, cap)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tq.Modifiers = []*oneroll.Modifier{}\n\n\t\t\t\tm := new(oneroll.Modifier)\n\n\t\t\t\tfor _, mLoop := range wc.Counter { // Modifier Loop\n\t\t\t\t\tmName := req.FormValue(fmt.Sprintf(\"Q%d-M%d-Name\", qLoop, mLoop))\n\t\t\t\t\tif mName != \"\" {\n\t\t\t\t\t\tl, err := strconv.Atoi(req.FormValue(fmt.Sprintf(\"Q%d-M%d-Level\", qLoop, mLoop)))\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tl = 0\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\ttM := oneroll.Modifiers[mName]\n\n\t\t\t\t\t\tm = &tM\n\n\t\t\t\t\t\tif m.RequiresLevel {\n\t\t\t\t\t\t\tm.Level = l\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif m.RequiresInfo {\n\t\t\t\t\t\t\tm.Info = req.FormValue(fmt.Sprintf(\"Q%d-M%d-Info\", qLoop, mLoop))\n\t\t\t\t\t\t}\n\t\t\t\t\t\tq.Modifiers = append(q.Modifiers, m)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ths.Qualities = append(hs.Qualities, q)\n\t\t\t}\n\t\t}\n\n\t\tapply := req.FormValue(\"Apply\")\n\n\t\tif apply == \"Yes\" {\n\t\t\t// Apply Modifiers to Base\n\t\t\ths.Apply = true\n\t\t\t// Remove existing Skill Modifiers\n\t\t\tstat.Modifiers = nil\n\t\t\t// Get base description text\n\t\t\tbaseEffectText := strings.Split(hs.Effect, \"++\")\n\n\t\t\t// Add modifiers to base Skill\n\t\t\tfor _, q := range hs.Qualities {\n\t\t\t\tfor _, m := range q.Modifiers {\n\n\t\t\t\t\tstat.Modifiers = append(stat.Modifiers, m)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Update Skill Cost\n\t\t\toneroll.UpdateCost(stat)\n\t\t\t// Determine the difference from the base skill cost\n\t\t\tmodStatCost := stat.Cost - (stat.Dice.Normal * 5)\n\n\t\t\t// If difference is positive, add to descriptive text\n\t\t\tif modStatCost > 0 {\n\t\t\t\tnewModText := fmt.Sprintf(\"\\n++Added modifiers to base stat (%dpts)\",\n\t\t\t\t\tmodStatCost)\n\t\t\t\ths.Effect = baseEffectText[0] + newModText\n\t\t\t} else {\n\t\t\t\ths.Effect = baseEffectText[0]\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(c)\n\n\t\terr = database.UpdateCharacterModel(db, cm)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Println(\"Saved\")\n\t\t}\n\n\t\tfmt.Println(c)\n\n\t\turl := fmt.Sprintf(\"/view_character/%d\", cm.ID)\n\n\t\thttp.Redirect(w, req, url, http.StatusSeeOther)\n\t}\n}", "func (c *cpusetHandler) Stat(ctr *CgroupControl, m *Metrics) error {\n\treturn nil\n}", "func GinHandler(c *gin.Context) {\n\tc.JSON(http.StatusOK, api.GetStats())\n}", "func (d *Dao) Stat(c context.Context, aid int64) (st *api.Stat, err error) {\n\tif st, err = d.statCache(c, aid); err != nil {\n\t\tlog.Error(\"%+v\", err)\n\t} else if st != nil {\n\t\treturn\n\t}\n\targ := &archive.ArgAid2{Aid: aid}\n\tif st, err = d.arcRPC.Stat3(c, arg); err != nil {\n\t\tlog.Error(\"d.arcRPC.Stat3(%v) error(%v)\", arg, err)\n\t\tif st, err = d.arcRPC2.Stat3(c, arg); err != nil {\n\t\t\terr = errors.Wrapf(err, \"%v\", arg)\n\t\t}\n\t}\n\treturn\n}", "func (s *session) handleSTAT(args []string) error {\n\treturn s.respondOK(\"%d %d\", s.getMessageCount(), s.getMaildropSize())\n}", "func statsHandler(a *sir.ApplicationContext, c web.C, w http.ResponseWriter, r *http.Request) (int, error) {\n\t// Number of available names in the pool\n\tremaining, _ := a.Redis.SCard(a.PoolKey).Result()\n\t// Number of taken names in the pool\n\ttaken, _ := a.Redis.SCard(a.AllocatedKey).Result()\n\t// Remaining\n\ttotal := remaining + taken\n\n\tresp, _ := json.Marshal(&statsResponse{\n\t\tTotal: total,\n\t\tTaken: taken,\n\t\tRemaining: remaining,\n\t})\n\n\tstatus := 200\n\n\tw.WriteHeader(status)\n\tw.Write(resp)\n\n\treturn status, nil\n}", "func statusHandler(w http.ResponseWriter, _ *http.Request) {\n\tbToMb := func(b uint64) string {\n\t\treturn fmt.Sprintf(\"%v MiB\", b/1024/1024)\n\t}\n\tvar m runtime.MemStats\n\truntime.ReadMemStats(&m)\n\n\trowData := [][2]string{\n\t\t{\"Total Files:\", fmt.Sprintf(\"%v\", uint64(fileCount(config.Global.Root)))},\n\t\t{\"Media Folder Size:\", bToMb(uint64(folderSize(config.Global.Root)))},\n\t\t{\"Thumbnail Folder Size:\", bToMb(uint64(folderSize(config.Global.Cache)))},\n\t\t{\"Folders Watched:\", fmt.Sprint(gallery.WatchedFolders)},\n\t\t{\"Public Url:\", config.Global.PublicUrl},\n\t\t{\"Prefix:\", config.Global.Prefix},\n\t\t{\"-\", \"\"},\n\t\t{\"Alloc Memory:\", bToMb(m.Alloc)},\n\t\t{\"Sys Memory:\", bToMb(m.Sys)},\n\t\t{\"Goroutines:\", fmt.Sprint(runtime.NumGoroutine())},\n\t\t{\"-\", \"\"},\n\t\t{\"App Version:\", BuildVersion},\n\t\t{\"App Build Date:\", BuildTimestamp},\n\t\t{\"Service Uptime:\", time.Since(startTime).String()},\n\t}\n\n\tpage := templates.TwoColTable{\n\t\tPage: templates.Page{\n\t\t\tTitle: \"System Status\",\n\t\t\tPrefix: urlPrefix,\n\t\t\tAppVersion: BuildVersion,\n\t\t\tAppBuildTime: BuildTimestamp,\n\t\t},\n\t\tRows: rowData,\n\t}\n\t_ = templates.Html.ExecuteTemplate(w, \"table\", &page)\n}", "func (s *Stats) Process(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\tc.Set(\"user\", \"hello?\")\n\n\t\tif err := next(c); err != nil {\n\t\t\tc.Error(err)\n\t\t}\n\t\ts.mutex.Lock()\n\t\tdefer s.mutex.Unlock()\n\t\ts.RequestCount++\n\t\tstatus := strconv.Itoa(c.Response().Status)\n\t\ts.Statuses[status]++\n\t\treturn nil\n\t}\n}", "func SessionStatHandler(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, fmt.Sprintf(\"{ \\\"Session\\\" : [ %s, %s ] }\", qpsData.QpsString(),\n\t\tfmt.Sprintf(\"{ \\\"total requests\\\" : %s }\", requestStat.String())))\n}", "func StatsHandler(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\te := json.NewEncoder(w)\n\terr := e.Encode(httpstats.Data())\n\tif err != nil {\n\t\tlog.Println(\"Error encoding data:\", err)\n\t}\n}", "func Stat(path string, sta *Stat_t) (err error) {\n\tvar statLE Stat_LE_t\n\terr = stat(path, &statLE)\n\tcopyStat(sta, &statLE)\n\treturn\n}", "func (be *RetryBackend) Stat(ctx context.Context, h restic.Handle) (fi restic.FileInfo, err error) {\n\terr = be.retry(ctx, fmt.Sprintf(\"Stat(%v)\", h),\n\t\tfunc() error {\n\t\t\tvar innerError error\n\t\t\tfi, innerError = be.Backend.Stat(ctx, h)\n\n\t\t\treturn innerError\n\t\t})\n\treturn fi, err\n}", "func (s *Service) Stats(r *http.Request, args *StatsArgs, result *StatsResponse) error {\n\tif args.UserID == \"\" {\n\t\tresult.Error = uidMissing\n\t\treturn nil\n\t}\n\tresult.Whole = -1\n\tresult.Bookmarks = -1\n\tresult.Pim = -1\n\tresult.Org = -1\n\tcoll := s.Session.DB(MentatDatabase).C(args.UserID)\n\twholeCount, err := coll.Count()\n\tif err != nil {\n\t\tresult.Error = fmt.Sprintf(\"failed getting stats/whole count: %s\", err)\n\t\treturn nil\n\t}\n\tresult.Whole = wholeCount\n\tif args.Detailed {\n\t\tvar entries []Entry\n\t\terr := coll.Find(bson.M{\"type\": \"bookmark\"}).All(&entries)\n\t\tif err != nil {\n\t\t\tresult.Error = fmt.Sprintf(\"failed getting stats/bookmarks count: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t\tresult.Bookmarks = len(entries)\n\t\terr = coll.Find(bson.M{\"type\": \"pim\"}).All(&entries)\n\t\tif err != nil {\n\t\t\tresult.Error = fmt.Sprintf(\"failed getting stats/pim count: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t\tresult.Pim = len(entries)\n\t\terr = coll.Find(bson.M{\"type\": \"org\"}).All(&entries)\n\t\tif err != nil {\n\t\t\tresult.Error = fmt.Sprintf(\"failed getting stats/org count: %s\", err)\n\t\t\treturn nil\n\t\t}\n\t\tresult.Org = len(entries)\n\t}\n\treturn nil\n}", "func (k *KVAdapter) Stat(property string) (string, error) {\n\tpanic(\"not implemented\") // TODO: Implement\n}", "func (a *app) printStat() {\n\tfmt.Printf(\"Total capacity %vgb \\n\", a.sq.Limit/1024/1024/1024)\n\tfmt.Printf(\"Usage %vmb \\n\", a.sq.Usage/1024/1024)\n\tfmt.Printf(\"In Drive %vmb \\n\", a.sq.UsageInDrive/1024/1024)\n\tfmt.Printf(\"In Trash %vmb \\n\", a.sq.UsageInDriveTrash/1024/1024)\n\n\tperOfUse := float64(a.sq.UsageInDrive) / float64(a.sq.Limit) * 100\n\tfmt.Println(\"Current percentage of use:\", perOfUse)\n}", "func NewStatHandler(scope Scope, handler http.Handler) http.Handler {\n\treturn &httpHandler{\n\t\tscope: scope,\n\t\tdelegate: handler,\n\t\ttimer: scope.NewTimer(requestTimer),\n\t\tcodes: map[int]Counter{},\n\t}\n}", "func (s *stat) Stat() (cp Stat) {\n\ts.mx.Lock()\n\tdefer s.mx.Unlock()\n\n\tcp.Registries = s.Registries\n\tcp.Save = s.Save\n\tcp.CleanUp = s.CleanUp\n\treturn\n}", "func (st *httpStats) updateStats(r *http.Request, w *httpResponseRecorder) {\n\t// A successful request has a 2xx response code\n\tsuccessReq := (w.respStatusCode >= 200 && w.respStatusCode < 300)\n\t// Update stats according to method verb\n\tswitch r.Method {\n\tcase \"HEAD\":\n\t\tst.totalHEADs.Inc(1)\n\t\tif successReq {\n\t\t\tst.successHEADs.Inc(1)\n\t\t}\n\tcase \"GET\":\n\t\tst.totalGETs.Inc(1)\n\t\tif successReq {\n\t\t\tst.successGETs.Inc(1)\n\t\t}\n\tcase \"PUT\":\n\t\tst.totalPUTs.Inc(1)\n\t\tif successReq {\n\t\t\tst.successPUTs.Inc(1)\n\t\t}\n\tcase \"POST\":\n\t\tst.totalPOSTs.Inc(1)\n\t\tif successReq {\n\t\t\tst.successPOSTs.Inc(1)\n\t\t}\n\tcase \"DELETE\":\n\t\tst.totalDELETEs.Inc(1)\n\t\tif successReq {\n\t\t\tst.successDELETEs.Inc(1)\n\t\t}\n\t}\n}", "func (p *stats) Handles(req *comm.Request) (res bool) {\n\treturn\n}", "func (s *BaseAmbigListener) EnterStat(ctx *StatContext) {}", "func (s *server) shortHandler(kind aliasKind) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tctx := r.Context()\n\n\t\tvar err error\n\t\tdefer func() {\n\t\t\tif err != nil {\n\t\t\t\t// Just tell the user we could not find the record rather than\n\t\t\t\t// throw 50x. The server should be able to identify the issue.\n\t\t\t\tlog.Printf(\"stats err: %v\\n\", err)\n\t\t\t\t// Use 307 redirect to 404 page\n\t\t\t\thttp.Redirect(w, r, \"/404.html\", http.StatusTemporaryRedirect)\n\t\t\t}\n\t\t}()\n\n\t\t// statistic page\n\t\tvar prefix string\n\t\tswitch kind {\n\t\tcase kindShort:\n\t\t\tprefix = conf.S.Prefix\n\t\tcase kindRandom:\n\t\t\tprefix = conf.R.Prefix\n\t\t}\n\n\t\talias := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, prefix), \"/\")\n\t\tif alias == \"\" {\n\t\t\terr = s.stats(ctx, kind, w, r)\n\t\t\treturn\n\t\t}\n\n\t\t// figure out redirect location\n\t\turl, ok := s.cache.Get(alias)\n\t\tif !ok {\n\t\t\turl, err = s.checkdb(ctx, alias)\n\t\t\tif err != nil {\n\t\t\t\turl, err = s.checkvcs(ctx, alias)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\t\t\ts.cache.Put(alias, url)\n\t\t}\n\n\t\t// redirect the user immediate, but run pv/uv count in background\n\t\thttp.Redirect(w, r, url, http.StatusTemporaryRedirect)\n\n\t\t// count visit in another goroutine so it won't block the redirect.\n\t\tgo func() {\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second*10)\n\t\t\tdefer cancel()\n\n\t\t\tip := readIP(r)\n\t\t\t_, err := s.db.FetchIP(context.Background(), ip)\n\t\t\tif errors.Is(err, redis.Nil) {\n\t\t\t\terr = s.db.StoreIP(ctx, ip, alias) // new ip\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"failt to store ip: %v\", err)\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\tlog.Printf(\"cannot fetch data store for ip processing: %v\\n\", err)\n\t\t\t} else {\n\t\t\t\terr = s.db.UpdateIP(ctx, ip, alias) // old ip\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Printf(\"failt to update ip: %v\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\t})\n}", "func (p *Pages) Stats() PagesStat {\n\tvar totalPages int\n\tvar stats = map[string]SessionStat{}\n\tvar stack = njson.Log(p.logger)\n\n\tp.sl.RLock()\n\ttotalPages = len(p.managers)\n\tfor page, manager := range p.managers {\n\t\tstat, err := manager.Stat()\n\t\tif err != nil {\n\t\t\tstack.New().LError().Error(\"error\", err).\n\t\t\t\tMessage(\"failed to get stat for page\").\n\t\t\t\tString(\"page\", page).\n\t\t\t\tEnd()\n\t\t\tcontinue\n\t\t}\n\t\tstats[page] = stat\n\t}\n\tp.sl.RUnlock()\n\n\tvar stat PagesStat\n\tstat.PageSessions = stats\n\tstat.TotalPages = totalPages\n\treturn stat\n}", "func (h *Handler) Info(c router.Control) {\n\thost, _ := os.Hostname()\n\tm := new(runtime.MemStats)\n\truntime.ReadMemStats(m)\n\n\tc.Code(http.StatusOK)\n\tc.Body(Status{\n\t\tHost: host,\n\t\tVersion: version.RELEASE,\n\t\tCommit: version.COMMIT,\n\t\tRepo: version.REPO,\n\t\tCompiler: runtime.Version(),\n\t\tRuntime: Runtime{\n\t\t\tCPU: runtime.NumCPU(),\n\t\t\tMemory: fmt.Sprintf(\"%.2fMB\", float64(m.Sys)/(1<<(10*2))),\n\t\t\tGoroutines: runtime.NumGoroutine(),\n\t\t},\n\t\tState: State{\n\t\t\tMaintenance: h.maintenance,\n\t\t\tUptime: time.Now().Sub(h.stats.startTime).String(),\n\t\t},\n\t\tRequests: Requests{\n\t\t\tDuration: Duration{\n\t\t\t\tAverage: h.stats.requests.Duration.Average,\n\t\t\t\tMax: h.stats.requests.Duration.Max,\n\t\t\t},\n\t\t\tCodes: Codes{\n\t\t\t\tC2xx: h.stats.requests.Codes.C2xx,\n\t\t\t\tC4xx: h.stats.requests.Codes.C4xx,\n\t\t\t\tC5xx: h.stats.requests.Codes.C5xx,\n\t\t\t},\n\t\t},\n\t})\n}", "func (this *Node) GetStat() int {\n\treturn int(this.ptr.stat)\n}", "func (my *Driver) UseStat(s statFn) {\n\tmy.stat = s\n}", "func printStat(app *app, s stat.Stat, props stat.PostgresProperties) {\n\tapp.ui.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(\"sysstat\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"set focus on sysstat view failed: %s\", err)\n\t\t}\n\t\tv.Clear()\n\t\terr = printSysstat(v, s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"print sysstat failed: %s\", err)\n\t\t}\n\n\t\tv, err = g.View(\"pgstat\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"set focus on pgstat view failed: %s\", err)\n\t\t}\n\t\tv.Clear()\n\t\terr = printPgstat(v, s, props, app.db)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"print summary postgres stat failed: %s\", err)\n\t\t}\n\n\t\tv, err = g.View(\"dbstat\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"set focus on dbstat view failed: %s\", err)\n\t\t}\n\t\tv.Clear()\n\n\t\terr = printDbstat(v, app.config, s)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"print main postgres stat failed: %s\", err)\n\t\t}\n\n\t\tif app.config.view.ShowExtra > stat.CollectNone {\n\t\t\tv, err := g.View(\"extra\")\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"set focus on extra view failed: %s\", err)\n\t\t\t}\n\n\t\t\tswitch app.config.view.ShowExtra {\n\t\t\tcase stat.CollectDiskstats:\n\t\t\t\tv.Clear()\n\t\t\t\terr := printIostat(v, s.Diskstats)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase stat.CollectNetdev:\n\t\t\t\tv.Clear()\n\t\t\t\terr := printNetdev(v, s.Netdevs)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\tcase stat.CollectLogtail:\n\t\t\t\tsize, buf, err := readLogfileRecent(v, app.config.logtail)\n\t\t\t\tif err != nil {\n\t\t\t\t\tprintCmdline(g, \"Tail Postgres log failed: %s\", err)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif size < app.config.logtail.Size {\n\t\t\t\t\tv.Clear()\n\t\t\t\t\terr := app.config.logtail.Reopen(app.db, app.postgresProps.VersionNum)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tprintCmdline(g, \"Tail Postgres log failed: %s\", err)\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Update info about logfile size.\n\t\t\t\tapp.config.logtail.Size = size\n\n\t\t\t\terr = printLogtail(v, app.config.logtail.Path, buf)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (h BaseHandler) Status(ctx *fasthttp.RequestCtx, status int) error {\n\treturn Status(ctx, status)\n}", "func statFunc(cmd *cobra.Command, args []string) {\n\tsession := getAwsSession()\n\tmanager := db.NewManager(rds.New(session))\n\tname := args[0]\n\n\ti, err := manager.Stat(name)\n\tif err != nil {\n\t\tfmt.Printf(\"%s: %s\\n\", name, getAwsError(err))\n\t\treturn\n\t}\n\n\tfmt.Println(i)\n}", "func (mw serviceLoggingMiddleware) GetStat(ctx context.Context, establishmentID, menuID int64, soireeBegin, soireeEnd time.Time) (soireeID int64, err error) {\n\tdefer func(begin time.Time) {\n\t\tmw.logger.Log(\n\t\t\t\"method\", \"GetStat\",\n\t\t\t\"establishmentID\", establishmentID, \"menuID\", menuID,\n\t\t\t\"soireeBegin\", soireeBegin, \"soireeEnd\", soireeEnd,\n\t\t\t\"soireeID\", soireeID,\n\t\t\t\"error\", err,\n\t\t\t\"took\", time.Since(begin),\n\t\t)\n\t}(time.Now())\n\treturn mw.next.GetStat(ctx, establishmentID, menuID, soireeBegin, soireeEnd)\n}", "func (a *app) gatherStat() {\n\tabout, err := a.srv.About.Get().Fields(\"storageQuota\").Do()\n\tif err != nil {\n\t\tlog.Fatalf(\"Unable to execute an about request: %v\", err)\n\t}\n\n\ta.sq = about.StorageQuota\n}", "func (ss *StreamerServer) handleStats(w http.ResponseWriter, r *http.Request) {\n\tif r.Method != \"GET\" {\n\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\tvar statsReq model.StatsReq\n\tdefer r.Body.Close()\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\terr = json.Unmarshal(body, &statsReq)\n\tif statsReq.BaseManifestID == \"\" || err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tif err != nil {\n\t\t\tw.Write([]byte(err.Error()))\n\t\t}\n\t\tw.Write([]byte(\"must supply base_manifest_id\\n\"))\n\t\treturn\n\t}\n\tstats := ss.streamer.Stats(statsReq.BaseManifestID)\n\n\t// glog.Infof(\"Lat avg %d p50 %d p95 %d p99 %d avg %s p50 %s p95 %s p99 %s\", stats.SourceLatencies.Avg, stats.SourceLatencies.P50, stats.SourceLatencies.P95,\n\t// \tstats.SourceLatencies.P99, stats.SourceLatencies.Avg, stats.SourceLatencies.P50, stats.SourceLatencies.P95, stats.SourceLatencies.P99)\n\tb, err := json.Marshal(stats)\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\tw.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tw.Write(b)\n}", "func (st *Store) Stat() *stats.Statistics {\n\treturn st.stat\n}", "func (this Statuser) Run(vars map[string]interface{}, next func()) {\n\tnext()\n\n\tstatus := httper.V(vars).GetStatus()\n\n\tlayout := strconv.Itoa(status)\n\tif templater.V(vars).Exists(this.Folder + \"/\" + layout) {\n\t\tvars[this.LayoutVar] = layout\n\t\treturn\n\t}\n\n\tlayout = strconv.Itoa(status/100) + \"xx\"\n\tif templater.V(vars).Exists(this.Folder + \"/\" + layout) {\n\t\tvars[this.ErrorVar] = strconv.Itoa(status)\n\t\tvars[this.LayoutVar] = layout\n\t}\n}", "func (dir HgmDir) getStatEndpoint(path string, readdir bool) string {\n\tpathUrl := url.URL{Path: path}\n\tendpoint := fmt.Sprintf(\"%s%s%s\", dir.hgmFs.proxyUrl, stattool.StatSvcEndpoint, pathUrl.String())\n\tif readdir == true {\n\t\tendpoint += \"?op=readdir\"\n\t}\n\treturn endpoint\n}", "func (s *snapshotter) Stat(ctx context.Context, key string) (snapshots.Info, error) {\n\tlog.G(ctx).Debug(\"Starting Stat\")\n\tctx, t, err := s.ms.TransactionContext(ctx, false)\n\tif err != nil {\n\t\treturn snapshots.Info{}, err\n\t}\n\tdefer t.Rollback()\n\n\t_, info, _, err := storage.GetInfo(ctx, key)\n\treturn info, err\n}", "func getStatus() {\n\n\tif !authenticated {\n\t\tauth(client)\n\t}\n\n\tsay(\"Fetching progress page...\", 2)\n\tresp, err := client.Get(penet + \"/progress\")\n\tif err != nil {\n\t\tfmt.Printf(\"Error : %s\", err)\n\t}\n\n\tb, _ := ioutil.ReadAll(resp.Body)\n\tresp.Body.Close()\n\tsay(\"Progress page downloaded.\", 1)\n\n\tsay(\"Writing page to \"+settings[\"statusPath\"], 3)\n\tioutil.WriteFile(settings[\"statusPath\"], b, permissions)\n\n\tsay(string(b), 5)\n\n\t//fmt.Println(string(b))\n}", "func respStat(file *schema.File) *protocol.StatResp {\n\treturn &protocol.StatResp{\n\t\tDataFileID: file.ID,\n\t\tName: file.Name,\n\t\tDataDirs: file.DataDirs,\n\t\tChecksum: file.Checksum,\n\t\tSize: file.Size,\n\t\tBirthtime: file.Birthtime,\n\t\tMTime: file.MTime,\n\t}\n}", "func (txn *Txn) Stat(dbi DBI) (*Stat, error) {\n\tvar _stat C.MDB_stat\n\tret := C.mdb_stat(txn._txn, C.MDB_dbi(dbi), &_stat)\n\tif ret != success {\n\t\treturn nil, errno(ret)\n\t}\n\tstat := Stat{PSize: uint(_stat.ms_psize),\n\t\tDepth: uint(_stat.ms_depth),\n\t\tBranchPages: uint64(_stat.ms_branch_pages),\n\t\tLeafPages: uint64(_stat.ms_leaf_pages),\n\t\tOverflowPages: uint64(_stat.ms_overflow_pages),\n\t\tEntries: uint64(_stat.ms_entries)}\n\treturn &stat, nil\n}", "func HandlerStats(stats stats.Stats) server.HandlerWrapper {\n\t// return a handler wrapper\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\t// return a function that returns a function\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\t// execute the handler\n\t\t\terr := h(ctx, req, rsp)\n\t\t\t// record the stats\n\t\t\tstats.Record(err)\n\t\t\t// return the error\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (f *httpFile) Stat() (os.FileInfo, error) {\n\treturn f, nil\n}", "func (f *httpFile) Stat() (os.FileInfo, error) {\n\treturn f, nil\n}", "func (f *httpFile) Stat() (os.FileInfo, error) {\n\treturn f, nil\n}", "func (d *Dao) Stat(c context.Context, oid int64) (f *favmdl.Folder, err error) {\n\tfid, table := hit(oid)\n\tf = &favmdl.Folder{}\n\trow := d.db.QueryRow(c, fmt.Sprintf(_statSQL, table), fid)\n\tif err = row.Scan(&f.PlayCount, &f.FavedCount, &f.ShareCount); err != nil {\n\t\tif err == sql.ErrNoRows {\n\t\t\terr = nil\n\t\t\tf = nil\n\t\t\treturn\n\t\t}\n\t\tlog.Error(\"Stat(%v) error(%+v)\", f, err)\n\t}\n\treturn\n}", "func (s *Server) statproc() {\n\tvar (\n\t\tv *volume.Volume\n\t\tolds *stat.Stats\n\t\tnews = new(stat.Stats)\n\t)\n\tfor {\n\t\tolds = s.info.Stats\n\t\t*news = *olds\n\t\ts.info.Stats = news // use news instead, for current display\n\t\tolds.Reset()\n\t\tfor _, v = range s.store.Volumes {\n\t\t\tv.Stats.Calc()\n\t\t\tolds.Merge(v.Stats)\n\t\t}\n\t\tolds.Calc()\n\t\ts.info.Stats = olds\n\t\ttime.Sleep(statDuration)\n\t}\n}", "func Stats(c *libvirt.Connect, uuid string) error {\n\t//Check exists\n\td, err := c.LookupDomainByUUIDString(uuid)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to lookup: %s\", err)\n\t}\n\n\t//Check is running\n\ts, _, err := d.GetState()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed check state: %s\", err)\n\t}\n\tif s != libvirt.DOMAIN_RUNNING {\n\t\treturn fmt.Errorf(\"domain not running: %d\", s)\n\t}\n\n\tmemStats, err := memStats(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"STAT: %+v\\n\", memStats)\n\tfmt.Printf(\"STAT Used: %+v\\n\", memStats.Available-memStats.Unused)\n\tfmt.Printf(\"STAT Last: %s\\n\", time.Unix(int64(memStats.LastUpdate), 0))\n\n\tcpuStats, total, err := cpuStats(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"%+v\\n\", cpuStats)\n\tfmt.Printf(\"Total: %+#v\\n\", total)\n\n\tnetStats, err := netStats(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"NET: %+v\\n\", netStats)\n\n\t_, dTotal, err := diskStats(d)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Printf(\"DISK: %+v\\n\", dTotal)\n\n\treturn nil\n}", "func (h *BasicStatsHandler) HandleConn(ctx context.Context, i stats.ConnStats) {\n}", "func NewStat() *Stat {\n\treturn &Stat{}\n}", "func PrintStats(w http.ResponseWriter, r *http.Request) {\n var b bytes.Buffer\n // Print the totals\n b.WriteString(\"# HELP logstat_request_total logstat_request_total\\n\")\n b.WriteString(\"# TYPE logstat_request_total counter\\n\")\n for service, sdata := range Stats {\n for status, stdata := range sdata {\n for method, mdata := range stdata {\n b.WriteString(\"logstat_request_total\")\n b.WriteString(\"{service=\\\"\")\n b.WriteString(service)\n b.WriteString(\"\\\",status=\\\"\")\n b.WriteString(strconv.Itoa(status))\n b.WriteString(\"\\\",method=\\\"\")\n b.WriteString(method)\n b.WriteString(\"\\\"} \")\n b.WriteString(strconv.Itoa(int(mdata[CounterRequests])))\n b.WriteString(\"\\n\")\n }\n }\n }\n // Print the time to serve\n b.WriteString(\"# HELP logstat_request_tts_total logstat_request_tts_total\\n\")\n b.WriteString(\"# TYPE logstat_request_tts_total counter\\n\")\n for service, sdata := range Stats {\n for status, stdata := range sdata {\n for method, mdata := range stdata {\n b.WriteString(\"logstat_request_tts_total\")\n b.WriteString(\"{service=\\\"\")\n b.WriteString(service)\n b.WriteString(\"\\\",status=\\\"\")\n b.WriteString(strconv.Itoa(status))\n b.WriteString(\"\\\",method=\\\"\")\n b.WriteString(method)\n b.WriteString(\"\\\"} \")\n b.WriteString(strconv.FormatFloat(mdata[CounterTts], 'f', 3, 64))\n b.WriteString(\"\\n\")\n }\n }\n }\n w.Write([]byte(b.String()))\n}", "func (s sys) Stat(path string) (os.FileInfo, error) {\n\treturn os.Stat(path)\n}", "func ProcStat(c *gin.Context) {\n\tres := CmdExec(\"cat /proc/stat | head -n 1 | awk '{$1=\\\"\\\";print}'\")\n\tresArray := strings.Split(res[0], \" \")\n\tvar cpu []int64\n\tvar totalcpu, idlecpu int64\n\tfor _, v := range resArray {\n\t\ttemp, err := strconv.ParseInt(v, 10, 64)\n\t\tif err == nil {\n\t\t\tcpu = append(cpu, temp)\n\t\t\ttotalcpu = totalcpu + temp\n\t\t}\n\t}\n\tidlecpu = cpu[3]\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"totalcpu\": totalcpu,\n\t\t\"idlecpu\": idlecpu,\n\t})\n}", "func (s *BaseCymbolListener) EnterStat(ctx *StatContext) {}", "func GetStatsHandler(c echo.Context) error {\n\treturn c.String(http.StatusOK, \"Hello, World!\")\n}", "func (mw *Stats) Handler(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tbeginning, recorder := mw.Begin(w)\n\n\t\th.ServeHTTP(recorder, r)\n\n\t\tmw.End(beginning, WithRecorder(recorder))\n\t})\n}", "func processStat(dsStats *Stats, dsRegexes todata.Regexes, dsTypes map[string]enum.DSType, cachegroup enum.CacheGroupName, server enum.CacheName, serverType enum.CacheType, stat string, value interface{}) (enum.DeliveryServiceName, Stat, error) {\n\tparts := strings.Split(stat, \".\")\n\tif len(parts) < 1 {\n\t\treturn \"\", nil, fmt.Errorf(\"stat has no initial part\")\n\t}\n\n\tswitch parts[0] {\n\tcase \"plugin\":\n\t\treturn processStatPlugin(dsStats, dsRegexes, dsTypes, cachegroup, server, serverType, stat, parts[1:], value)\n\tcase \"proxy\":\n\t\treturn \"\", nil, ErrNotProcessedStat\n\tdefault:\n\t\treturn \"\", nil, fmt.Errorf(\"stat has unknown initial part '%s'\", parts[0])\n\t}\n}", "func (m *Monitor) Stats(ctx *context.Context) {\n\tctx.JSON(m.Holder.GetStats())\n}", "func (c *Collection) Status(w http.ResponseWriter, req *http.Request) {\n\t// responds with current status of the analysis\n\t// checks systemtap is running, this is probably done via global variable?\n}", "func (s *SharemeService) Stat(c *gae.Context, key string) Share {\n\tdsk, err := datastore.DecodeKey(key)\n\tif err != nil {\n\t\tc.HTTPContext.ReturnStatus = http.StatusNotFound\n\t\treturn *noShare(fmt.Errorf(\"Error decoding key '%s': %s\", key, err))\n\t}\n\tstat := &Share{DSK: dsk}\n\terr = datastore.Get(c, dsk, stat)\n\tswitch err {\n\tcase datastore.ErrNoSuchEntity:\n\t\tc.HTTPContext.ReturnStatus = http.StatusNotFound\n\t\treturn *noShare(fmt.Errorf(\"Entity not found for key '%s' : %s\", key, err))\n\tdefault:\n\t\tc.HTTPContext.ReturnStatus = http.StatusInternalServerError\n\t\treturn *noShare(fmt.Errorf(\"Error retrieving data for key '%s' : %s\", key, err))\n\tcase nil:\n\t\tshare, err := s.storageService.Stat(c, stat.StorageKey)\n\t\tif err != nil || len(share.StorageKey) <= 0 {\n\t\t\t//TODO: delete from datastore\n\t\t\treturn *noShare(fmt.Errorf(\"No storage key for '%s' %s\", key, err))\n\t\t}\n\t\tstat.Key = key\n\t\tstat.Url = fmt.Sprintf(\"%s/%s/%s/%s\", c.HTTPContext.Container.BaseUrl(), InterfaceName, \"Get\", key)\n\t\tstat.Thumbnail = s.storageService.Thumbnail(c, stat.StorageKey, 50, 50)\n\t\tstat.StorageService = s.storageService\n\t\treturn *stat\n\t}\n}", "func GetStatEndpoint(s IService) endpoint.Endpoint {\n\treturn func(ctx context.Context, request interface{}) (response interface{}, err error) {\n\t\tcsReq := request.(GetStatRequest)\n\t\tsoireeID, err := s.GetStat(ctx, csReq.EstablishmentID, csReq.MenuID, csReq.SoireeBegin, csReq.SoireeEnd)\n\t\treturn GetStatResponse{\n\t\t\tSoireeID: soireeID,\n\t\t}, err\n\t}\n}", "func (b Base) Stat(sum string) (os.FileInfo, error) {\n\treturn os.Stat(b.blobPath(sum))\n}", "func (fsys *FS) stat(node mountlib.Node, stat *fuse.Stat_t) (errc int) {\n\tvar Size uint64\n\tvar Blocks uint64\n\tvar modTime time.Time\n\tvar Mode os.FileMode\n\tswitch x := node.(type) {\n\tcase *mountlib.Dir:\n\t\tmodTime = x.ModTime()\n\t\tMode = mountlib.DirPerms | fuse.S_IFDIR\n\tcase *mountlib.File:\n\t\tvar err error\n\t\tmodTime, Size, Blocks, err = x.Attr(mountlib.NoModTime)\n\t\tif err != nil {\n\t\t\treturn translateError(err)\n\t\t}\n\t\tMode = mountlib.FilePerms | fuse.S_IFREG\n\t}\n\t//stat.Dev = 1\n\tstat.Ino = node.Inode() // FIXME do we need to set the inode number?\n\tstat.Mode = uint32(Mode)\n\tstat.Nlink = 1\n\tstat.Uid = mountlib.UID\n\tstat.Gid = mountlib.GID\n\t//stat.Rdev\n\tstat.Size = int64(Size)\n\tt := fuse.NewTimespec(modTime)\n\tstat.Atim = t\n\tstat.Mtim = t\n\tstat.Ctim = t\n\tstat.Blksize = 512\n\tstat.Blocks = int64(Blocks)\n\tstat.Birthtim = t\n\t// fs.Debugf(nil, \"stat = %+v\", *stat)\n\treturn 0\n}", "func (d *Dao) UpStat(c context.Context, mid int64, dt string) (st *model.UpBaseStat, err error) {\n\t// try cache\n\tst, err = d.getUpBaseStatCache(c, mid, dt)\n\tif err != nil {\n\t\tlog.Error(\"d.getUpBaseStatCache(%d) error(%v)\", mid, err)\n\t\treturn\n\t}\n\tif st != nil {\n\t\treturn\n\t}\n\t// from hbase\n\tif st, err = d.BaseUpStat(c, mid, dt); st != nil {\n\t\td.AddCache(func() {\n\t\t\td.setUpBaseStatCache(context.TODO(), mid, dt, st)\n\t\t})\n\t}\n\treturn\n}", "func (s Service) GetStat(ctx context.Context, establishmentID, menuID int64, soireeBegin, soireeEnd time.Time) (int64, error) {\n\t// return s.svcsoiree.GetStat(ctx, establishmentID, menuID, soireeBegin, soireeEnd)\n\treturn 0, dbToHTTPErr(nil)\n}", "func (base *Base) Stat(ctx context.Context, path string) (storagedriver.FileInfo, error) {\n\tctx, done := dcontext.WithTrace(ctx)\n\tdefer done(\"%s.Stat(%q)\", base.Name(), path)\n\n\tif !storagedriver.PathRegexp.MatchString(path) && path != \"/\" {\n\t\treturn nil, storagedriver.InvalidPathError{Path: path, DriverName: base.StorageDriver.Name()}\n\t}\n\n\tstart := time.Now()\n\tfi, e := base.StorageDriver.Stat(ctx, path)\n\tstorageAction.WithValues(base.Name(), \"Stat\").UpdateSince(start)\n\treturn fi, base.setDriverName(e)\n}", "func (b *testBroker) Stat(pipe *Pipeline) (stat *Stat, err error) {\n\tif err := b.isServing(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tq := b.queue(pipe)\n\tif q == nil {\n\t\treturn nil, fmt.Errorf(\"undefined testQueue `%s`\", pipe.Name())\n\t}\n\n\treturn q.stat(), nil\n}", "func (reader *embedFileReader) Stat() (os.FileInfo, error) {\n\treturn nil, ErrNotImplemented\n}", "func (h *Handler) servePing(w http.ResponseWriter, r *http.Request) {}", "func jsonStatsHandler(w http.ResponseWriter, r *http.Request) {\n\trunID := r.FormValue(\"runID\")\n\tstats, histogram, err := resultStore.GetStats(runID)\n\tif err != nil {\n\t\thttputils.ReportError(w, r, err, fmt.Sprintf(\"Failed to retrieve stats for run %s\", runID))\n\t}\n\tsendJsonResponse(w, map[string]map[string]int{\"stats\": stats, \"histogram\": histogram})\n}", "func (*FindTopServerClientBrowserMonthlyStatsResponse_Stat) Descriptor() ([]byte, []int) {\n\treturn file_service_server_client_browser_monthly_stat_proto_rawDescGZIP(), []int{1, 0}\n}", "func Stat(t *kernel.Task, args arch.SyscallArguments) (uintptr, *kernel.SyscallControl, error) {\n\taddr := args[0].Pointer()\n\tstatAddr := args[1].Pointer()\n\n\tpath, dirPath, err := copyInPath(t, addr, false /* allowEmpty */)\n\tif err != nil {\n\t\treturn 0, nil, err\n\t}\n\n\treturn 0, nil, fileOpOn(t, linux.AT_FDCWD, path, true /* resolve */, func(root *fs.Dirent, d *fs.Dirent, _ uint) error {\n\t\treturn stat(t, d, dirPath, statAddr)\n\t})\n}", "func (i *Item) Stat() (os.FileInfo, error) { return i, nil }", "func (s LabelStat) ProcessStat(p StatProcessor) {\n\tp.ProcessLabelStat(s)\n}", "func (b *BlockProcessorQueue) Stat() StatResponse {\n\n\tresp := make(chan StatResponse)\n\treq := Stat{ResponseChan: resp}\n\n\tb.StatChan <- req\n\treturn <-resp\n\n}", "func index_handler(w http.ResponseWriter, r *http.Request){ \n // the w parameter is of the http.ResponseWriter type\n // it's *http.Request, we're reading through the value of the request. \n\n // let's just put some text on the screen.\n fmt.Fprintf(w, \"Whoa, go is neat!\")\n }", "func (a API) Stats(c echo.Context) error {\n\tvar output []OutputStat\n\tvar err error\n\n\tif output, err = a.maxRecord(); err != nil {\n\t\tc.Logger().Error(err.Error())\n\t\treturn c.JSON(http.StatusInternalServerError, \"please contact administrator\")\n\t}\n\tif len(output) == 0 {\n\t\treturn c.NoContent(http.StatusNoContent)\n\t}\n\treturn c.JSON(http.StatusOK, output)\n}", "func (r *RPCClientNode) Stat() (stat *Stat, err error) {\n\tvar s Stat\n\tif err = r.r.c.Call(\"node.Stat\", struct{}{}, &s); err != nil {\n\t\treturn\n\t}\n\treturn &s, nil\n}", "func (mw *Stats) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) {\n\tbeginning, recorder := mw.Begin(w)\n\n\tnext(recorder, r)\n\n\tmw.End(beginning, WithRecorder(recorder))\n}", "func (db *Database) Stat(property string) (string, error) {\n\treturn \"\", database.ErrNotFound\n}", "func stat(d *Driver, p string) (os.FileInfo, error) {\n\tif d.stat != nil {\n\t\treturn d.stat(p)\n\t}\n\treturn os.Stat(p)\n}", "func (s *Service) SetStat(c context.Context, arg *model.PlStat) (err error) {\n\tvar fav *favmdl.Folder\n\targFav := &favmdl.ArgFolder{Type: favmdl.TypePlayVideo, Fid: arg.Fid, Mid: arg.Mid, RealIP: \"\"}\n\tif fav, err = s.fav.Folder(c, argFav); err != nil || fav == nil {\n\t\tlog.Error(\"SetStat s.fav.Folder(%+v) error(%v)\", argFav, err)\n\t\treturn\n\t}\n\tlog.Info(\"service SetStat(%v) favState(%d)\", arg, fav.State)\n\tif fav.State == favmdl.StateNormal {\n\t\tif err = s.dao.SetPlStatCache(c, arg.Mid, arg.ID, arg); err != nil {\n\t\t\tlog.Error(\"SetStat s.dao.SetPlStatCache(%d,%d) error(%v)\", arg.Mid, arg.ID, err)\n\t\t}\n\t}\n\treturn\n}", "func DeleteHyperStatHandler(w http.ResponseWriter, req *http.Request) {\n\n\t// Get session values or redirect to Login\n\tsession, err := sessions.Store.Get(req, \"session\")\n\n\tif err != nil {\n\t\tlog.Println(\"error identifying session\")\n\t\thttp.Redirect(w, req, \"/login/\", 302)\n\t\treturn\n\t\t// in case of error\n\t}\n\n\t// Prep for user authentication\n\tsessionMap := getUserSessionValues(session)\n\n\tusername := sessionMap[\"username\"]\n\tloggedIn := sessionMap[\"loggedin\"]\n\tisAdmin := sessionMap[\"isAdmin\"]\n\n\t// Get variables from URL\n\tvars := mux.Vars(req)\n\tpk := vars[\"id\"]\n\ts := vars[\"stat\"]\n\n\tif len(pk) == 0 {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\tid, err := strconv.Atoi(pk)\n\tif err != nil {\n\t\thttp.Redirect(w, req, \"/\", http.StatusSeeOther)\n\t}\n\n\t// Load CharacterModel\n\tcm, err := database.PKLoadCharacterModel(db, int64(id))\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\t// Validate that User == Author\n\tIsAuthor := false\n\n\tif username == cm.Author.UserName {\n\t\tIsAuthor = true\n\t} else {\n\t\thttp.Redirect(w, req, \"/\", 302)\n\t}\n\n\tc := cm.Character\n\n\ttargetStat := c.Statistics[s]\n\n\twc := WebChar{\n\t\tCharacterModel: cm,\n\t\tIsAuthor: IsAuthor,\n\t\tSessionUser: username,\n\t\tIsLoggedIn: loggedIn,\n\t\tIsAdmin: isAdmin,\n\t\tStatistic: targetStat,\n\t}\n\n\tif req.Method == \"GET\" {\n\n\t\t// Render page\n\t\tRender(w, \"templates/delete_hyperstat.html\", wc)\n\n\t}\n\n\tif req.Method == \"POST\" {\n\n\t\ttargetStat.HyperStat = nil\n\n\t\tfmt.Println(c)\n\n\t\terr = database.UpdateCharacterModel(db, cm)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t} else {\n\t\t\tfmt.Println(\"Saved\")\n\t\t}\n\n\t\tfmt.Println(c)\n\n\t\turl := fmt.Sprintf(\"/view_character/%d\", cm.ID)\n\n\t\thttp.Redirect(w, req, url, http.StatusSeeOther)\n\t}\n}", "func (s *Basememcached_protocolListener) EnterGeneral_statistic(ctx *General_statisticContext) {}" ]
[ "0.7159668", "0.69401085", "0.68013096", "0.67716306", "0.6660826", "0.64846504", "0.637847", "0.6369455", "0.6312719", "0.61892563", "0.6170867", "0.6161586", "0.61407954", "0.61216813", "0.60604984", "0.6051216", "0.6028069", "0.5972511", "0.59578055", "0.5927742", "0.59213406", "0.5911659", "0.58882964", "0.58872944", "0.5884946", "0.5881297", "0.5844619", "0.584098", "0.58146346", "0.580959", "0.5797848", "0.5795165", "0.57921046", "0.5783728", "0.57812786", "0.5769419", "0.5766097", "0.57486534", "0.56913036", "0.56834215", "0.5665061", "0.56604433", "0.56577176", "0.56455415", "0.5629027", "0.5617626", "0.5596663", "0.55962896", "0.5594731", "0.55856574", "0.5582682", "0.5577709", "0.5568613", "0.55651623", "0.5564801", "0.5551469", "0.55366075", "0.55303276", "0.5518997", "0.5518997", "0.5518997", "0.5508504", "0.5504202", "0.55010664", "0.5498935", "0.54986256", "0.5489387", "0.54850316", "0.5483343", "0.54742795", "0.5471197", "0.5465229", "0.5462522", "0.5453916", "0.54396605", "0.5429116", "0.54283214", "0.5426159", "0.5422229", "0.54055196", "0.539787", "0.5387629", "0.5357662", "0.53557223", "0.535144", "0.53439677", "0.53432757", "0.53383034", "0.5333364", "0.53260577", "0.5319781", "0.5319644", "0.5311209", "0.530818", "0.5307821", "0.53042054", "0.5304193", "0.52941674", "0.5292288", "0.52907735" ]
0.65706605
5
/ ok so here is the problem. If we call opreduce on a core node, then we can only deliver pointwidths GREATER than our pointwidth and less than pointwidth + 6 right? but as a leaf we can potentially deliver pointwidths down to 0...
func (n *QTreeNode) OpReduce(pointwidth uint8, index uint64) (uint64, float64, float64, float64) { if !n.isLeaf && pointwidth < n.PointWidth() { lg.Panic("Bad pointwidth for core. See code comment") } if pointwidth > n.PointWidth()+PWFACTOR { lg.Panic("Can't guarantee this PW") } maxpw := n.PointWidth() + PWFACTOR pwdelta := pointwidth - n.PointWidth() width := int64(1) << pointwidth maxidx := 1 << (maxpw - pointwidth) if maxidx <= 0 || index >= uint64(maxidx) { lg.Critical("node is %s", n.TreePath()) lg.Panic("bad index", maxidx, index) } sum := 0.0 min := math.NaN() max := math.NaN() minset := false maxset := false count := uint64(0) if n.isLeaf { st := n.StartTime() + int64(index)*width et := st + width if n.vector_block.Len != 0 { for i := 0; i < int(n.vector_block.Len); i++ { if n.vector_block.Time[i] < st { continue } if n.vector_block.Time[i] >= et { break } v := n.vector_block.Value[i] sum += v if !minset || v < min { minset = true min = v } if !maxset || v > max { maxset = true max = v } count++ } } return count, min, sum / float64(count), max } else { s := index << pwdelta e := (index + 1) << pwdelta for i := s; i < e; i++ { if n.core_block.Count[i] == 0 { continue } count += n.core_block.Count[i] sum += n.core_block.Mean[i] * float64(n.core_block.Count[i]) if !minset || n.core_block.Min[i] < min { minset = true min = n.core_block.Min[i] } if !maxset || n.core_block.Max[i] > max { maxset = true max = n.core_block.Max[i] } } mean := sum / float64(count) return count, min, mean, max } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (h *BSTHandler) CalculateTreeWidth() {\n\n}", "func (n *node) width() int32 {\n\t// find two non-nil nodes\n\tfor i := 0; i < 8; i++ {\n\t\tif n.leafs[i] != nil && n.leafs[i].Center() != nil {\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tif n.leafs[j] != nil && n.leafs[j].Center() != nil {\n\t\t\t\t\tp1, p2 := n.leafs[i].Center(), n.leafs[j].Center()\n\t\t\t\t\t// calculate non-zero difference in one of the dimensions (any)\n\t\t\t\t\txwidth := math.Abs(float64(p1.X - p2.X))\n\t\t\t\t\tif xwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tywidth := math.Abs(float64(p1.Y - p2.Y))\n\t\t\t\t\tif ywidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t\tzwidth := math.Abs(float64(p1.Z - p2.Z))\n\t\t\t\t\tif zwidth > 0 {\n\t\t\t\t\t\treturn int32(xwidth)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn 0\n}", "func nodeWidth(n uint) uint {\n\treturn 2*(n-1) + 1\n}", "func (node *dcOctree) computeOctreeLeaf(d sdf.SDF3) {\n\tcorners := 0\n\tfor i := 0; i < 8; i++ {\n\t\tcornerPos := node.relToSDF(d, node.minOffset.Add(dcChildMinOffsets[i]))\n\t\tisSolid := d.Evaluate(cornerPos) < 0\n\t\tif isSolid {\n\t\t\tcorners = corners | (1 << i)\n\t\t}\n\t}\n\tif corners == 0 || corners == 255 {\n\t\t// voxel is fully inside or outside the volume: store nil for this child\n\t\treturn\n\t}\n\t// otherwise, the voxel contains the surface, so find the edge intersections\n\tconst maxCrossings = 6\n\tedgeCount := 0\n\tnormalSum := v3.Vec{X: 0, Y: 0, Z: 0}\n\tqefSolver := new(dcQefSolver)\n\tfor i := 0; i < 12 && edgeCount < maxCrossings; i++ {\n\t\tc1 := dcEdgevmap[i][0]\n\t\tc2 := dcEdgevmap[i][1]\n\t\tm1 := (corners >> c1) & 1\n\t\tm2 := (corners >> c2) & 1\n\t\tif (m1 == 1 && m2 == 1) || (m1 == 0 && m2 == 0) {\n\t\t\t// no zero crossing on this edge\n\t\t\tcontinue\n\t\t}\n\t\tp1 := node.relToSDF(d, node.minOffset.Add(dcChildMinOffsets[c1]))\n\t\tp2 := node.relToSDF(d, node.minOffset.Add(dcChildMinOffsets[c2]))\n\t\tp := dcApproximateZeroCrossingPosition(d, p1, p2)\n\t\tn := dcCalculateSurfaceNormal(d, p)\n\t\tqefSolver.Add(p, n)\n\t\tnormalSum = normalSum.Add(n)\n\t\tedgeCount++\n\t}\n\tqefPosition := qefSolver.Solve(node.rCond)\n\t// See documentation of the next function\n\tif node.lockVertices {\n\t\tqefPosition = dcBoundVertexPosition(d, node, qefPosition, qefSolver)\n\t}\n\tnode.drawInfo = &dcOctreeDrawInfo{\n\t\tindex: -1,\n\t\tcorners: corners,\n\t\tposition: qefPosition,\n\t\taverageNormal: normalSum.DivScalar(float64(edgeCount)).Normalize(),\n\t\tqef: qefSolver,\n\t}\n\tnode.kind = dcOctreeNodeTypeLeaf\n}", "func (self *Rectangle) Size1O(output *Point) *Point{\n return &Point{self.Object.Call(\"size\", output)}\n}", "func buildPodTopologySpreadMap(pod *v1.Pod, filteredNodes []*v1.Node, allNodes []*schedulernodeinfo.NodeInfo) (*podTopologySpreadMap, error) {\n\tif len(filteredNodes) == 0 || len(allNodes) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// initialize podTopologySpreadMap which will be used in Score plugin.\n\tm := newTopologySpreadConstraintsMap()\n\terr := m.initialize(pod, filteredNodes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// return if incoming pod doesn't have soft topology spread constraints.\n\tif m.constraints == nil {\n\t\treturn nil, nil\n\t}\n\n\tprocessAllNode := func(i int) {\n\t\tnodeInfo := allNodes[i]\n\t\tnode := nodeInfo.Node()\n\t\tif node == nil {\n\t\t\treturn\n\t\t}\n\t\t// (1) `node` should satisfy incoming pod's NodeSelector/NodeAffinity\n\t\t// (2) All topologyKeys need to be present in `node`\n\t\tif !predicates.PodMatchesNodeSelectorAndAffinityTerms(pod, node) ||\n\t\t\t!nodeLabelsMatchSpreadConstraints(node.Labels, m.constraints) {\n\t\t\treturn\n\t\t}\n\n\t\tfor _, c := range m.constraints {\n\t\t\tpair := topologyPair{key: c.topologyKey, value: node.Labels[c.topologyKey]}\n\t\t\t// If current topology pair is not associated with any candidate node,\n\t\t\t// continue to avoid unnecessary calculation.\n\t\t\tif m.topologyPairToPodCounts[pair] == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// <matchSum> indicates how many pods (on current node) match the <constraint>.\n\t\t\tmatchSum := int64(0)\n\t\t\tfor _, existingPod := range nodeInfo.Pods() {\n\t\t\t\tif c.selector.Matches(labels.Set(existingPod.Labels)) {\n\t\t\t\t\tmatchSum++\n\t\t\t\t}\n\t\t\t}\n\t\t\tatomic.AddInt64(m.topologyPairToPodCounts[pair], matchSum)\n\t\t}\n\t}\n\tworkqueue.ParallelizeUntil(context.Background(), 16, len(allNodes), processAllNode)\n\n\treturn m, nil\n}", "func getOffsetNodeCount(nodeCount uint64, offset int64, rounder func(float64) float64) uint64 {\n\treturn uint64(int64(nodeCount) + int64(rounder(float64(nodeCount)*float64(offset)/100)))\n}", "func (eps *EPS) alloc(id ecs.EntityID, t ecs.ComponentType) {\n\ti := len(eps.pt)\n\teps.pt = append(eps.pt, image.ZP)\n\teps.ix.flg = append(eps.ix.flg, 0)\n\teps.ix.key = append(eps.ix.key, 0)\n\teps.ix.ix = append(eps.ix.ix, i)\n}", "func xsliceGeometryCallback(tls *libc.TLS, p uintptr, nCoord int32, aCoord uintptr, pRes uintptr) int32 { /* speedtest1.c:1412:12: */\n\t*(*int32)(unsafe.Pointer(pRes)) = (libc.Bool32((*(*float64)(unsafe.Pointer(aCoord + uintptr(3)*8)) >= *(*sqlite3_rtree_dbl)(unsafe.Pointer((*sqlite3_rtree_geometry)(unsafe.Pointer(p)).aParam + uintptr(0)*8))) && (*(*float64)(unsafe.Pointer(aCoord + uintptr(2)*8)) <= *(*sqlite3_rtree_dbl)(unsafe.Pointer((*sqlite3_rtree_geometry)(unsafe.Pointer(p)).aParam + uintptr(1)*8)))))\n\treturn 0\n}", "func GxOuterWidth(value float64) *SimpleElement { return newSEFloat(\"gx:outerWidth\", value) }", "func (*Secp256k1) PointLen() int { return egPoint.MarshalSize() }", "func (mcts *MCTS) playout(state WorldModel) float64 {\n\titerState := state\n\tfor !iterState.IsTerminal() {\n\t\t//pick random action\n\t\taction := globalActions[rand.Intn(len(globalActions))]\n\t\t//applyeffects checks if its is executable gives the appropriate\n\t\t//reward and generates child\n\t\tstate := action.ApplyEffects(iterState)\n\t\t//state = state with new actions\n\t\titerState = state\n\n\t}\n\treturn iterState.Fitness - state.Fitness\n}", "func OfGeomPoints(points ...geom.Point) Winding { return Order{}.OfGeomPoints(points...) }", "func buildNormalizedNodeResourceMap(pods []*core_v1.Pod, nodes []*core_v1.Node) nodeResourceMap { // nolint: gocyclo\n\tnrm := nodeResourceMap{}\n\n\tfor _, n := range nodes {\n\t\tnrm[n.ObjectMeta.Name] = allocatedNodeResources{node: n}\n\t}\n\n\t// We sum the total allocated resources on every node from our list of pods.\n\t// Some strategies may wish to price pods based on their fraction of allocated\n\t// node resources, rather than the total resources available on a node. This\n\t// may punish lone pods that are initially scheduled onto large nodes, but this\n\t// may be desirable as it rightfully punishes applications that may cause\n\t// frequent node turnover.\n\tfor _, p := range pods {\n\t\tnr, ok := nrm[p.Spec.NodeName]\n\t\tif !ok {\n\t\t\tlog.Log.Warnw(\"unexpected missing node from NodeMap\", zap.String(\"nodeName\", p.Spec.NodeName))\n\t\t\tcontinue\n\t\t}\n\t\tnr.cpuUsed += sumPodResource(p, core_v1.ResourceCPU)\n\t\tnr.memoryUsed += sumPodResource(p, core_v1.ResourceMemory)\n\t\tnr.gpuUsed += sumPodResource(p, ResourceGPU)\n\t\tnrm[p.Spec.NodeName] = nr\n\t}\n\n\tfor k, v := range nrm {\n\t\tc := v.node.Status.Capacity.Cpu()\n\t\tif c != nil {\n\t\t\tv.cpuAvailable = c.MilliValue()\n\t\t}\n\n\t\tm := v.node.Status.Capacity.Memory()\n\t\tif m != nil {\n\t\t\tv.memoryAvailable = m.Value()\n\t\t}\n\n\t\tg := gpuCapacity(&v.node.Status.Capacity)\n\t\tif g != nil {\n\t\t\tv.gpuAvailable = g.Value()\n\t\t}\n\n\t\t// The ratio of cpuUsed / cpuAvailable is used for proportional scaling of\n\t\t// resources to \"normalize\" pod resource utilization to a full node. If\n\t\t// cpuUsed is 0 because the pods that are running have not made resource\n\t\t// requests, there's a possible divide by 0 in calling code so we default to\n\t\t// setting cpuUsed to cpuAvailable.\n\t\tif v.cpuUsed == 0 {\n\t\t\tv.cpuUsed = v.cpuAvailable\n\t\t}\n\n\t\tif v.memoryUsed == 0 {\n\t\t\tv.memoryUsed = v.memoryAvailable\n\t\t}\n\n\t\tif v.gpuUsed == 0 {\n\t\t\tv.gpuUsed = v.gpuAvailable\n\t\t}\n\n\t\tnrm[k] = v\n\t}\n\n\treturn nrm\n}", "func (n *node) chooseSplitAxis() int { //TODO Make the code prettier\n\t//[CSA 1]\n\t//Entries sorted by Latitude\n\tS_lat := 0.000000 //used to determine the best axis to split on\n\tbestK_lat := 0 //used to determine the best distribution\n\tminOverlap_lat := -1.000000\n\tbest_area_lat := -1.000000\n\tsortByLat := make([]entry, len(n.entries)) // len(sortByLat) == len(n.entries) is needed for copy to work\n\tcopy(sortByLat, n.entries)\n\tsort.Sort(byLat(sortByLat))\n\n\t//Entries sorted by Longitude\n\tS_long := 0.000000 //used to determine the best axis to split on\n\tbestK_long := 0 //used to determine the best distribution\n\tminOverlap_long := -1.000000\n\tbest_area_long := -1.000000\n\tsort.Sort(byLong(n.entries))\n\n\t//For each axis: M - 2m + 2 distributions of the M+1 entries into two groups are determined\n\td := (RTree_M - (2 * RTree_m) + 2)\n\tfor k := 1; k <= d; k++ {\n\t\t//By Latitude\n\t\tLatGroup1 := make([]entry, (RTree_m - 1 + k))\n\t\tLatGroup2 := make([]entry, (RTree_M - len(LatGroup1) + 1))\n\t\tcopy(LatGroup1, sortByLat[:RTree_m-1+k])\n\t\tcopy(LatGroup2, sortByLat[RTree_m-1+k:])\n\t\tlatGoodness := marginOf(LatGroup1) + marginOf(LatGroup2)\n\t\tS_lat += latGoodness\n\t\t// test if this distribution has the best overlap value for latitude\n\t\tmbr1 := mbrOf(LatGroup1...)\n\t\tmbr2 := mbrOf(LatGroup2...)\n\t\tif o := mbr1.OverlapWith(mbr2); o <= minOverlap_lat || minOverlap_lat == -1 {\n\t\t\tif o < minOverlap_lat || minOverlap_lat == -1 {\n\t\t\t\tbestK_lat = k //we have a new best\n\t\t\t\tminOverlap_lat = o\n\t\t\t\tbest_area_lat = mbr1.Area() + mbr2.Area()\n\t\t\t} else { //tie -> keep the distribution with the least area\n\t\t\t\ta_now := mbr1.Area() + mbr2.Area()\n\t\t\t\tif a_now < best_area_lat {\n\t\t\t\t\tbestK_lat = k //we have a new best\n\t\t\t\t\tminOverlap_lat = o\n\t\t\t\t\tbest_area_lat = mbr1.Area() + mbr2.Area()\n\t\t\t\t}\n\t\t\t}\n\t\t} //else don't change the value\n\n\t\t//By Longitude\n\t\tLongGroup1 := make([]entry, (RTree_m - 1 + k))\n\t\tLongGroup2 := make([]entry, (RTree_M - len(LongGroup1) + 1))\n\t\tcopy(LongGroup1, n.entries[:RTree_m-1+k])\n\t\tcopy(LongGroup2, n.entries[RTree_m-1+k:])\n\t\tlongGoodness := marginOf(LongGroup1) + marginOf(LongGroup2)\n\t\tS_long += longGoodness\n\t\t// test if this distribution has the best overlap value for longitude\n\t\tmbr1 = mbrOf(LongGroup1...)\n\t\tmbr2 = mbrOf(LongGroup2...)\n\t\tif o := mbr1.OverlapWith(mbr2); o <= minOverlap_long || minOverlap_long == -1 {\n\t\t\tif o < minOverlap_long || minOverlap_long == -1 {\n\t\t\t\tbestK_long = k //we have a new best\n\t\t\t\tminOverlap_long = o\n\t\t\t\tbest_area_long = mbr1.Area() + mbr2.Area()\n\t\t\t} else { //tie -> keep the distribution with the least area\n\t\t\t\ta_now := mbr1.Area() + mbr2.Area()\n\t\t\t\tif a_now < best_area_long {\n\t\t\t\t\tbestK_long = k //we have a new best\n\t\t\t\t\tminOverlap_long = o\n\t\t\t\t\tbest_area_long = mbr1.Area() + mbr2.Area()\n\t\t\t\t}\n\t\t\t}\n\t\t} //else don't change the value\n\t}\n\t//CSA2: Choose the axis with the minimum S as split axis\n\tif S_lat < S_long {\n\t\tn.entries = sortByLat\n\t\treturn bestK_lat\n\t}\n\treturn bestK_long\n}", "func (bpt *BplusTree) writeLayout() {\n\tleafIdx := 0\n\tnodeIdx := 0\n\tlevelIdx := 0\n\n\tif !bpt.initialized || bpt.rootKey.IsNil() {\n\t\treturn\n\t}\n\n\trootNode, _ := bpt.fetch(bpt.rootKey)\n\tif rootNode == nil {\n\t\tglog.Errorf(\"failed to fetch root key: %v. can not print the tree.\",\n\t\t\tbpt.rootKey)\n\t\treturn\n\t}\n\tglog.Infof(\"dumping the tree layout.. numChildren: %d\\n\",\n\t\tlen(rootNode.Children))\n\tnodeList := rootNode.Children\n\tnodeLensList := make([]int, 1)\n\tnodeLensList[0] = len(rootNode.Children)\n\tnumElems := nodeLensList[0]\n\tnumNodesAtLevel := 0\n\tprintLevel := true\n\tglog.Infof(\"level -- 0 <root: %v>\\n\", rootNode)\n\tif rootNode.IsLeaf {\n\t\treturn\n\t}\n\tfor i := 0; i < numElems; i++ {\n\t\tif printLevel {\n\t\t\tglog.Infof(\"level -- %d \", levelIdx+1)\n\t\t\tprintLevel = false\n\t\t}\n\t\tnode, _ := bpt.fetch(nodeList[i].NodeKey)\n\t\tif node == nil {\n\t\t\tglog.Errorf(\"failed to fetch root key: %v\", nodeList[i].NodeKey)\n\t\t\treturn\n\t\t}\n\n\t\tif node.IsLeaf {\n\t\t\tglog.Infof(\"level:%d <tree-L-node :%d, node: %v> \", levelIdx+1, leafIdx, node)\n\t\t\tleafIdx++\n\t\t} else {\n\t\t\tglog.Infof(\"level:%d <tree-I-node :%d, node: %v> \", levelIdx+1, nodeIdx, node)\n\t\t\tnodeList = append(nodeList, node.Children...)\n\t\t\tnumElems += len(node.Children)\n\t\t\tnumNodesAtLevel += len(node.Children)\n\t\t}\n\t\tnodeIdx++\n\t\tif nodeIdx >= nodeLensList[levelIdx] {\n\t\t\tnodeLensList = append(nodeLensList, numNodesAtLevel)\n\t\t\tlevelIdx++\n\t\t\tnodeIdx = 0\n\t\t\tnumNodesAtLevel = 0\n\t\t\tglog.Infof(\"\\n\")\n\t\t\tprintLevel = true\n\t\t}\n\t}\n\tglog.Infof(\"done.. dumping the layout\\n\")\n\tglog.Infof(\"----------------------------\\n\")\n}", "func Pwidth(wp, cw, defval float64) float64 {\n\tif wp == 0 {\n\t\treturn defval\n\t}\n\treturn (wp / 100) * cw\n}", "func normalizeProcessingUnitsOrNodes(pu, nodes int, computeType spannerv1beta1.ComputeType) int {\n\tswitch computeType {\n\tcase spannerv1beta1.ComputeTypePU:\n\t\treturn pu\n\tcase spannerv1beta1.ComputeTypeNode:\n\t\treturn nodes * 1000\n\tdefault:\n\t\treturn -1\n\t}\n}", "func (self *Graphics) AlignTo1O(parent interface{}, position int) interface{}{\n return self.Object.Call(\"alignTo\", parent, position)\n}", "func (m *podTopologySpreadMap) initialize(pod *v1.Pod, filteredNodes []*v1.Node) error {\n\tconstraints, err := filterSoftTopologySpreadConstraints(pod.Spec.TopologySpreadConstraints)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif constraints == nil {\n\t\treturn nil\n\t}\n\tm.constraints = constraints\n\tfor _, node := range filteredNodes {\n\t\tif !nodeLabelsMatchSpreadConstraints(node.Labels, m.constraints) {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, constraint := range m.constraints {\n\t\t\tpair := topologyPair{key: constraint.topologyKey, value: node.Labels[constraint.topologyKey]}\n\t\t\tif m.topologyPairToPodCounts[pair] == nil {\n\t\t\t\tm.topologyPairToPodCounts[pair] = new(int64)\n\t\t\t}\n\t\t}\n\t\tm.nodeNameSet[node.Name] = struct{}{}\n\t\t// For those nodes which don't have all required topologyKeys present, it's intentional to leave\n\t\t// their entries absent in nodeNameSet, so that we're able to score them to 0 afterwards.\n\t}\n\treturn nil\n}", "func init() {\n\tred := color.RGBA{255, 0, 0, 255}\n\tblue := color.RGBA{0, 0, 255, 255}\n\n\t//!+indirect\n\ttype ColoredPoint struct {\n\t\t*Point\n\t\tColor color.RGBA\n\t}\n\n\tp := ColoredPoint{&Point{1, 1}, red}\n\tq := ColoredPoint{&Point{5, 4}, blue}\n\tfmt.Println(p.Distance(*q.Point)) // \"5\"\n\tq.Point = p.Point // p and q now share the same Point\n\tp.ScaleBy(2)\n\tfmt.Println(*p.Point, *q.Point) // \"{2 2} {2 2}\"\n\tfmt.Println(p.Distance(*q.Point)) // \"0\"\n\t//!-indirect\n}", "func (src *prometheusMetricsSource) buildPoint(name string, m *dto.Metric, now int64, tags map[string]string) []*MetricPoint {\n\tvar result []*MetricPoint\n\tif m.Gauge != nil {\n\t\tif !math.IsNaN(m.GetGauge().GetValue()) {\n\t\t\tpoint := src.metricPoint(name+\".gauge\", float64(m.GetGauge().GetValue()), now, src.source, tags)\n\t\t\tresult = src.filterAppend(result, point)\n\t\t}\n\t} else if m.Counter != nil {\n\t\tif !math.IsNaN(m.GetCounter().GetValue()) {\n\t\t\tpoint := src.metricPoint(name+\".counter\", float64(m.GetCounter().GetValue()), now, src.source, tags)\n\t\t\tresult = src.filterAppend(result, point)\n\t\t}\n\t} else if m.Untyped != nil {\n\t\tif !math.IsNaN(m.GetUntyped().GetValue()) {\n\t\t\tpoint := src.metricPoint(name+\".value\", float64(m.GetUntyped().GetValue()), now, src.source, tags)\n\t\t\tresult = src.filterAppend(result, point)\n\t\t}\n\t}\n\treturn result\n}", "func updateNodes(num_bytes uint, block_start uint, pos uint, ringbuffer []byte, ringbuffer_mask uint, params *encoderParams, max_backward_limit uint, starting_dist_cache []int, num_matches uint, matches []backwardMatch, model *zopfliCostModel, queue *startPosQueue, nodes []zopfliNode) uint {\n\tvar cur_ix uint = block_start + pos\n\tvar cur_ix_masked uint = cur_ix & ringbuffer_mask\n\tvar max_distance uint = brotli_min_size_t(cur_ix, max_backward_limit)\n\tvar max_len uint = num_bytes - pos\n\tvar max_zopfli_len uint = maxZopfliLen(params)\n\tvar max_iters uint = maxZopfliCandidates(params)\n\tvar min_len uint\n\tvar result uint = 0\n\tvar k uint\n\tvar gap uint = 0\n\n\tevaluateNode(block_start, pos, max_backward_limit, gap, starting_dist_cache, model, queue, nodes)\n\t{\n\t\tvar posdata *posData = startPosQueueAt(queue, 0)\n\t\tvar min_cost float32 = (posdata.cost + zopfliCostModelGetMinCostCmd(model) + zopfliCostModelGetLiteralCosts(model, posdata.pos, pos))\n\t\tmin_len = computeMinimumCopyLength(min_cost, nodes, num_bytes, pos)\n\t}\n\n\t/* Go over the command starting positions in order of increasing cost\n\t difference. */\n\tfor k = 0; k < max_iters && k < startPosQueueSize(queue); k++ {\n\t\tvar posdata *posData = startPosQueueAt(queue, k)\n\t\tvar start uint = posdata.pos\n\t\tvar inscode uint16 = getInsertLengthCode(pos - start)\n\t\tvar start_costdiff float32 = posdata.costdiff\n\t\tvar base_cost float32 = start_costdiff + float32(getInsertExtra(inscode)) + zopfliCostModelGetLiteralCosts(model, 0, pos)\n\t\tvar best_len uint = min_len - 1\n\t\tvar j uint = 0\n\t\t/* Look for last distance matches using the distance cache from this\n\t\t starting position. */\n\t\tfor ; j < numDistanceShortCodes && best_len < max_len; j++ {\n\t\t\tvar idx uint = uint(kDistanceCacheIndex[j])\n\t\t\tvar backward uint = uint(posdata.distance_cache[idx] + kDistanceCacheOffset[j])\n\t\t\tvar prev_ix uint = cur_ix - backward\n\t\t\tvar len uint = 0\n\t\t\tvar continuation byte = ringbuffer[cur_ix_masked+best_len]\n\t\t\tif cur_ix_masked+best_len > ringbuffer_mask {\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif backward > max_distance+gap {\n\t\t\t\t/* Word dictionary -> ignore. */\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif backward <= max_distance {\n\t\t\t\t/* Regular backward reference. */\n\t\t\t\tif prev_ix >= cur_ix {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tprev_ix &= ringbuffer_mask\n\t\t\t\tif prev_ix+best_len > ringbuffer_mask || continuation != ringbuffer[prev_ix+best_len] {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlen = findMatchLengthWithLimit(ringbuffer[prev_ix:], ringbuffer[cur_ix_masked:], max_len)\n\t\t\t} else {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t{\n\t\t\t\tvar dist_cost float32 = base_cost + zopfliCostModelGetDistanceCost(model, j)\n\t\t\t\tvar l uint\n\t\t\t\tfor l = best_len + 1; l <= len; l++ {\n\t\t\t\t\tvar copycode uint16 = getCopyLengthCode(l)\n\t\t\t\t\tvar cmdcode uint16 = combineLengthCodes(inscode, copycode, j == 0)\n\t\t\t\t\tvar tmp float32\n\t\t\t\t\tif cmdcode < 128 {\n\t\t\t\t\t\ttmp = base_cost\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttmp = dist_cost\n\t\t\t\t\t}\n\t\t\t\t\tvar cost float32 = tmp + float32(getCopyExtra(copycode)) + zopfliCostModelGetCommandCost(model, cmdcode)\n\t\t\t\t\tif cost < nodes[pos+l].u.cost {\n\t\t\t\t\t\tupdateZopfliNode(nodes, pos, start, l, l, backward, j+1, cost)\n\t\t\t\t\t\tresult = brotli_max_size_t(result, l)\n\t\t\t\t\t}\n\n\t\t\t\t\tbest_len = l\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t/* At higher iterations look only for new last distance matches, since\n\t\t looking only for new command start positions with the same distances\n\t\t does not help much. */\n\t\tif k >= 2 {\n\t\t\tcontinue\n\t\t}\n\t\t{\n\t\t\t/* Loop through all possible copy lengths at this position. */\n\t\t\tvar len uint = min_len\n\t\t\tfor j = 0; j < num_matches; j++ {\n\t\t\t\tvar match backwardMatch = matches[j]\n\t\t\t\tvar dist uint = uint(match.distance)\n\t\t\t\tvar is_dictionary_match bool = (dist > max_distance+gap)\n\t\t\t\tvar dist_code uint = dist + numDistanceShortCodes - 1\n\t\t\t\tvar dist_symbol uint16\n\t\t\t\tvar distextra uint32\n\t\t\t\tvar distnumextra uint32\n\t\t\t\tvar dist_cost float32\n\t\t\t\tvar max_match_len uint\n\t\t\t\t/* We already tried all possible last distance matches, so we can use\n\t\t\t\t normal distance code here. */\n\t\t\t\tprefixEncodeCopyDistance(dist_code, uint(params.dist.num_direct_distance_codes), uint(params.dist.distance_postfix_bits), &dist_symbol, &distextra)\n\n\t\t\t\tdistnumextra = uint32(dist_symbol) >> 10\n\t\t\t\tdist_cost = base_cost + float32(distnumextra) + zopfliCostModelGetDistanceCost(model, uint(dist_symbol)&0x3FF)\n\n\t\t\t\t/* Try all copy lengths up until the maximum copy length corresponding\n\t\t\t\t to this distance. If the distance refers to the static dictionary, or\n\t\t\t\t the maximum length is long enough, try only one maximum length. */\n\t\t\t\tmax_match_len = backwardMatchLength(&match)\n\n\t\t\t\tif len < max_match_len && (is_dictionary_match || max_match_len > max_zopfli_len) {\n\t\t\t\t\tlen = max_match_len\n\t\t\t\t}\n\n\t\t\t\tfor ; len <= max_match_len; len++ {\n\t\t\t\t\tvar len_code uint\n\t\t\t\t\tif is_dictionary_match {\n\t\t\t\t\t\tlen_code = backwardMatchLengthCode(&match)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlen_code = len\n\t\t\t\t\t}\n\t\t\t\t\tvar copycode uint16 = getCopyLengthCode(len_code)\n\t\t\t\t\tvar cmdcode uint16 = combineLengthCodes(inscode, copycode, false)\n\t\t\t\t\tvar cost float32 = dist_cost + float32(getCopyExtra(copycode)) + zopfliCostModelGetCommandCost(model, cmdcode)\n\t\t\t\t\tif cost < nodes[pos+len].u.cost {\n\t\t\t\t\t\tupdateZopfliNode(nodes, pos, start, uint(len), len_code, dist, 0, cost)\n\t\t\t\t\t\tif len > result {\n\t\t\t\t\t\t\tresult = len\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func PMOVSXBW(mx, x operand.Op) { ctx.PMOVSXBW(mx, x) }", "func (c *curve) PointLen() int {\n\treturn (c.P.BitLen() + 7 + 1) / 8\n}", "func (a axes) drawPoint(p *vg.Painter, xy xyer, cs vg.CoordinateSystem, l Line, pointNumber int) {\n\tx, y, isEnvelope := xy.XY(l)\n\n\t// add number of NaNs leading pointNumber to pointNumber.\n\ttargetNumber := pointNumber\n\tfor i, v := range x {\n\t\tif i > targetNumber {\n\t\t\tbreak\n\t\t}\n\t\tif math.IsNaN(v) {\n\t\t\tpointNumber++\n\t\t}\n\t}\n\n\tif len(x) <= pointNumber || len(y) <= pointNumber || pointNumber < 0 {\n\t\treturn\n\t}\n\tp.SetFont(font1)\n\tlabels := make([]vg.FloatText, 2)\n\tif isEnvelope {\n\t\tif n := len(x); n != len(y) || pointNumber+2 > n {\n\t\t\treturn\n\t\t} else {\n\t\t\txp, yp := x[pointNumber], y[pointNumber]\n\t\t\txp2, yp2 := x[n-pointNumber-2], y[n-pointNumber-2]\n\t\t\tx = []float64{xp, xp2}\n\t\t\ty = []float64{yp, yp2}\n\t\t\tlabels[0] = vg.FloatText{X: xp, Y: yp, S: fmt.Sprintf(\"(%.4g, %.4g)\", xp, yp), Align: 5}\n\t\t\tlabels[1] = vg.FloatText{X: xp2, Y: yp2, S: fmt.Sprintf(\"(%.4g, %.4g)\", xp2, yp2), Align: 1}\n\t\t}\n\t} else {\n\t\txp, yp := x[pointNumber], y[pointNumber]\n\t\tx = []float64{xp}\n\t\ty = []float64{yp}\n\t\tvar s string\n\t\tif xyp, ok := xy.(xyPolar); ok {\n\t\t\txstr := \"\"\n\t\t\tif xyp.rmin == 0 && xyp.rmax == 0 { // polar\n\t\t\t\tif len(l.X) > pointNumber && pointNumber >= 0 {\n\t\t\t\t\txstr = fmt.Sprintf(\"%.4g, \", l.X[pointNumber])\n\t\t\t\t}\n\t\t\t\ts = xstr + xmath.Absang(complex(yp, xp), \"%.4g@%.0f\")\n\t\t\t} else { // ring\n\t\t\t\ts = fmt.Sprintf(\"%.4g@%.1f\", l.X[pointNumber], 180.0*l.Y[pointNumber]/math.Pi)\n\t\t\t}\n\t\t} else {\n\t\t\ts = fmt.Sprintf(\"(%.4g, %.4g)\", xp, yp)\n\t\t}\n\t\tlabels[0] = vg.FloatText{X: xp, Y: yp, S: s, Align: 1}\n\t\tlabels = labels[:1]\n\t}\n\n\tsize := l.Style.Marker.Size\n\tif size == 0 {\n\t\tsize = l.Style.Line.Width\n\t}\n\tif size == 0 {\n\t\tsize = 9\n\t} else {\n\t\tsize *= 3\n\t}\n\tc := a.plot.Style.Order.Get(l.Style.Marker.Color, l.Id+1).Color()\n\tp.SetColor(c)\n\tp.Add(vg.FloatCircles{X: x, Y: y, CoordinateSystem: cs, Radius: size, Fill: true})\n\trect := a.inside.Bounds()\n\tfor _, l := range labels {\n\t\tl.CoordinateSystem = cs\n\t\tl.Rect = rect\n\n\t\t// Change the alignment, if the label would be placed at a picture boundary.\n\t\tx0, y0 := cs.Pixel(l.X, l.Y, rect)\n\t\tif l.Align == 1 && y0 < 30 {\n\t\t\tl.Align = 5\n\t\t} else if l.Align == 5 && y0 > rect.Max.Y-30 {\n\t\t\tl.Align = 1\n\t\t}\n\t\tif x0 < 50 {\n\t\t\tif l.Align == 1 {\n\t\t\t\tl.Align = 0\n\t\t\t} else if l.Align == 5 {\n\t\t\t\tl.Align = 6\n\t\t\t}\n\t\t} else if x0 > rect.Max.X-50 {\n\t\t\tif l.Align == 1 {\n\t\t\t\tl.Align = 2\n\t\t\t} else if l.Align == 5 {\n\t\t\t\tl.Align = 4\n\t\t\t}\n\t\t}\n\n\t\t// Place the label above or below with the offset of the marker's radius.\n\t\tif l.Align <= 2 { // Label is above point.\n\t\t\tl.Yoff = -size\n\t\t} else if l.Align >= 4 { // Label is below point\n\t\t\tl.Yoff = size\n\t\t}\n\n\t\t// Fill background rectangle of the label.\n\t\tx, y, w, h := l.Extent(p)\n\t\tsaveColor := p.GetColor()\n\t\tp.SetColor(a.bg)\n\t\tp.Add(vg.Rectangle{X: x, Y: y, W: w, H: h, Fill: true})\n\t\tp.SetColor(saveColor)\n\t\tp.Add(l)\n\t}\n}", "func TestPaperValidation(t *testing.T) {\n\tsrc, dst := readFixtures(\"testdata/paper/src.json\", \"testdata/paper/dst.json\")\n\n\tsm := newSubtreeMatcher()\n\tmappings := sm.Match(src, dst)\n\n\tassert.Equal(t, 10, mappings.Size())\n\n\ts := getChild(src, 0, 2, 1)\n\td := getChild(dst, 0, 2, 1)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 3)\n\td = getChild(dst, 0, 2, 3)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 4, 0, 0)\n\td = getChild(dst, 0, 2, 4, 0, 0)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 4, 0, 1)\n\td = getChild(dst, 0, 2, 4, 0, 2, 1)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\n\tbum := newBottomUpMatcher(mappings)\n\tbum.simThreshold = 0.2\n\tmappings = bum.Match(src, dst)\n\n\t// 15 = 10 from top-down + 5 containers + 4 recovery mapping\n\tassert.Equal(t, 19, mappings.Size())\n\n\t// containers\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", src, dst)\n\ts = getChild(src, 0)\n\td = getChild(dst, 0)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2)\n\td = getChild(dst, 0, 2)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 4)\n\td = getChild(dst, 0, 2, 4)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 4, 0)\n\td = getChild(dst, 0, 2, 4, 0)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\n\t// recovery\n\ts = getChild(src, 0, 0)\n\td = getChild(dst, 0, 0)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 1)\n\td = getChild(dst, 0, 1)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 0)\n\td = getChild(dst, 0, 2, 0)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n\ts = getChild(src, 0, 2, 2)\n\td = getChild(dst, 0, 2, 2)\n\tassert.True(t, mappings.Has(s, d), \"%v = %v mapping not found\", s, d)\n}", "func cleanGeometryInfo(typ KernelInfoType, geometryFlags int,\n\tgeometryInfo *C.GeometryInfo) {\n\n\t// special handling of missing values in input string\n\tswitch typ {\n\n\t// Shape Kernel Defaults\n\tcase KERNEL_UNITY:\n\t\tif (geometryFlags & WIDTHVALUE) == 0 {\n\t\t\tgeometryInfo.rho = 1.0 /* Default scale = 1.0, zero is valid */\n\t\t}\n\n\tcase KERNEL_SQUARE, KERNEL_DIAMOND, KERNEL_OCTAGON,\n\t\tKERNEL_DISK, KERNEL_PLUS, KERNEL_CROSS:\n\t\tif (geometryFlags & HEIGHTVALUE) == 0 {\n\t\t\tgeometryInfo.sigma = 1.0 /* Default scale = 1.0, zero is valid */\n\t\t}\n\n\tcase KERNEL_RING:\n\t\tif (geometryFlags & XVALUE) == 0 {\n\t\t\tgeometryInfo.xi = 1.0 /* Default scale = 1.0, zero is valid */\n\t\t}\n\n\tcase KERNEL_RECTANGLE:\n\t\t// Rectangle - set size defaults\n\t\tif (geometryFlags & WIDTHVALUE) == 0 { /* if no width then */\n\t\t\tgeometryInfo.rho = geometryInfo.sigma /* then width = height */\n\t\t}\n\t\tif geometryInfo.rho < 1.0 { /* if width too small */\n\t\t\tgeometryInfo.rho = 3 /* then width = 3 */\n\t\t}\n\t\tif geometryInfo.sigma < 1.0 { /* if height too small */\n\t\t\tgeometryInfo.sigma = geometryInfo.rho /* then height = width */\n\t\t}\n\t\t//TODO - casting shenanigans\n\t\t//if ((geometryFlags & XVALUE) == 0) { /* center offset if not defined */\n\t\t//\tgeometryInfo.xi = (double)(((ssize_t)geometryInfo.rho-1)/2);\n\t\t//}\n\t\t//if ((geometryFlags & YVALUE) == 0) {\n\t\t//\tgeometryInfo.psi = (double)(((ssize_t)geometryInfo.sigma-1)/2);\n\t\t//}\n\n\t// Distance Kernel Defaults\n\tcase KERNEL_CHEBYSHEV, KERNEL_MANHATTAN, KERNEL_OCTAGONAL, KERNEL_EUCLIDEAN:\n\t\tif (geometryFlags & HEIGHTVALUE) == 0 { /* no distance scale */\n\t\t\tgeometryInfo.sigma = 100.0 /* default distance scaling */\n\t\t}\n\t\t//TODO casting shenanigans\n\t\t//else if ((flags & AspectValue ) != 0) { /* '!' flag */\n\t\t//\tgeometryInfo.sigma = QuantumRange/(geometryInfo.sigma+1); /* maximum pixel distance */\n\t\t//}\n\t\t//else if ((flags & PercentValue ) != 0) { /* '%' flag */\n\t\t//\tgeometryInfo.sigma *= QuantumRange/100.0; /* percentage of color range */\n\t\t//}\n\n\t}\n}", "func (s *QuasiSampler) collectPoints(filterBounds bool) []f64.Vec2 {\n\tvar pointlist []f64.Vec2\n\n\tit := NewTileLeafIterator(s.root)\n\tfor {\n\t\tpt := it.GetShape().GetP1()\n\t\t// Only \"pentagonal\" tiles generate sampling points.\n\t\tif it.GetShape().IsSamplingType() {\n\t\t\timportance := s.GetImportanceAt_bounded(pt)\n\n\t\t\t// Threshold the function against the F-Code value.\n\t\t\tif importance >= calcFCodeValue(it.GetShape().GetFCode(), it.GetShape().GetLevel()) {\n\t\t\t\t// Get the displaced point using the lookup table.\n\t\t\t\tpt_displaced := it.GetShape().GetDisplacedSamplingPoint(importance)\n\n\t\t\t\tif !filterBounds ||\n\t\t\t\t\t(pt_displaced.X >= 0 && pt_displaced.X < s.width &&\n\t\t\t\t\t\tpt_displaced.Y >= 0 && pt_displaced.Y < s.height) {\n\t\t\t\t\tpointlist = append(pointlist, pt_displaced)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif !it.Next() {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn pointlist\n}", "func AllocateLightmapRect(node *LightmapNode, width int32, height int32) *LightmapNode {\n\t// Check child nodes if they exist\n\tif len(node.Nodes) > 0 {\n\t\tnewNode := AllocateLightmapRect(&node.Nodes[0], width, height)\n\t\tif newNode != nil {\n\t\t\treturn newNode\n\t\t}\n\t\treturn AllocateLightmapRect(&node.Nodes[1], width, height)\n\t}\n\n\t// Already used\n\tif node.Filled {\n\t\treturn nil\n\t}\n\n\t// Too small\n\tif node.Width < width || node.Height < height {\n\t\treturn nil\n\t}\n\n\t// Allocate if it is a perfect fit\n\tif node.Width == width && node.Height == height {\n\t\tnode.Filled = true\n\t\treturn node\n\t}\n\n\t// Split by width or height\n\tvar nodes []LightmapNode\n\tif (node.Width - width) > (node.Height - height) {\n\t\tnodes = []LightmapNode{\n\t\t\tLightmapNode{\n\t\t\t\tX: node.X,\n\t\t\t\tY: node.Y,\n\t\t\t\tWidth: width,\n\t\t\t\tHeight: node.Height,\n\t\t\t\tNodes: []LightmapNode{},\n\t\t\t\tFilled: false,\n\t\t\t},\n\t\t\tLightmapNode{\n\t\t\t\tX: node.X + width,\n\t\t\t\tY: node.Y,\n\t\t\t\tWidth: node.Width - width,\n\t\t\t\tHeight: node.Height,\n\t\t\t\tNodes: []LightmapNode{},\n\t\t\t\tFilled: false,\n\t\t\t},\n\t\t}\n\t} else {\n\t\tnodes = []LightmapNode{\n\t\t\tLightmapNode{\n\t\t\t\tX: node.X,\n\t\t\t\tY: node.Y,\n\t\t\t\tWidth: node.Width,\n\t\t\t\tHeight: height,\n\t\t\t\tNodes: []LightmapNode{},\n\t\t\t\tFilled: false,\n\t\t\t},\n\t\t\tLightmapNode{\n\t\t\t\tX: node.X,\n\t\t\t\tY: node.Y + height,\n\t\t\t\tWidth: node.Width,\n\t\t\t\tHeight: node.Height - height,\n\t\t\t\tNodes: []LightmapNode{},\n\t\t\t\tFilled: false,\n\t\t\t},\n\t\t}\n\t}\n\tnode.Nodes = nodes\n\treturn AllocateLightmapRect(&node.Nodes[0], width, height)\n}", "func (m *metricFlinkOperatorWatermarkOutput) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func initAdjMap(pxMap [][]bool) {\n\tfor x := 0; x < sizeX; x++ {\n\t\tfor y := 0; y < sizeY; y++ {\n\t\t\tif pxMap[x][y] && nodeMap[x][y].nodeType != \"dEnd\" && nodeMap[x][y].nodeType != \"path\" {\n\t\t\t\t//scanning x++\n\t\t\t\tix := x\n\t\t\t\tiy := y\n\t\t\t\tfor pxMap[ix][y] {\n\t\t\t\t\tif ix+1 < sizeX {\n\t\t\t\t\t\tix++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif nodeMap[ix][iy].nodeType != \"dEnd\" && nodeMap[ix][iy].nodeType != \"wall\" && nodeMap[ix][iy].nodeType != \"path\" {\n\t\t\t\t\t\tnodeMap[x][y].weights = append(nodeMap[x][y].weights, ix-x)\n\t\t\t\t\t\tnodeMap[x][y].adjacentNodes = append(nodeMap[x][y].adjacentNodes, &nodeMap[ix][iy])\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//scanning y++\n\t\t\t\tix = x\n\t\t\t\tiy = y\n\t\t\t\tfor pxMap[x][iy] {\n\t\t\t\t\tif iy+1 < sizeY {\n\t\t\t\t\t\tiy++\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif nodeMap[ix][iy].nodeType != \"dEnd\" && nodeMap[ix][iy].nodeType != \"wall\" && nodeMap[ix][iy].nodeType != \"path\" {\n\t\t\t\t\t\tnodeMap[x][y].weights = append(nodeMap[x][y].weights, iy-y)\n\t\t\t\t\t\tnodeMap[x][y].adjacentNodes = append(nodeMap[x][y].adjacentNodes, &nodeMap[ix][iy])\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//scanning x--\n\t\t\t\tix = x\n\t\t\t\tiy = y\n\t\t\t\tfor pxMap[ix][y] {\n\t\t\t\t\tif ix-1 >= 0 {\n\t\t\t\t\t\tix--\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tif nodeMap[ix][iy].nodeType != \"dEnd\" && nodeMap[ix][iy].nodeType != \"wall\" && nodeMap[ix][iy].nodeType != \"path\" {\n\t\t\t\t\t\tnodeMap[x][y].weights = append(nodeMap[x][y].weights, x-ix)\n\t\t\t\t\t\tnodeMap[x][y].adjacentNodes = append(nodeMap[x][y].adjacentNodes, &nodeMap[ix][iy])\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t//scanning y--\n\t\t\t\tix = x\n\t\t\t\tiy = y\n\t\t\t\tfor pxMap[x][iy] {\n\t\t\t\t\tif iy-1 >= 0 {\n\t\t\t\t\t\tiy--\n\t\t\t\t\t} else {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\tif nodeMap[ix][iy].nodeType != \"dEnd\" && nodeMap[ix][iy].nodeType != \"wall\" && nodeMap[ix][iy].nodeType != \"path\" {\n\t\t\t\t\t\tnodeMap[x][y].weights = append(nodeMap[x][y].weights, y-iy)\n\t\t\t\t\t\tnodeMap[x][y].adjacentNodes = append(nodeMap[x][y].adjacentNodes, &nodeMap[ix][iy])\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func (cm ConcurrenceModel) getCorePoints(eps float64, minPts int) map[int]int {\n\t// -------------------------------------------------------------------------\n\t// step 1: compute the density of all points' neighborhoods\n\tn := cm.n\n\tdensities := make([]int, n)\n\tfor pt := 0; pt < n; pt++ {\n\t\trowPt := cm.concurrences[pt]\n\t\tdensity := cm.cardinalities[pt]\n\t\tfor neighbor, similarity := range rowPt {\n\t\t\tif similarity+eps >= 1.0 {\n\t\t\t\tdensity += cm.cardinalities[neighbor]\n\t\t\t}\n\t\t}\n\t\tdensities[pt] = density\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// step 2: generate a list of points with dense neighborhoods\n\tcorePts := map[int]int{}\n\tfor pt, density := range densities {\n\t\tif density >= minPts {\n\t\t\tcorePts[pt] = density\n\t\t}\n\t}\n\n\t// -------------------------------------------------------------------------\n\t// step 3: return the result\n\treturn corePts\n}", "func MINPD(mx, x operand.Op) { ctx.MINPD(mx, x) }", "func BP2FP(perm []uint8) [][4]uint8 {\n\tn := uint8(len(perm))\n\trects := make([][4]uint8, n+1)\n\trects[perm[0]] = [4]uint8{0, n, 0, n}\n\tbelow := make(map[uint8]uint8)\n\tleft := make(map[uint8]uint8)\n\tprevlabel := perm[0]\n\n\tfor k := uint8(1); k < n; k++ {\n\t\tp := perm[k]\n\t\tif p < prevlabel {\n\t\t\toldrect := rects[prevlabel]\n\t\t\t// middle := (oldrect[2] + oldrect[3]) / 2\n\n\t\t\t// Horizontal slice\n\t\t\trects[p] = oldrect\n\t\t\trects[p][2] = k\n\t\t\trects[prevlabel][3] = k\n\n\t\t\t// Store spatial relations\n\t\t\tbelow[p] = prevlabel\n\t\t\tlp, past := left[prevlabel]\n\t\t\tif past {\n\t\t\t\tleft[p] = lp\n\t\t\t}\n\n\t\t\t_, ok := left[p]\n\t\t\tfor ok && left[p] > p {\n\t\t\t\tl := left[p]\n\n\t\t\t\trects[p][0] = rects[l][0]\n\n\t\t\t\trects[l][3] = rects[p][2]\n\n\t\t\t\tll, okl := left[l]\n\t\t\t\tif okl {\n\t\t\t\t\tleft[p] = ll\n\t\t\t\t} else {\n\t\t\t\t\tdelete(left, p)\n\t\t\t\t}\n\n\t\t\t\tok = okl\n\t\t\t}\n\n\t\t\tprevlabel = p\n\n\t\t} else {\n\t\t\toldrect := rects[prevlabel]\n\t\t\t// middle := (oldrect[0] + oldrect[1]) / 2\n\n\t\t\t// Vertical slice\n\t\t\trects[p] = oldrect\n\t\t\trects[p][0] = k\n\t\t\trects[prevlabel][1] = k\n\n\t\t\t// Store spatial relations\n\t\t\tleft[p] = prevlabel\n\t\t\tbp, past := below[prevlabel]\n\t\t\tif past {\n\t\t\t\tbelow[p] = bp\n\t\t\t}\n\n\t\t\t_, ok := below[p]\n\t\t\tfor ok && below[p] < p {\n\t\t\t\tb := below[p]\n\n\t\t\t\trects[p][2] = rects[b][2]\n\n\t\t\t\trects[b][1] = rects[p][0]\n\n\t\t\t\tbb, okb := below[b]\n\t\t\t\tif okb {\n\t\t\t\t\tbelow[p] = bb\n\t\t\t\t} else {\n\t\t\t\t\tdelete(below, p)\n\t\t\t\t}\n\n\t\t\t\tok = okb\n\t\t\t}\n\n\t\t\tprevlabel = p\n\n\t\t}\n\t}\n\n\treturn rects[1:]\n}", "func (space Space) PointCombine(point1 []float64, weight1 int, point2 []float64, weight2 int) []float64 {\n\treturn space.vspace.PointCombine(point1, weight1, point2, weight2)\n}", "func OfPoints(pts ...[2]float64) Winding { return Order{}.OfPoints(pts...) }", "func Test_309(t *testing.T) {\n\ttestName := \"Test_309 ExtendPolyLine\"\n\trunStart := time.Now()\n\tfmt.Printf(\"%s\\n\", testName)\n\tdefer func() {\n\t\tVerbose.Printf(\"%s took %v\\n\", testName, time.Since(runStart))\n\t}()\n\tvar (\n\t\tgpstest1 GPS2dList = GPS2dList{\n\t\t\t{Lat: 10, Lon: 10},\n\t\t\t{Lat: 15, Lon: 15},\n\t\t}\n\t\tgpstest2 GPS2dList = GPS2dList{\n\t\t\t//\t\t\t{Lat:10,Lon:10,Up:10},\n\t\t\t//\t\t\t{Lat:15,Lon:15,Up:10},\n\t\t\t{Lat: 36.810202, Lon: -77.025878},\n\t\t\t{Lat: 36.803840, Lon: -76.862869},\n\t\t\t{Lat: 36.814619, Lon: -76.902701},\n\t\t}\n\t\tpl PolyLine\n\t\tp2 PolyLine\n\t\tp3 PolyLine\n\t)\n\tVerbose.Printf(\"Centroid of empty list = %v\\n\", pl.Centroid())\n\tpl = append(pl, []Pointe{Pointe{X: 1.0, Y: 1.0}})\n\tVerbose.Printf(\"Centroid of single point [1,1] = %v\\n\", pl.Centroid())\n\tpl[0] = append(pl[0], Pointe{X: 100.0, Y: 100.0})\n\tVerbose.Printf(\"Centroid of line point [1,1],[100,100] = %v\\n\", pl.Centroid())\n\tVerbose.Printf(\"Expect [50.5,50.5]\\n\\n\")\n\tVerbose.Printf(\"%v\\n\", gpstest1)\n\tVerbose.Printf(\"Centroid of gpslist is %v\\n\", pl.Centroid())\n\tgpsPoly1 := gpstest1.PolyLine()\n\tgpsPoly2 := gpstest2.PolyLine()\n\n\tp2.ExtendByPolyLine(gpsPoly1)\n\tVerbose.Printf(\"len p2 now = %d\\n\", len(p2))\n\tVerbose.Printf(\"Centroid of p2 is %v\\n\", p2.Centroid())\n\n\tp3.ExtendByPolyLine(gpsPoly2)\n}", "func (b *BinP1D) XWidth() float64 {\n\treturn b.xrange.Max - b.xrange.Min\n}", "func (op Print) Width() int { return 2 }", "func (g *tgraph) MarshalROOT(w *rbytes.WBuffer) (int, error) {\n\tif w.Err() != nil {\n\t\treturn 0, w.Err()\n\t}\n\n\thdr := w.WriteHeader(g.Class(), g.RVersion())\n\n\tw.WriteObject(&g.Named)\n\tw.WriteObject(&g.attline)\n\tw.WriteObject(&g.attfill)\n\tw.WriteObject(&g.attmarker)\n\n\tw.WriteI32(g.npoints)\n\t{\n\t\tw.WriteI8(1)\n\t\tw.WriteArrayF64(g.x)\n\t\tw.WriteI8(1)\n\t\tw.WriteArrayF64(g.y)\n\t}\n\n\tw.WriteObjectAny(g.funcs)\n\tw.WriteObjectAny(g.histo)\n\t{\n\t\tw.WriteF64(g.min)\n\t\tw.WriteF64(g.max)\n\t}\n\n\treturn w.SetHeader(hdr)\n}", "func findRescuePathLength(caveDepth, targetX, targetY int, cavePlan cavePlanType) (int, cavePlanType) {\n\tgraphMap := make(graphMapType)\n\tstartTorchKey := graphItemKeyType{0, 0, TORCH}\n\tstartTorch := graphItemType{&startTorchKey, 0, -1, nil, false}\n\tpq := make(priorityQueue, 1)\n\tpq[0] = &startTorch\n\tgraphMap[startTorchKey] = &startTorch\n\theap.Init(&pq)\n\n\tfor len(pq) > 0 {\n\t\thead := heap.Pop(&pq).(*graphItemType)\n\t\thead.processed = true\n\t\t// If target reached return distance\n\t\tif head.x == targetX && head.y == targetY && head.tool == TORCH {\n\t\t\treturn head.dist, cavePlan\n\t\t}\n\t\t// Left\n\t\tif head.x > 0 && cavePlan[head.y][head.x-1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x-1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Up\n\t\tif head.y > 0 && cavePlan[head.y-1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y-1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Generate additional cave plan if required\n\t\tif head.x == len(cavePlan[head.y])-1 {\n\t\t\tcavePlan = addColumn(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\tif head.y == len(cavePlan)-1 {\n\t\t\tcavePlan = addRow(caveDepth, targetX, targetY, cavePlan)\n\t\t}\n\t\t// Right\n\t\tif cavePlan[head.y][head.x+1].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x+1, head.y, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Down\n\t\tif cavePlan[head.y+1][head.x].erosion != head.tool {\n\t\t\tcreateGraphItem(head.x, head.y+1, head.tool, head.dist+1, &pq, &graphMap, head)\n\t\t}\n\t\t// Change the tool operation is also one of options\n\t\tnewTool := (head.tool + 1) % 3\n\t\tif newTool == cavePlan[head.y][head.x].erosion {\n\t\t\tnewTool = (newTool + 1) % 3\n\t\t}\n\t\tcreateGraphItem(head.x, head.y, newTool, head.dist+7, &pq, &graphMap, head)\n\t}\n\treturn -1, cavePlan\n}", "func (l *leaf) del(view *View, pred func(x, y float64, e interface{}) bool, _ *subtree, _ *root) {\n\tfor i := range l.ps {\n\t\tpoint := &l.ps[i]\n\t\tif !point.zeroed() && view.contains(point.x, point.y) {\n\t\t\tdel(point, pred)\n\t\t\tif len(point.elems) == 0 {\n\t\t\t\tpoint.zeroOut()\n\t\t\t}\n\t\t}\n\t}\n\trestoreOrder(&l.ps)\n\treturn\n}", "func hammer_modify_node(trans hammer_transaction_t, node hammer_node_t,\n//\t\t void *base, int len)\n//{\n\t\tbase interface{}, len int) {\n\tif bsd.KERNEL_DEFINED() == true {\n//\thammer_crc_t *crcptr;\n\t\tvar crcptr *hammer_crc_t\n//\n\n//\tKKASSERT((char *)base >= (char *)node->ondisk &&\n\t\tkern.KKASSERT(unsafe.Sizeof(base) >= unsafe.Sizeof(node.ondisk) &&\n//\t\t (char *)base + len <=\n\t\t\tint(unsafe.Sizeof(base)) + len <=\n//\t\t (char *)node->ondisk + sizeof(*node->ondisk));\n\t\t\tint(unsafe.Sizeof(node.ondisk) + unsafe.Sizeof(*node.ondisk)))\n//\tKKASSERT((node->flags & HAMMER_NODE_CRCBAD) == 0);\n\t\tkern.KKASSERT((node.flags & HAMMER_NODE_CRCBAD) == 0)\n//\n//\tif (hammer_btree_full_undo) {\n\t\tif hammer_btree_full_undo != 0 {\n//\t\thammer_modify_node_all(trans, node);\n\t\t\thammer_modify_node_all(trans, node)\n//\t} else {\n\t\t} else {\n//\t\thammer_modify_buffer(trans, node->buffer, base, len);\n\t\t\thammer_modify_buffer(trans, node.buffer, base, len)\n//\t\tcrcptr = &node->ondisk->crc;\n\t\t\tcrcptr = &node.ondisk.crc\n//\t\thammer_modify_buffer(trans, node->buffer,\n\t\t\thammer_modify_buffer(trans, node.buffer,\n//\t\t\t\t crcptr, sizeof(hammer_crc_t));\n\t\t\t\tcrcptr, int(unsafe.Sizeof(new(hammer_crc_t))))\n//\t\t--node->buffer->io.modify_refs;\t/* only want one ref */\n\t\t\tnode.buffer.io.modify_refs--\t/* only want one ref */\n//\t}\n\t\t}\n\t}\n//}\n}", "func updateZopfliNode(nodes []zopfliNode, pos uint, start_pos uint, len uint, len_code uint, dist uint, short_code uint, cost float32) {\n\tvar next *zopfliNode = &nodes[pos+len]\n\tnext.length = uint32(len | (len+9-len_code)<<25)\n\tnext.distance = uint32(dist)\n\tnext.dcode_insert_length = uint32(short_code<<27 | (pos - start_pos))\n\tnext.u.cost = cost\n}", "func (k *kernel) alignRecursion(t filter.Trapezoid) {\n\tmid := (t.Bottom + t.Top) / 2\n\n\tk.traceForward(mid, mid-t.Right, mid-t.Left)\n\n\tfor x := 1; x == 1 || k.highEnd.Bbpos > mid+x*k.MaxIGap && k.highEnd.Score < k.lowEnd.Score; x++ {\n\t\tk.traceReverse(k.lowEnd.Bepos, k.lowEnd.Aepos, k.lowEnd.Aepos, mid+k.MaxIGap, k.BlockCost+2*x*k.DiffCost)\n\t}\n\n\tk.highEnd.Aepos, k.highEnd.Bepos = k.lowEnd.Aepos, k.lowEnd.Bepos\n\n\tlowTrap, highTrap := t, t\n\tlowTrap.Top = k.highEnd.Bbpos - k.MaxIGap\n\thighTrap.Bottom = k.highEnd.Bepos + k.MaxIGap\n\n\tif k.highEnd.Bepos-k.highEnd.Bbpos >= k.minLen && k.highEnd.Aepos-k.highEnd.Abpos >= k.minLen {\n\t\tindel := (k.highEnd.Abpos - k.highEnd.Bbpos) - (k.highEnd.Aepos - k.highEnd.Bepos)\n\t\tif indel < 0 {\n\t\t\tif indel == -indel {\n\t\t\t\tpanic(\"dp: weird number overflow\")\n\t\t\t}\n\t\t\tindel = -indel\n\t\t}\n\t\tidentity := ((1 / k.RMatchCost) - float64(k.highEnd.Score-indel)/(k.RMatchCost*float64(k.highEnd.Bepos-k.highEnd.Bbpos)))\n\n\t\tif identity <= k.maxDiff {\n\t\t\tk.highEnd.Error = identity\n\n\t\t\tfor i, trap := range k.trapezoids[k.slot+1:] {\n\t\t\t\tvar trapAProjection, trapBProjection, coverageA, coverageB int\n\n\t\t\t\tif trap.Bottom >= k.highEnd.Bepos {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\n\t\t\t\ttrapBProjection = trap.Top - trap.Bottom + 1\n\t\t\t\ttrapAProjection = trap.Right - trap.Left + 1\n\t\t\t\tif trap.Left < k.highEnd.LowDiagonal {\n\t\t\t\t\tcoverageA = k.highEnd.LowDiagonal\n\t\t\t\t} else {\n\t\t\t\t\tcoverageA = trap.Left\n\t\t\t\t}\n\t\t\t\tif trap.Right > k.highEnd.HighDiagonal {\n\t\t\t\t\tcoverageB = k.highEnd.HighDiagonal\n\t\t\t\t} else {\n\t\t\t\t\tcoverageB = trap.Right\n\t\t\t\t}\n\n\t\t\t\tif coverageA > coverageB {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tcoverageA = coverageB - coverageA + 1\n\t\t\t\tif trap.Top > k.highEnd.Bepos {\n\t\t\t\t\tcoverageB = k.highEnd.Bepos - trap.Bottom + 1\n\t\t\t\t} else {\n\t\t\t\t\tcoverageB = trapBProjection\n\t\t\t\t}\n\n\t\t\t\tif (float64(coverageA)/float64(trapAProjection))*(float64(coverageB)/float64(trapBProjection)) > 0.99 {\n\t\t\t\t\tk.covered[i] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Diagonals to this point are query-target, not target-query.\n\t\t\tk.highEnd.LowDiagonal, k.highEnd.HighDiagonal = -k.highEnd.HighDiagonal, -k.highEnd.LowDiagonal\n\n\t\t\tk.result <- k.highEnd\n\t\t}\n\t}\n\n\tif lowTrap.Top-lowTrap.Bottom > k.minLen && lowTrap.Top < t.Top-k.MaxIGap {\n\t\tk.alignRecursion(lowTrap)\n\t}\n\tif highTrap.Top-highTrap.Bottom > k.minLen {\n\t\tk.alignRecursion(highTrap)\n\t}\n}", "func TestNoTopo(t *testing.T) {\n\tkdlog.InitLogs()\n\n\tkubePod := &kubev1.Pod{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Pod0\",\n\t\t\tAnnotations: map[string]string{\n\t\t\t\t\"ABCD\": \"EFGH\",\n\t\t\t},\n\t\t},\n\t\tSpec: kubev1.PodSpec{\n\t\t\tContainers: []kubev1.Container{\n\t\t\t\t{\n\t\t\t\t\tName: \"Cont0\",\n\t\t\t\t\tResources: kubev1.ResourceRequirements{\n\t\t\t\t\t\tRequests: kubev1.ResourceList{\n\t\t\t\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo0 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node0\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(4, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo1 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node1\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo2 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node2\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(0, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(0, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\tnodeInfo3 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node3\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{},\n\t}\n\tnodeInfo4 := &kubev1.Node{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: \"Node4\",\n\t\t},\n\t\tStatus: kubev1.NodeStatus{\n\t\t\tCapacity: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t\tAllocatable: kubev1.ResourceList{\n\t\t\t\tkubev1.ResourceName(gpuplugintypes.ResourceGPU): *resource.NewQuantity(8, resource.DecimalSI),\n\t\t\t},\n\t\t},\n\t}\n\n\tds := DeviceScheduler\n\tds.RemoveAll()\n\tdev := &gpuschedulerplugin.NvidiaGPUScheduler{}\n\tds.AddDevice(dev)\n\n\tn0, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo0, nil)\n\tn1, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo1, nil)\n\tn2, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo2, nil)\n\tn3, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo3, nil)\n\tn4, _ := kubeinterface.KubeNodeToNodeInfo(nodeInfo4, nil)\n\tds.AddNode(nodeInfo0.ObjectMeta.Name, n0)\n\tds.AddNode(nodeInfo1.ObjectMeta.Name, n1)\n\tds.AddNode(nodeInfo2.ObjectMeta.Name, n2)\n\tds.AddNode(nodeInfo3.ObjectMeta.Name, n3)\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tds.AddNode(nodeInfo4.ObjectMeta.Name, n4)\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tfmt.Printf(\"Node: %+v\\n\", n0)\n\tfmt.Printf(\"Node: %+v\\n\", n1)\n\tmodReq := gpuschedulerplugin.TranslateGPUResources(n0.KubeAlloc[gpuplugintypes.ResourceGPU], types.ResourceList{\n\t\ttypes.DeviceGroupPrefix + \"/gpugrp1/A/gpugrp0/B/gpu/GPU0/cards\": int64(1),\n\t}, n0.Allocatable)\n\tif !reflect.DeepEqual(modReq, n0.Allocatable) {\n\t\tt.Errorf(\"Alloc not same, expect: %v, have: %v\", n0.Allocatable, modReq)\n\t}\n\tn0.Allocatable = modReq\n\t//fmt.Printf(\"Node: %+v\\n\", n0)\n\n\tp0, _ := kubeinterface.KubePodInfoToPodInfo(kubePod, false)\n\tfmt.Printf(\"Pod: %+v\\n\", p0)\n\n\tfits, failures, score := ds.PodFitsResources(p0, n0, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n1, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n2, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfits, failures, score = ds.PodFitsResources(p0, n3, false)\n\tfmt.Printf(\"Fit: %v Failures: %v Score: %v\\n\", fits, failures, score)\n\n\tfmt.Printf(\"Scores: %+v\\n\", ds.score)\n\n\tpri0 := ds.PodPriority(p0, n0)\n\tfmt.Printf(\"PodPriority0: %v\\n\", pri0)\n\n\tpri1 := ds.PodPriority(p0, n1)\n\tfmt.Printf(\"PodPriority1: %v\\n\", pri1)\n\n\tds.RemoveNode(\"Node1\")\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\tds.RemoveNode(\"Node4\")\n\tfmt.Printf(\"NodeLocationMap:\\n%+v\\n\", gpuschedulerplugin.NodeLocationMap)\n\tfmt.Printf(\"NodeCacheMap:\\n%+v\\n\", gpuschedulerplugin.NodeCacheMap)\n\n\tkdlog.FlushLogs()\n}", "func shouldUpdateOVNKonPrepull(ovn bootstrap.OVNBootstrapResult, releaseVersion string) (updateNode, renderPrepull bool) {\n\t// Fresh cluster - full steam ahead! No need to wait for pre-puller.\n\tif ovn.NodeUpdateStatus == nil {\n\t\tklog.V(3).Infof(\"Fresh cluster, no need for prepuller\")\n\t\treturn true, false\n\t}\n\n\t// if node is already upgraded, then no need to pre-pull\n\t// Return true so that we reconcile any changes that somehow could have happened.\n\texistingNodeVersion := ovn.NodeUpdateStatus.Version\n\tif existingNodeVersion == releaseVersion {\n\t\tklog.V(3).Infof(\"OVN-Kubernetes node is already in the expected release.\")\n\t\treturn true, false\n\t}\n\n\t// at this point, we've determined we need an upgrade\n\tif ovn.PrePullerUpdateStatus == nil {\n\t\tklog.Infof(\"Rolling out the no-op prepuller daemonset...\")\n\t\treturn false, true\n\t}\n\n\t// If pre-puller just pulled a new upgrade image and then we\n\t// downgrade immediately, we might wanna make prepuller pull the downgrade image.\n\texistingPrePullerVersion := ovn.PrePullerUpdateStatus.Version\n\tif existingPrePullerVersion != releaseVersion {\n\t\tklog.Infof(\"Rendering prepuller daemonset to update its image...\")\n\t\treturn false, true\n\t}\n\n\tif ovn.PrePullerUpdateStatus.Progressing {\n\t\tklog.Infof(\"Waiting for ovnkube-upgrades-prepuller daemonset to finish pulling the image before updating node\")\n\t\treturn false, true\n\t}\n\n\tklog.Infof(\"OVN-Kube upgrades-prepuller daemonset rollout complete, now starting node rollouts\")\n\treturn true, false\n}", "func (e *encoder) writeSOF0(size image.Point, nComponent int) {\n\tmarkerlen := 8 + 3*nComponent\n\te.writeMarkerHeader(sof0Marker, markerlen)\n\te.buf[0] = 8 // 8-bit color.\n\te.buf[1] = uint8(size.Y >> 8)\n\te.buf[2] = uint8(size.Y & 0xff)\n\te.buf[3] = uint8(size.X >> 8)\n\te.buf[4] = uint8(size.X & 0xff)\n\te.buf[5] = uint8(nComponent)\n\tif nComponent == 1 {\n\t\te.buf[6] = 1\n\t\t// No subsampling for grayscale image.\n\t\te.buf[7] = 0x11\n\t\te.buf[8] = 0x00\n\t} else {\n\t\tfor i := 0; i < nComponent; i++ {\n\t\t\te.buf[3*i+6] = uint8(i + 1)\n\t\t\t// We use 4:2:0 chroma subsampling.\n\t\t\te.buf[3*i+7] = \"\\x22\\x11\\x11\"[i]\n\t\t\te.buf[3*i+8] = \"\\x00\\x01\\x01\"[i]\n\t\t}\n\t}\n\te.write(e.buf[:3*(nComponent-1)+9])\n}", "func (m *metricAerospikeNodeMemoryFree) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}", "func (m *metricAerospikeNamespaceGeojsonRegionQueryPoints) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func treeGene( geneArray[] string, arrayPos int, shapeType string) int{\n\n//Function check to see if the there is any shapes in the in the listArray\n//if not it changes the structures as it moves to the end\n\tif listArray[0] != shapeType { \n\t\t\tlistArray[1]= \"<inst>\"\n\t\t\tlistArray[0] = shapeType\n\t\tarrayPos++\n\t\ttreeGene(geneArray[0:],arrayPos,shapeType)\t// Called the function so it can be processed with the valid format \t\n\t}else{ if listArray[1] == \"\" || listArray[1] == \"<inst>\"{ // after transforming it is place in a format that can be parsed \n\t\t\tif geneArray[arrayPos] == shapeType{ \t// Ensure we are not Validating a Shape\n\t\t\t\tarrayPos++\n\t\t\t}\n\t\t\t// Retrieve the Coordinated from the array\n\t\t\tvar curCoord string=geneArray[arrayPos] \n\t\t\tarrayPos++\n\t\t\t\n\t\t\t// Using Slices we get each Values \n\t\t\tx:=curCoord[0:1] \n\t\t\ty:=curCoord[1:2]\n\t\t\tfmt.Printf(\"\\n |\\n\")\n\t\t\t\n\t\t\t// The Only Difference with Circle is that it Has a Coordinated\n\t\t\tfmt.Printf(shapeType+\"\\n / \\\\\\n\")\n\t\t\tif shapeType == \"CIR\"{\n\t\t\t\tfmt.Printf(\"<coord>\\n\")\n\t\t\t}\t\t\t\n\t\t\tfmt.Printf(\"<x><y>\\n\"+x+\" \"+y)\n\t\t\t\n\t\t}\n\t\t }\n\n\treturn arrayPos\n}", "func (*Root) Size() int64 { return 0 }", "func Make_Layer_Rect_Xmap(tile m.TileID, finds []l.Polygon) Tile_Xmap {\n\tnewlist := []l.Polygon{}\n\n\t// getting rectangle\n\tfirst := l.Polygon{Polygon: Make_Tile_Poly(tile)}\n\t//first.Polygon.Add(val)\n\tval := first.Polygon[0]\n\tval = pc.Contour{val[0], val[1], val[2], val[3], val[2], val[1], val[0]}\n\tfirst.Polygon.Add(val)\n\t// iterating through each found area\n\tfor _, i := range finds {\n\t\ti.Polygon.Add(val)\n\t\t//if IsReachable(first, i, \"INTERSECTION\") == true {\n\t\tresult := first.Polygon.Construct(pc.INTERSECTION, i.Polygon)\n\t\t//}\n\n\t\t// adding the the result to newlist if possible\n\t\tif len(result) != 0 {\n\t\t\tamap := map[string]string{}\n\t\t\tamap[i.Layer] = i.Area\n\t\t\tamap[\"tile\"] = m.Tilestr(tile)\n\n\t\t\t//fmt.Print(amap, \"\\n\")\n\t\t\ti.Polygon = result\n\t\t\ti.Layers = amap\n\t\t\tnewlist = append(newlist, i)\n\t\t} else {\n\t\t\t//\tfmt.Print(\"here\\n\", first.Polystring, \"\\n\", i.Polystring, \"\\n\")\n\t\t\t//fmt.Print(\"here\\n\")\n\t\t}\n\n\t}\n\t// linting the output polygons\n\tstringlist := Lint_Layer_Polygons(newlist)\n\n\t// iterating through each value in newlist\n\txmaptotal := map[string][]Yrow{}\n\tfor _, i := range stringlist {\n\t\txmap := Make_Xmap_Total(get_coords_json(i[1]), i[0], tile)\n\t\tfor k, v := range xmap {\n\t\t\txmaptotal[k] = append(xmaptotal[k], v...)\n\t\t}\n\t}\n\tvalbool := false\n\n\tif valbool == true {\n\t\tstringlist2 := []string{\"LONG,LAT,AREA\"}\n\t\tfor k, v := range xmaptotal {\n\t\t\tx := Get_Middle(k)[0]\n\t\t\tfor _, vv := range v {\n\t\t\t\tarea := strings.Replace(vv.Area, \",\", \"\", -1)\n\t\t\t\tstringlist2 = append(stringlist2, fmt.Sprintf(\"%f,%f,%s\", x, vv.Range[0], area))\n\t\t\t\tstringlist2 = append(stringlist2, fmt.Sprintf(\"%f,%f,%s\", x, vv.Range[1], area))\n\t\t\t}\n\n\t\t}\n\t\t//fmt.Print(xmap, \"\\n\")\n\t\tbds := m.Bounds(tile)\n\t\tcount := 0\n\t\tlatconst := bds.N\n\n\t\tfor count < 100000 {\n\t\t\tcount += 1\n\t\t\tpt := RandomPt(bds)\n\t\t\tareat := strings.Replace(Pip_Simple(pt, xmaptotal, latconst), \",\", \"\", -1)\n\t\t\tfmt.Print(areat)\n\t\t\tif areat != \"\" {\n\t\t\t\tfmt.Print(\"Here\\n\")\n\t\t\t\tstringlist2 = append(stringlist2, fmt.Sprintf(\"%f,%f,%s\", pt[0], pt[1], areat))\n\t\t\t}\n\t\t}\n\n\t\ta := strings.Join(stringlist2, \"\\n\")\n\t\tff, _ := os.Create(\"d.csv\")\n\t\tff.WriteString(a)\n\t\tfmt.Print(a, \"\\n\")\n\t}\n\t//ff, _ := os.Create(\"d.csv\")\n\t//ff.WriteString(a)\n\treturn Tile_Xmap{Tile: tile, Xmap: xmaptotal}\n}", "func nodeLen(data interface{}) int {\n\tif data == nil {\n\t\treturn 0\n\t}\n\tswitch d := data.(type) {\n\tcase []interface{}:\n\t\treturn len(d)\n\tcase map[string]interface{}:\n\t\treturn len(d)\n\tcase string, int, float64, bool:\n\t\treturn 1\n\t}\n\treturn 0\n}", "func UNPCKHPD(mx, x operand.Op) { ctx.UNPCKHPD(mx, x) }", "func subtreeSize(x uint, n uint) uint {\n\tw := nodeWidth(n)\n\tlr := uint((1 << level(x)) - 1)\n\trr := uint(lr)\n\tif x+rr >= w {\n\t\trr = w - x - 1\n\t}\n\n\treturn (lr+rr)/2 + 1\n}", "func treeSQR( sqrArray[] string, arrayPos int) int{\n\n//Function check to see if the there is any shapes in the in the listArray\n//if not it changes the structures as it moves to the end\nif listArray[0] != \"SQR\" { \n\t\t\tlistArray[1]= \"<inst>\"\n\t\t\tlistArray[0] = \"SQR\"\n\t\tarrayPos++\n\t\t\n\t\t// Called the function so it can be processed with the valid format \n\t\ttreeSQR(sqrArray[0:],arrayPos)\t\n\t}else{ if listArray[1] == \"\" || listArray[1] == \"<inst>\"{ // after transforming it is place in a format that can be parsed \n\t\n\t\t\tif sqrArray[arrayPos] == \"SQR\"{ // Ensure we are not Validating a Shape\n\t\t\t\tarrayPos++\n\t\t\t}\n\t\t\t\n\t\t\t// Retrieve the Coordinated from the array\n\t\t\t// Proceeding to the next value\n\t\t\tvar curCoord string=sqrArray[arrayPos]\n\t\t\tarrayPos++\n\t\t\tvar secCoord string=sqrArray[arrayPos]\n\t\t\t//arrayPos++\t\t\n\t\t\t\n\t\t\t// Using Slices we get each Values \n\t\t\tvar test string \n\t\t\tx:=curCoord[0:1]\n\t\t\ty:=curCoord[1:2]\n\t\t\tyy:=secCoord[0:1]\n\t\t\txx:=secCoord[1:2]\n\t\t\tarrayPos=arrayPos-2\n\t\t\t\n\t\t\t//The Printing format for the lower part of the tree\n\t\t\tfmt.Printf(\"\\n |\\n\")\n\t\t\tfmt.Printf(\"SQR\\n/ \\\\\\n\")\n\t\t\tfmt.Printf(\"<coord>,<coord>\\n\")\n\t\t\tfmt.Printf(\" / \\\\ / \\\\\\n\")\n\t\t\tfmt.Printf(\"<x><y>,<x><y>\\n\"+x+\" \"+y+\" \"+yy+\" \"+xx)\n\t\t\n\t\t\tlistArray[0] = \"<inst>\"\n\t\t\tlistArray[1] = \"<inst_list>\"\n\t\t\t\t\t\t\n\t\t\ttempCount=tempCount-1\n\t\t\t\tif(tempCount >= 0){\t\t\t\t\n\t\t\t\t\tlistArray[tempCount]=\"\"\n\t\t\t\t\t\n\t\t\t\t}\n\t\t\treturn arrayPos\t\n\t\t}\n\t\treturn arrayPos\n\t\t }\n\t\n\treturn arrayPos\n}", "func (self *TileSprite) TileScaleOffset() *Point{\n return &Point{self.Object.Get(\"tileScaleOffset\")}\n}", "func (self *Rectangle) InflatePoint(a *Rectangle, point *Point) *Rectangle{\n return &Rectangle{self.Object.Call(\"inflatePoint\", a, point)}\n}", "func GxPhysicalWidth(value float64) *SimpleElement { return newSEFloat(\"gx:physicalWidth\", value) }", "func (b *BoundingBox2D) width() float64 {\n\n\treturn b.upperCorner.X - b.lowerCorner.X\n}", "func (a *AxisPosition) update(gtx layout.Context, axis layout.Axis, elements, maxPx int, dimensioner Dimensioner) {\n\ta.normalize(gtx, axis, elements, dimensioner)\n\tpixelsUsed := a.computePosition(gtx, axis, elements, maxPx, dimensioner)\n\tif pixelsUsed < maxPx {\n\t\ta.Offset -= (maxPx - pixelsUsed)\n\t\ta.normalize(gtx, axis, elements, dimensioner)\n\t\t_ = a.computePosition(gtx, axis, elements, maxPx, dimensioner)\n\t}\n}", "func layoutTree(root ContainerLayoutItem, size Size, cancel chan struct{}, done chan []LayoutResult, stopwatch *stopwatch) {\n\tconst minSizeCacheSubject = \"layoutTree - populating min size cache\"\n\n\tif stopwatch != nil {\n\t\tstopwatch.Start(minSizeCacheSubject)\n\t}\n\n\t// Populate some caches now, so we later need only read access to them from multiple goroutines.\n\tctx := root.Context()\n\n\tpopulateContextForItem := func(item LayoutItem) {\n\t\tctx.layoutItem2MinSizeEffective[item] = minSizeEffective(item)\n\t}\n\n\tvar populateContextForContainer func(container ContainerLayoutItem)\n\tpopulateContextForContainer = func(container ContainerLayoutItem) {\n\t\tfor _, child := range container.AsContainerLayoutItemBase().children {\n\t\t\tif cli, ok := child.(ContainerLayoutItem); ok {\n\t\t\t\tpopulateContextForContainer(cli)\n\t\t\t} else {\n\t\t\t\tpopulateContextForItem(child)\n\t\t\t}\n\t\t}\n\n\t\tpopulateContextForItem(container)\n\t}\n\n\tpopulateContextForContainer(root)\n\n\tif stopwatch != nil {\n\t\tstopwatch.Stop(minSizeCacheSubject)\n\t}\n\n\tconst layoutSubject = \"layoutTree - computing layout\"\n\n\tif stopwatch != nil {\n\t\tstopwatch.Start(layoutSubject)\n\t}\n\n\tresults := make(chan LayoutResult)\n\tfinished := make(chan struct{})\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tclose(results)\n\t\t\tclose(finished)\n\t\t}()\n\n\t\tvar wg sync.WaitGroup\n\n\t\tvar layoutSubtree func(container ContainerLayoutItem, size Size)\n\t\tlayoutSubtree = func(container ContainerLayoutItem, size Size) {\n\t\t\twg.Add(1)\n\n\t\t\tgo func() {\n\t\t\t\tdefer wg.Done()\n\n\t\t\t\tclib := container.AsContainerLayoutItemBase()\n\n\t\t\t\tclib.geometry.ClientSize = size\n\n\t\t\t\titems := container.PerformLayout()\n\n\t\t\t\tselect {\n\t\t\t\tcase <-cancel:\n\t\t\t\t\treturn\n\n\t\t\t\tcase results <- LayoutResult{container, items}:\n\t\t\t\t}\n\n\t\t\t\tfor _, item := range items {\n\t\t\t\t\tselect {\n\t\t\t\t\tcase <-cancel:\n\t\t\t\t\t\treturn\n\n\t\t\t\t\tdefault:\n\t\t\t\t\t}\n\n\t\t\t\t\titem.Item.Geometry().Size = item.Bounds.Size()\n\n\t\t\t\t\tif childContainer, ok := item.Item.(ContainerLayoutItem); ok {\n\t\t\t\t\t\tlayoutSubtree(childContainer, item.Bounds.Size())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}()\n\t\t}\n\n\t\tlayoutSubtree(root, size)\n\n\t\twg.Wait()\n\n\t\tselect {\n\t\tcase <-cancel:\n\t\t\treturn\n\n\t\tcase finished <- struct{}{}:\n\t\t}\n\t}()\n\n\tvar layoutResults []LayoutResult\n\n\tfor {\n\t\tselect {\n\t\tcase result := <-results:\n\t\t\tlayoutResults = append(layoutResults, result)\n\n\t\tcase <-finished:\n\t\t\tif stopwatch != nil {\n\t\t\t\tstopwatch.Stop(layoutSubject)\n\t\t\t}\n\n\t\t\tdone <- layoutResults\n\t\t\treturn\n\n\t\tcase <-cancel:\n\t\t\tif stopwatch != nil {\n\t\t\t\tstopwatch.Cancel(layoutSubject)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t}\n}", "func (np *vpoint) zeroOut() {\n\tnp.elems = nil\n}", "func (m *metricAerospikeNodeConnectionOpen) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (n *node) updateMassCenter() {\n\tvar points []*Point\n\tfor i := range n.leafs {\n\t\tpoints = append(points, n.leafs[i].Center())\n\t}\n\n\tn.massCenter = massCenter(points)\n}", "func (o AiFeatureStoreOnlineServingConfigOutput) FixedNodeCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v AiFeatureStoreOnlineServingConfig) *int { return v.FixedNodeCount }).(pulumi.IntPtrOutput)\n}", "func (fh *serviceTopologyFilterHandler) reassembleEndpointSlice(endpointSlice *discovery.EndpointSlice) *discovery.EndpointSlice {\n\tvar serviceTopologyType string\n\t// get the service Topology type\n\tif svcName, ok := endpointSlice.Labels[discovery.LabelServiceName]; ok {\n\t\tsvc, err := fh.serviceLister.Services(endpointSlice.Namespace).Get(svcName)\n\t\tif err != nil {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get service %s/%s, err: %v\", endpointSlice.Namespace, svcName, err)\n\t\t\treturn endpointSlice\n\t\t}\n\n\t\tif serviceTopologyType, ok = svc.Annotations[AnnotationServiceTopologyKey]; !ok {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, service %s/%s has no annotation %s\", endpointSlice.Namespace, svcName, AnnotationServiceTopologyKey)\n\t\t\treturn endpointSlice\n\t\t}\n\t}\n\n\tvar newEps []discovery.Endpoint\n\t// if type of service Topology is 'kubernetes.io/hostname'\n\t// filter the endpoint just on the local host\n\tif serviceTopologyType == AnnotationServiceTopologyValueNode {\n\t\tfor i := range endpointSlice.Endpoints {\n\t\t\tif endpointSlice.Endpoints[i].Topology[v1.LabelHostname] == fh.nodeName {\n\t\t\t\tnewEps = append(newEps, endpointSlice.Endpoints[i])\n\t\t\t}\n\t\t}\n\t\tendpointSlice.Endpoints = newEps\n\t} else if serviceTopologyType == AnnotationServiceTopologyValueNodePool || serviceTopologyType == AnnotationServiceTopologyValueZone {\n\t\t// if type of service Topology is openyurt.io/nodepool\n\t\t// filter the endpoint just on the node which is in the same nodepool with current node\n\t\tcurrentNode, err := fh.nodeGetter()\n\t\tif err != nil {\n\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get current node %s, err: %v\", fh.nodeName, err)\n\t\t\treturn endpointSlice\n\t\t}\n\t\tif nodePoolName, ok := currentNode.Labels[nodepoolv1alpha1.LabelCurrentNodePool]; ok {\n\t\t\tnodePool, err := fh.nodePoolLister.Get(nodePoolName)\n\t\t\tif err != nil {\n\t\t\t\tklog.Infof(\"skip reassemble endpointSlice, failed to get nodepool %s, err: %v\", nodePoolName, err)\n\t\t\t\treturn endpointSlice\n\t\t\t}\n\t\t\tfor i := range endpointSlice.Endpoints {\n\t\t\t\tif inSameNodePool(endpointSlice.Endpoints[i].Topology[v1.LabelHostname], nodePool.Status.Nodes) {\n\t\t\t\t\tnewEps = append(newEps, endpointSlice.Endpoints[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\tendpointSlice.Endpoints = newEps\n\t\t}\n\t}\n\treturn endpointSlice\n}", "func Point(children ...Element) *CompoundElement { return newCE(\"Point\", children) }", "func nodeIsValidForTopologyAwareHints(node *corev1.Node) bool {\n\treturn !node.Status.Allocatable.Cpu().IsZero() && node.Labels[corev1.LabelTopologyZone] != \"\"\n}", "func (m *metricFlinkJvmMemoryMappedUsed) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func offset2Key(key []byte, offset uint) uint {\n\t// The node has 1024 children, i.e. 10 bits. Extract it\n\t// from the key to figure out which child to recurse into.\n\t// The number is necessarily spread across 2 bytes because\n\t// the pitch is 10 and therefore a multiple of 2. Hence, no\n\t// 3 byte scenario is possible.\n\tnFirstByte := offset / 8\n\tnBitsInSecondByte := (offset + width) % 8\n\tfirstBitShift := (8 - (offset % 8))\n\tlastBitShift := (8 - nBitsInSecondByte) % 8\n\tleftMask := (key[nFirstByte] >> firstBitShift) << firstBitShift\n\tret := (uint(key[nFirstByte]^leftMask) << ((nBitsInSecondByte-1)%8 + 1))\n\tif int(nFirstByte)+1 < len(key) {\n\t\tret |= uint(key[nFirstByte+1] >> lastBitShift)\n\t}\n\treturn ret\n}", "func (o *V0037JobProperties) GetMinimumCpusPerNodeOk() (*int32, bool) {\n\tif o == nil || o.MinimumCpusPerNode == nil {\n\t\treturn nil, false\n\t}\n\treturn o.MinimumCpusPerNode, true\n}", "func TestSmlWriterProcessing(t *testing.T) {\n\troot := createSmlStructure()\n\tbufA := bytes.NewBufferString(\"\")\n\tbufB := bytes.NewBufferString(\"\")\n\tsppA := NewSmlWriterProcessor(bufA, true)\n\tsppB := NewSmlWriterProcessor(bufB, false)\n\n\troot.ProcessWith(sppA)\n\troot.ProcessWith(sppB)\n\n\tt.Logf(\"Print A: %v\", bufA)\n\tt.Logf(\"Print B: %v\", bufB)\n}", "func computeMinimumCopyLength(start_cost float32, nodes []zopfliNode, num_bytes uint, pos uint) uint {\n\tvar min_cost float32 = start_cost\n\tvar len uint = 2\n\tvar next_len_bucket uint = 4\n\t/* Compute the minimum possible cost of reaching any future position. */\n\n\tvar next_len_offset uint = 10\n\tfor pos+len <= num_bytes && nodes[pos+len].u.cost <= min_cost {\n\t\t/* We already reached (pos + len) with no more cost than the minimum\n\t\t possible cost of reaching anything from this pos, so there is no point in\n\t\t looking for lengths <= len. */\n\t\tlen++\n\n\t\tif len == next_len_offset {\n\t\t\t/* We reached the next copy length code bucket, so we add one more\n\t\t\t extra bit to the minimum cost. */\n\t\t\tmin_cost += 1.0\n\n\t\t\tnext_len_offset += next_len_bucket\n\t\t\tnext_len_bucket *= 2\n\t\t}\n\t}\n\n\treturn uint(len)\n}", "func PointSize(size float32) {\n C.glowPointSize(gpPointSize, (C.GLfloat)(size))\n}", "func (orderbook *Orderbook) backfillPoints(topbook []*Point, pointDistance uint64, leftMultiple uint64, rightMultiple uint64) []*Point {\n\tfor currentMultiple := leftMultiple; currentMultiple < rightMultiple; currentMultiple++ {\n\t\tpoint := CreatePoint(orderbook, (currentMultiple+1)*pointDistance)\n\t\ttopbook = append(topbook, &point)\n\t}\n\treturn topbook\n}", "func (m *metricAerospikeNodeQueryTracked) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func kwReduction(gr g.Graph, poolSize int, debug int) g.Graph {\n\tif debug % 2 == 1 {\n\t\tfmt.Printf(\"Starting KW Reduction \\n\")\n\t}\n\tdegree := gr.MaxDegree\n\tstartIndexes := make([]int, 0)\n\tsize := len(gr.Nodes)\n\tc := make(chan g.Graph)\n\t// If we can't split the graph into bins,\n\tif size < 2 * (degree + 1) {\n\t\tgr.Description = \"Color Reduced with KW\"\n\t\tgo runNaiveGoRoutine(gr, poolSize, debug, c)\n\t\treturn <- c\n\t}\n\tfor x := 0; x < size; x++ {\n\t\tif x % (2 * (degree + 1)) == 0 {\n\t\t\tstartIndexes = append(startIndexes, x)\n\t\t}\n\t}\n\n\tnumColors := g.CountColors(&gr)\n\tcolorBins := make([][]*g.Node, numColors)\n\tcolorToIndex := make(map[int]int)\n\tlatestIndex := 0\n\tfor _, node := range gr.Nodes {\n\t\tif _, ok := colorToIndex[node.Color]; ! ok {\n\t\t\tcolorToIndex[node.Color] = latestIndex\n\t\t\tlatestIndex++\n\t\t}\n\t\tcolorBins[colorToIndex[node.Color]] = append(colorBins[colorToIndex[node.Color]], node)\n\t}\n\n\tfor len(colorBins) > degree + 1 {\n\t\t//fmt.Printf(\"Number of bins: %d\\n\", len(colorBins))\n\t\td := make(chan [][]*g.Node)\n\t\tbinIndexes := make([]int, 0)\n\t\tcolors := len(colorBins)\n\n\t\tfor x := 0; x < colors; x++ {\n\t\t\tif x%(2*(degree+1)) == 0 {\n\t\t\t\tbinIndexes = append(binIndexes, x)\n\t\t\t}\n\t\t}\n\t\ttempBins := make([][]*g.Node, 0)\n\n\t\tfor i := 0; i < len(binIndexes); i++ {\n\t\t\tcurrStart := binIndexes[i]\n\t\t\tvar nextStart int\n\t\t\tif i+1 != len(binIndexes) {\n\t\t\t\tnextStart = binIndexes[i+1]\n\t\t\t} else {\n\t\t\t\tnextStart = len(colorBins)\n\t\t\t}\n\t\t\tgo combineColorsWithoutNaive(colorBins[currStart:nextStart], gr, d)\n\t\t}\n\t\tfor i := 0; i < len(binIndexes); i++ {\n\t\t\tbins := <-d\n\t\t\ttempBins = append(tempBins, bins...)\n\t\t}\n\n\t\tclose(d)\n\n\t\tcolorBins = tempBins\n\t\ttempBins = make([][]*g.Node, 0)\n\t}\n\tgraph := convertBinsToGraph(colorBins, &gr)\n\treturn *graph\n}", "func splitMetrics(size int, src pmetric.Metrics) pmetric.Metrics {\n\tdataPoints := src.DataPointCount()\n\tif dataPoints <= size {\n\t\treturn src\n\t}\n\ttotalCopiedDataPoints := 0\n\tdest := pmetric.NewMetrics()\n\n\tsrc.ResourceMetrics().RemoveIf(func(srcRs pmetric.ResourceMetrics) bool {\n\t\t// If we are done skip everything else.\n\t\tif totalCopiedDataPoints == size {\n\t\t\treturn false\n\t\t}\n\n\t\t// If it fully fits\n\t\tsrcRsDataPointCount := resourceMetricsDPC(srcRs)\n\t\tif (totalCopiedDataPoints + srcRsDataPointCount) <= size {\n\t\t\ttotalCopiedDataPoints += srcRsDataPointCount\n\t\t\tsrcRs.MoveTo(dest.ResourceMetrics().AppendEmpty())\n\t\t\treturn true\n\t\t}\n\n\t\tdestRs := dest.ResourceMetrics().AppendEmpty()\n\t\tsrcRs.Resource().CopyTo(destRs.Resource())\n\t\tsrcRs.ScopeMetrics().RemoveIf(func(srcIlm pmetric.ScopeMetrics) bool {\n\t\t\t// If we are done skip everything else.\n\t\t\tif totalCopiedDataPoints == size {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// If possible to move all metrics do that.\n\t\t\tsrcIlmDataPointCount := scopeMetricsDPC(srcIlm)\n\t\t\tif srcIlmDataPointCount+totalCopiedDataPoints <= size {\n\t\t\t\ttotalCopiedDataPoints += srcIlmDataPointCount\n\t\t\t\tsrcIlm.MoveTo(destRs.ScopeMetrics().AppendEmpty())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tdestIlm := destRs.ScopeMetrics().AppendEmpty()\n\t\t\tsrcIlm.Scope().CopyTo(destIlm.Scope())\n\t\t\tsrcIlm.Metrics().RemoveIf(func(srcMetric pmetric.Metric) bool {\n\t\t\t\t// If we are done skip everything else.\n\t\t\t\tif totalCopiedDataPoints == size {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\t// If possible to move all points do that.\n\t\t\t\tsrcMetricPointCount := metricDPC(srcMetric)\n\t\t\t\tif srcMetricPointCount+totalCopiedDataPoints <= size {\n\t\t\t\t\ttotalCopiedDataPoints += srcMetricPointCount\n\t\t\t\t\tsrcMetric.MoveTo(destIlm.Metrics().AppendEmpty())\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\t// If the metric has more data points than free slots we should split it.\n\t\t\t\tcopiedDataPoints, remove := splitMetric(srcMetric, destIlm.Metrics().AppendEmpty(), size-totalCopiedDataPoints)\n\t\t\t\ttotalCopiedDataPoints += copiedDataPoints\n\t\t\t\treturn remove\n\t\t\t})\n\t\t\treturn false\n\t\t})\n\t\treturn srcRs.ScopeMetrics().Len() == 0\n\t})\n\n\treturn dest\n}", "func (obj *Device) DrawPrimitiveUP(\n\ttyp PRIMITIVETYPE,\n\tprimitiveCount uint,\n\tvertexStreamZeroData uintptr,\n\tvertexStreamZeroStride uint,\n) Error {\n\tret, _, _ := syscall.Syscall6(\n\t\tobj.vtbl.DrawPrimitiveUP,\n\t\t5,\n\t\tuintptr(unsafe.Pointer(obj)),\n\t\tuintptr(typ),\n\t\tuintptr(primitiveCount),\n\t\tvertexStreamZeroData,\n\t\tuintptr(vertexStreamZeroStride),\n\t\t0,\n\t)\n\treturn toErr(ret)\n}", "func processNode(systemLicense []string, currentPosInList int, currentTotal int) (int, int) {\n\tvar numChildren int\n\tvar numMetaData int\n\n\tnumChildren, _ = strconv.Atoi(systemLicense[currentPosInList])\n\tnumMetaData, _ = strconv.Atoi(systemLicense[currentPosInList+1])\n\tcurrentPosInList += 2\n\n\tfor numChildren > 0 {\n\t\tcurrentPosInList, currentTotal = processNode (systemLicense, currentPosInList, currentTotal)\n\t\tnumChildren--\n\t}\n\n\tfor numMetaData > 0 {\n\t\ttempCurrentTotal, _ := strconv.Atoi(systemLicense[currentPosInList])\n\t\tcurrentTotal += tempCurrentTotal\n\t\tcurrentPosInList++\n\t\tnumMetaData--\n\t}\n\n\treturn currentPosInList, currentTotal\n}", "func newRoot(view *View, leafAllocation int64) *root {\n\tif leafAllocation < 10 {\n\t\tleafAllocation = 10\n\t}\n\tleafNum := 3 - ((leafAllocation - 1) % 3) + leafAllocation\n\tnodeNum := (leafNum - 1) / 3\n\tr := new(root)\n\tr.leaves = make([]leaf, leafNum, leafNum)\n\tfor i := 0; i < len(r.leaves)-2; i++ {\n\t\tr.leaves[i].nextFree = &r.leaves[i+1]\n\t}\n\tr.nodes = make([]node, nodeNum, nodeNum)\n\tfor i := 0; i < len(r.nodes)-2; i++ {\n\t\tr.nodes[i].nextFree = &r.nodes[i+1]\n\t}\n\tr.freeNode = &r.nodes[0]\n\tr.freeLeaf = &r.leaves[0]\n\trootNode := r.newNode(view)\n\tr.rootNode = rootNode\n\treturn r\n}", "func (p *transformDataNodes) CleanUp() {}", "func FourPointTransform(img gocv.Mat, pts []image.Point, dst *gocv.Mat) {\n\trect := OrderPoints(pts)\n\ttl := rect[0]\n\ttr := rect[1]\n\tbr := rect[2]\n\tbl := rect[3]\n\n\twidthA := math.Sqrt(math.Pow(float64(br.X)-float64(bl.X), 2) +\n\t\tmath.Pow(float64(br.Y)-float64(bl.Y), 2))\n\twidthB := math.Sqrt(math.Pow(float64(tr.X)-float64(tl.X), 2) +\n\t\tmath.Pow(float64(tr.Y)-float64(tl.Y), 2))\n\tmaxWidth := math.Max(widthA, widthB)\n\n\theightA := math.Sqrt(math.Pow(float64(tr.X)-float64(br.X), 2) +\n\t\tmath.Pow(float64(tr.Y)-float64(br.Y), 2))\n\theightB := math.Sqrt(math.Pow(float64(tl.X)-float64(bl.X), 2) +\n\t\tmath.Pow(float64(tl.Y)-float64(bl.Y), 2))\n\tmaxHeight := math.Max(heightA, heightB)\n\n\tdt := []image.Point{\n\t\timage.Pt(0, 0),\n\t\timage.Pt(int(maxWidth)-1, 0),\n\t\timage.Pt(int(maxWidth)-1, int(maxHeight)-1),\n\t\timage.Pt(0, int(maxHeight)-1)}\n\n\tm := gocv.GetPerspectiveTransform(rect, dt)\n\tgocv.WarpPerspective(img, dst, m, image.Pt(int(maxWidth), int(maxHeight)))\n\n}", "func (l *leaf) insert(x, y float64, elems []interface{}, inPtr *subtree, r *root) {\n\tfor i := range l.ps {\n\t\tif l.ps[i].zeroed() {\n\t\t\tl.ps[i].x = x\n\t\t\tl.ps[i].y = y\n\t\t\tl.ps[i].elems = elems\n\t\t\treturn\n\t\t}\n\t\tif l.ps[i].sameLoc(x, y) {\n\t\t\tl.ps[i].elems = append(l.ps[i].elems, elems...)\n\t\t\treturn\n\t\t}\n\t}\n\t// This leaf is full we need to create an intermediary node to divide it up\n\tnewIntNode(x, y, elems, inPtr, l, r)\n}", "func nodesAndOffsetToRange(numNodes uint64, offset int64, res []Resource) ResourceListPair {\n\tnumNodesMin := getOffsetNodeCount(numNodes, -offset, math.Floor)\n\tnumNodesMax := getOffsetNodeCount(numNodes, offset, math.Ceil)\n\treturn ResourceListPair{\n\t\tlower: calculateResources(numNodesMin, res),\n\t\tupper: calculateResources(numNodesMax, res),\n\t}\n}", "func (t *Dense) oshape() Shape {\n\tif t.old != nil {\n\t\treturn t.old.Shape()\n\t}\n\treturn t.Shape()\n}", "func (*ExprFPTrunc) MetadataNode() {}", "func (p *G2Jac) pippenger(curve *Curve, points []G2Jac, scalars []fr.Element, s, b uint64, T []G2Jac, computeT func(T []G2Jac, t0 *G2Jac)) *G2Jac {\n\tvar t, selectorIndex, ks int\n\tvar selectorMask, selectorShift, selector uint64\n\n\tt = fr.ElementLimbs * 64 / int(s) // t from Bootle, equal to (scalar bit length) / s\n\tselectorMask = (1 << b) - 1 // low b bits are 1\n\tmorePoints := make([]G2Jac, t) // morePoints is the set of G'_k points from Bootle\n\tfor k := 0; k < t; k++ {\n\t\tmorePoints[k].Set(&curve.g2Infinity)\n\t}\n\tfor i := 0; i < len(points); i++ {\n\t\t// compute the set T_i from Bootle: all possible combinations of elements from S_i from Bootle\n\t\tcomputeT(T, &points[i])\n\t\t// for each morePoints: find the right T element and add it\n\t\tfor k := 0; k < t; k++ {\n\t\t\tks = k * int(s)\n\t\t\tselectorIndex = ks / 64\n\t\t\tselectorShift = uint64(ks - (selectorIndex * 64))\n\t\t\tselector = (scalars[i][selectorIndex] & (selectorMask << selectorShift)) >> selectorShift\n\t\t\tif selector != 0 {\n\t\t\t\tmorePoints[k].Add(curve, &T[selector-1])\n\t\t\t}\n\t\t}\n\t}\n\t// combine morePoints to get the final result\n\tp.Set(&morePoints[t-1])\n\tfor k := t - 2; k >= 0; k-- {\n\t\tfor j := uint64(0); j < s; j++ {\n\t\t\tp.Double()\n\t\t}\n\t\tp.Add(curve, &morePoints[k])\n\t}\n\treturn p\n}", "func RCPPS(mx, x operand.Op) { ctx.RCPPS(mx, x) }", "func LevelWidth(n Nodes, l Level) Nodes {\n\tif l < 0 {\n\t\tpanic(\"can't see below\")\n\t}\n\tfor l > 0 {\n\t\tn = (n + 1) / 2\n\t\tl--\n\t}\n\treturn n\n}", "func XLAT() { ctx.XLAT() }", "func (mtr *Dprdpr1intsramseccMetrics) getOffset(fldName string) int {\n\tvar offset int\n\n\tif fldName == \"DprPktinFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPktinFifoUncorrectable.Size()\n\n\tif fldName == \"DprPktinFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPktinFifoCorrectable.Size()\n\n\tif fldName == \"DprCsumFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprCsumFifoUncorrectable.Size()\n\n\tif fldName == \"DprCsumFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprCsumFifoCorrectable.Size()\n\n\tif fldName == \"DprPhvFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPhvFifoUncorrectable.Size()\n\n\tif fldName == \"DprPhvFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPhvFifoCorrectable.Size()\n\n\tif fldName == \"DprOhiFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprOhiFifoUncorrectable.Size()\n\n\tif fldName == \"DprOhiFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprOhiFifoCorrectable.Size()\n\n\tif fldName == \"DprPtrFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPtrFifoUncorrectable.Size()\n\n\tif fldName == \"DprPtrFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPtrFifoCorrectable.Size()\n\n\tif fldName == \"DprPktoutFifoUncorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPktoutFifoUncorrectable.Size()\n\n\tif fldName == \"DprPktoutFifoCorrectable\" {\n\t\treturn offset\n\t}\n\toffset += mtr.DprPktoutFifoCorrectable.Size()\n\n\treturn offset\n}", "func (gd *Definition) ConatainsPoint(x, y, buf float64) bool {\n\tif x < gd.Eorig-buf {\n\t\treturn false\n\t}\n\tif x > gd.Eorig+float64(gd.Ncol)*gd.Cwidth+buf {\n\t\treturn false\n\t}\n\tif y > gd.Norig+buf {\n\t\treturn false\n\t}\n\tif y < gd.Norig-float64(gd.Nrow)*gd.Cwidth-buf {\n\t\treturn false\n\t}\n\treturn true\n}", "func (m *metricMysqlBufferPoolPageFlushes) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}", "func (o IntegrationRuntimeManagedOutput) NodeSize() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationRuntimeManaged) pulumi.StringOutput { return v.NodeSize }).(pulumi.StringOutput)\n}", "func (mapData mapData) countTrees(deltaX, deltaY int) int {\n\tcount, x, y := 0, 0, 0\n\tfor y < mapData.height-1 {\n\t\tx = (x + deltaX) % (mapData.width) // move deltaX right and wrap around\n\t\ty += deltaY\n\t\t//log.Printf(\"X: %d, Y: %d, Tree: %s\", x, y, string(mapData.topography[y][x]))\n\t\tif mapData.topography[y][x] == '#' {\n\t\t\tcount++\n\t\t}\n\t}\n\treturn count\n}", "func (o AiFeatureStoreOnlineServingConfigScalingPtrOutput) MinNodeCount() pulumi.IntPtrOutput {\n\treturn o.ApplyT(func(v *AiFeatureStoreOnlineServingConfigScaling) *int {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.MinNodeCount\n\t}).(pulumi.IntPtrOutput)\n}" ]
[ "0.5026649", "0.50242597", "0.49472058", "0.49300432", "0.49166244", "0.47778267", "0.4630798", "0.46252307", "0.462098", "0.45679888", "0.45007497", "0.4496216", "0.44752523", "0.44449383", "0.44319668", "0.44183248", "0.43823767", "0.43734977", "0.43650812", "0.43611854", "0.43366182", "0.43319875", "0.4323907", "0.43074018", "0.43020278", "0.4299165", "0.42961204", "0.42908287", "0.42907083", "0.42806756", "0.42682275", "0.4266783", "0.4260159", "0.42556405", "0.42506075", "0.42408204", "0.4231112", "0.42269564", "0.4224998", "0.42229503", "0.4218999", "0.42142394", "0.42116496", "0.42090052", "0.42014432", "0.4198202", "0.41780895", "0.4177127", "0.41742015", "0.41734928", "0.41663134", "0.41597733", "0.41583705", "0.415742", "0.4144671", "0.41402733", "0.4136316", "0.41246566", "0.4119522", "0.41067892", "0.41035497", "0.4095868", "0.4093881", "0.4093579", "0.4091746", "0.40825835", "0.40814656", "0.4080417", "0.408017", "0.4070391", "0.40676516", "0.40665013", "0.40641722", "0.4047963", "0.40470484", "0.40433946", "0.40431273", "0.40430316", "0.40392387", "0.4038934", "0.4033748", "0.4033371", "0.40331122", "0.4032248", "0.40301603", "0.40297437", "0.40293524", "0.4027797", "0.4027551", "0.40248924", "0.4016983", "0.40120518", "0.4011203", "0.40106353", "0.40034983", "0.40034264", "0.4002698", "0.40001673", "0.39985245", "0.39965865" ]
0.47099692
6
GetMultipleClustersName retrive from the CLI (cobra) arguments one or more clusters name
func GetMultipleClustersName(cmd *cobra.Command, args []string) ([]string, error) { if len(args) == 0 { return nil, UserErrorf("requires a cluster name") } return args, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getClusterNameForMultiVC(ctx context.Context, vs *multiVCvSphere,\n\tclientIndex int) ([]*object.ClusterComputeResource,\n\t*VsanClient, error) {\n\n\tvar vsanHealthClient *VsanClient\n\tvar err error\n\tc := newClientForMultiVC(ctx, vs)\n\n\tdatacenter := strings.Split(multiVCe2eVSphere.multivcConfig.Global.Datacenters, \",\")\n\n\tfor i, client := range c {\n\t\tif clientIndex == i {\n\t\t\tvsanHealthClient, err = newVsanHealthSvcClient(ctx, client.Client)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t}\n\t}\n\n\tfinder := find.NewFinder(vsanHealthClient.vim25Client, false)\n\tdc, err := finder.Datacenter(ctx, datacenter[0])\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfinder.SetDatacenter(dc)\n\n\tclusterComputeResource, err := finder.ClusterComputeResourceList(ctx, \"*\")\n\tframework.Logf(\"clusterComputeResource %v\", clusterComputeResource)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\treturn clusterComputeResource, vsanHealthClient, err\n}", "func GetOneClusterName(cmd *cobra.Command, args []string, validate bool) (clusterName string, err error) {\n\tif len(args) == 0 {\n\t\treturn \"\", UserErrorf(\"requires a cluster name\")\n\t}\n\tif len(args) != 1 {\n\t\treturn \"\", UserErrorf(\"accepts 1 cluster name, received %d. %v\", len(args), args)\n\t}\n\tif len(args[0]) == 0 {\n\t\treturn \"\", UserErrorf(\"cluster name cannot be empty\")\n\t}\n\tif validate {\n\t\treturn kluster.ValidClusterName(args[0])\n\t}\n\treturn args[0], nil\n}", "func GetClusterNames(clusterName string) (lines []string, err error) {\n\t// For now, only supports one server, so server name will be based on th cluster name\n\tcmd := exec.Command(\n\t\t\"docker\",\n\t\t\"ps\",\n\t\t\"-q\", // quiet output for parsing\n\t\t\"-a\", // show stopped nodes\n\t\t\"--no-trunc\", // don't truncate\n\t\t// filter for nodes with the cluster label\n\t\t\"--filter\", fmt.Sprintf(\"label=%s=%s\", clusterconfig.ClusterLabelKey, clusterName),\n\t\t// format to include the cluster name\n\t\t\"--format\", `{{.Names}}`,\n\t)\n\tlines, err = docker.ExecOutput(*cmd, false)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// currentlt only supports one server\n\t// if len(lines) != 1 {\n\t// \treturn nil, fmt.Errorf(\"k3scli don't support multiserver now...\")\n\t// }\n\treturn lines, nil\n}", "func (c *Config) GetClusters(ctx context.Context, quiet bool, filterMap map[string]string, clustersName ...string) (string, error) {\n\tc.Logger.Debugf(\"Sending parameters to server to get the clusters %q\", strings.Join(clustersName, \", \"))\n\n\tfilter := MapToSlice(filterMap)\n\n\treturn c.RunGRPCnRESTFunc(\"get\", true,\n\t\tfunc() (string, error) {\n\t\t\treturn c.getClustersGRPC(ctx, quiet, filter, clustersName...)\n\t\t},\n\t\tfunc() (string, error) {\n\t\t\treturn c.getClustersHTTP(quiet, filter, clustersName...)\n\t\t})\n}", "func GetClusterName(self *C.PyObject, args *C.PyObject) *C.PyObject {\n\tclusterName := clustername.GetClusterName()\n\n\tcStr := C.CString(clusterName)\n\tpyStr := C.PyString_FromString(cStr)\n\tC.free(unsafe.Pointer(cStr))\n\treturn pyStr\n}", "func getClusters(kubeconfig string) ([]string, error) {\n\tkubectlArgs := []string{\"kubectl\"}\n\tif kubeconfig != \"\" {\n\t\tkubectlArgs = append(kubectlArgs, fmt.Sprintf(\"--kubeconfig=%s\", kubeconfig))\n\t}\n\tcontextArgs := append(kubectlArgs, []string{\"config\", \"get-contexts\", \"-o=name\"}...)\n\toutput, err := runCommand(contextArgs)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error in getting contexts from kubeconfig: %s\", err)\n\t}\n\treturn strings.Split(output, \"\\n\"), nil\n}", "func GetClusterNameOrDie() string {\n\tc, err := clientcmd.LoadFromFile(framework.TestContext.KubeConfig)\n\tframework.ExpectNoError(err, \"failed to load kubeconfig from file\")\n\n\tauthInfo := c.AuthInfos[c.Contexts[c.CurrentContext].AuthInfo]\n\n\tfor i, v := range authInfo.Exec.Args {\n\t\t// aws-iam-authenticator token\n\t\tif v == \"-i\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t\t// aws eks get-token\n\t\tif v == \"--cluster-name\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t}\n\tframework.Fail(\"failed to get EKS cluster name\")\n\treturn \"\"\n}", "func (c *Client) GetClusters(ctx context.Context) <-chan GetClusterResult {\n\t// TODO Make the concurrency configurable\n\tconcurrency := int(math.Min(5, float64(runtime.NumCPU())))\n\tresults := make(chan GetClusterResult, concurrency)\n\n\tclusterNames, err := c.GetClusterNames(ctx)\n\tif err != nil {\n\t\tclose(results)\n\t\treturn results\n\t}\n\n\tvar wg sync.WaitGroup\n\n\tgo func() {\n\t\tdefer close(results)\n\t\tfor _, clusterName := range clusterNames {\n\t\t\twg.Add(1)\n\t\t\tgo func(name string) {\n\t\t\t\tdefer wg.Done()\n\t\t\t\tcluster, err := c.GetCluster(ctx, name)\n\t\t\t\tresult := GetClusterResult{Cluster: cluster, Error: err}\n\t\t\t\tresults <- result\n\t\t\t}(clusterName)\n\t\t}\n\t\twg.Wait()\n\t}()\n\n\treturn results\n}", "func clusterList() []string {\n\tif c := envy.String(\"DQLITED_CLUSTER\"); c != \"\" {\n\t\treturn strings.Split(c, \",\")\n\t}\n\treturn defaultCluster\n}", "func bootstrapClusterName() string {\n\t// This constitutes a \"bootstrap\" invocation of \"kubectl\", we can't use the configuration because we are actually creating it\n\tcmd := exec.Command(\"kubectl\", \"config\", \"view\", \"--minify\", \"--output\", \"jsonpath={.clusters[0].name}\")\n\tif stdout, err := cmd.Output(); err == nil {\n\t\tif clusterName := strings.TrimSpace(string(stdout)); clusterName != \"\" {\n\t\t\treturn clusterName\n\t\t}\n\t}\n\treturn \"default\"\n}", "func getClusterName(utils detectorUtils) (string, error) {\n\tresp, err := utils.fetchString(\"GET\", k8sSvcURL+cwConfigmapPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: %w\", err)\n\t}\n\n\t// parse JSON object returned from HTTP request\n\tvar respmap map[string]json.RawMessage\n\terr = json.Unmarshal([]byte(resp), &respmap)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\tvar d data\n\terr = json.Unmarshal(respmap[\"data\"], &d)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\n\tclusterName := d.ClusterName\n\n\treturn clusterName, nil\n}", "func GetInstances(cmd *cobra.Command, params util.ClusterParams, flagName string) ([]string, error) {\n\tif all, _ := cmd.Flags().GetBool(\"all\"); all {\n\t\treturn instances.List(params)\n\t}\n\treturn cmd.Flags().GetStringSlice(flagName)\n}", "func (a *Client) GetClusters(params *GetClustersParams, opts ...ClientOption) (*GetClustersOK, *GetClustersMultiStatus, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetClustersParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetClusters\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/kubernetes-protection/entities/kubernetes/clusters/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetClustersReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *GetClustersOK:\n\t\treturn value, nil, nil\n\tcase *GetClustersMultiStatus:\n\t\treturn nil, value, nil\n\t}\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for kubernetes_protection: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a *ClusterControllerApiService) GetClustersUsingGET1(ctx _context.Context, account string, application string) apiGetClustersUsingGET1Request {\n\treturn apiGetClustersUsingGET1Request{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\taccount: account,\n\t\tapplication: application,\n\t}\n}", "func genInitialClusterArgs(replicas int32,\n\tstsName, svcName string) (argsVal string) {\n\tfor i := int32(0); i < replicas; i++ {\n\t\t// use 2380 as the default port for etcd peer communication\n\t\tpeerAddr := fmt.Sprintf(\"%s-%d=https://%s-%d.%s:%d\",\n\t\t\tstsName, i, stsName, i, svcName, 2380)\n\t\tif i == replicas-1 {\n\t\t\targsVal = argsVal + peerAddr\n\t\t\tbreak\n\t\t}\n\t\targsVal = argsVal + peerAddr + \",\"\n\t}\n\n\treturn argsVal\n}", "func genInitialClusterArgs(replicas int32, stsName, svcName string) (argsVal string) {\n\tfor i := int32(0); i < replicas; i++ {\n\t\t// use 2380 as the default port for etcd peer communication\n\t\tpeerAddr := fmt.Sprintf(\"%s-%d=https://%s-%d.%s:%d\",\n\t\t\tstsName, i, stsName, i, svcName, DefaultETCDPeerPort)\n\t\tif i == replicas-1 {\n\t\t\targsVal = argsVal + peerAddr\n\t\t\tbreak\n\t\t}\n\t\targsVal = argsVal + peerAddr + \",\"\n\t}\n\n\treturn argsVal\n}", "func (r *ProjectsInstancesClustersService) Get(name string) *ProjectsInstancesClustersGetCall {\n\tc := &ProjectsInstancesClustersGetCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.name = name\n\treturn c\n}", "func InitGetOpts(cmd *cobra.Command, args []string) (opts *InitOpts, warns []string, err error) {\n\twarns = make([]string, 0)\n\n\t// Validate cluster name\n\tclusterName, err := GetOneClusterName(cmd, args, true)\n\tif err != nil {\n\t\tif clusterName == \"\" {\n\t\t\treturn nil, warns, err\n\t\t}\n\t\twarns = append(warns, fmt.Sprintf(\"%s. They were replaced and the new cluster name is: %q\", err, clusterName))\n\t}\n\n\t// The `--update` flag will be deprecated and replaced by the `update` command\n\tupdate := false\n\tupdateFlag := cmd.Flags().Lookup(\"update\")\n\tif updateFlag != nil {\n\t\tupdate = updateFlag.Value.String() == \"true\"\n\t}\n\n\t// Validate platform (required unless it's an update)\n\tplatform := cmd.Flags().Lookup(\"platform\").Value.String()\n\tif len(platform) == 0 && !update {\n\t\treturn nil, warns, UserErrorf(\"platform is required\")\n\t}\n\tplatform = strings.ToLower(platform)\n\n\t// The `--path` and `--format` flags are only part of the `kubekit` binary\n\tvar path string\n\tif pathFlag := cmd.Flags().Lookup(\"path\"); pathFlag != nil {\n\t\tpath = pathFlag.Value.String()\n\t}\n\tvar format string\n\tif formatFlag := cmd.Flags().Lookup(\"format\"); formatFlag != nil {\n\t\tformat = formatFlag.Value.String()\n\t}\n\t// TODO: templateName will be used later to create a cluster from a template\n\tvar templateName string\n\tif templateNameFlag := cmd.Flags().Lookup(\"template\"); templateNameFlag != nil {\n\t\ttemplateName = templateNameFlag.Value.String()\n\t}\n\n\t// Variables:\n\tvarsStr := cmd.Flags().Lookup(\"var\").Value.String()\n\tvariables, warnV, errV := GetVariables(varsStr)\n\tif errV != nil {\n\t\treturn nil, warns, err\n\t}\n\tif len(warnV) != 0 {\n\t\twarns = append(warns, warnV...)\n\t}\n\n\t// Credentials:\n\tcreds := GetCredentials(platform, cmd)\n\n\treturn &InitOpts{\n\t\tClusterName: clusterName,\n\t\tPlatform: platform,\n\t\tPath: path,\n\t\tFormat: format,\n\t\tVariables: variables,\n\t\tCredentials: creds,\n\t\tTemplateName: templateName,\n\t\tUpdate: update,\n\t}, warns, nil\n}", "func getClusterNameFromZone(ctx context.Context, availabilityZone string) string {\n\tclusterName := \"\"\n\tclusterComputeResourceList, _, err := getClusterName(ctx, &e2eVSphere)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tnimbusGeneratedVcPwd := GetAndExpectStringEnvVar(vcUIPwd)\n\tcmd := fmt.Sprintf(\"dcli +username %s +password %s +skip +show com vmware \"+\n\t\t\"vcenter consumptiondomains zones cluster associations get --zone \"+\n\t\t\"%s\", adminUser, nimbusGeneratedVcPwd, availabilityZone)\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\tframework.Logf(\"Invoking command %v on vCenter host %v\", cmd, vcAddress)\n\tresult, err := fssh.SSH(cmd, vcAddress, framework.TestContext.Provider)\n\tframework.Logf(\"result: %v\", result)\n\tclusterId := strings.Split(result.Stdout, \"- \")[1]\n\tclusterID := strings.TrimSpace(clusterId)\n\tframework.Logf(\"clusterId: %v\", clusterID)\n\tfmt.Print(clusterId)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\tframework.Failf(\"couldn't execute command: %s on vCenter host: %v\", cmd, err)\n\t}\n\tfor _, cluster := range clusterComputeResourceList {\n\t\tclusterMoId := cluster.Reference().Value\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tframework.Logf(\"cluster MOID %v\", clusterMoId)\n\t\tif clusterMoId == clusterID {\n\t\t\tframework.Logf(\"Found matching cluster domain!!\")\n\t\t\tclusterName = cluster.Name()\n\t\t\tbreak\n\t\t}\n\t}\n\tframework.Logf(\"cluster on zone is: %s\", clusterName)\n\tif clusterName == \"\" {\n\t\tframework.Failf(\"couldn't find cluster on zone %s\", availabilityZone)\n\t}\n\treturn clusterName\n\n}", "func cmdCluster(c *cli.Context, subCmd string) string {\n\troute := \"_cluster/\"\n\turl := c.GlobalString(\"baseurl\")\n\n\tvar arg string\n\tswitch subCmd {\n\tcase \"health\":\n\t\targ = \"health\"\n\tcase \"state\":\n\t\targ = \"state\"\n\tdefault:\n\t\targ = \"\"\n\t}\n\treturn url + route + arg\n}", "func (o GetClustersClusterOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func getKubeClusterName(args []string, teleportClusterName string) (string, error) {\n\tkubeconfigLocation, selectedContext := extractKubeConfigAndContext(args)\n\tif selectedContext == \"\" {\n\t\tkubeName, err := kubeconfig.SelectedKubeCluster(kubeconfigLocation, teleportClusterName)\n\t\treturn kubeName, trace.Wrap(err)\n\t}\n\tkc, err := kubeconfig.Load(kubeconfigLocation)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\tkubeName := kubeconfig.KubeClusterFromContext(selectedContext, kc.Contexts[selectedContext], teleportClusterName)\n\tif kubeName == \"\" {\n\t\treturn \"\", trace.BadParameter(\"selected context %q does not belong to Teleport cluster %q\", selectedContext, teleportClusterName)\n\t}\n\treturn kubeName, nil\n}", "func getInputClusters(args []string) (inputClusterMap, error) {\n\tinputs := make(inputClusterMap)\n\tfor _, val := range args {\n\t\tfields := vv8LogNamePattern.FindStringSubmatch(val)\n\t\tif len(fields) > 0 {\n\t\t\tkey := fields[1] + \"0.log\"\n\t\t\trank, err := strconv.Atoi(fields[2])\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tinputs[key] = append(inputs[key], logSegment{rank, val})\n\t\t} else {\n\t\t\t// \"@oid\" (no input files) or \"-\" (stdin)\n\t\t\tinputs[val] = []logSegment{{0, val}}\n\t\t}\n\t}\n\tfor _, files := range inputs {\n\t\tif len(files) > 0 {\n\t\t\tsort.Slice(files, func(i, j int) bool {\n\t\t\t\treturn files[i].rank < files[j].rank\n\t\t\t})\n\t\t}\n\t}\n\treturn inputs, nil\n}", "func (a *Client) GetCombinedCloudClusters(params *GetCombinedCloudClustersParams, opts ...ClientOption) (*GetCombinedCloudClustersOK, *GetCombinedCloudClustersMultiStatus, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetCombinedCloudClustersParams()\n\t}\n\top := &runtime.ClientOperation{\n\t\tID: \"GetCombinedCloudClusters\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/kubernetes-protection/entities/cloud_cluster/v1\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\", \"application/octet-stream\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetCombinedCloudClustersReader{formats: a.formats},\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t}\n\tfor _, opt := range opts {\n\t\topt(op)\n\t}\n\n\tresult, err := a.transport.Submit(op)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tswitch value := result.(type) {\n\tcase *GetCombinedCloudClustersOK:\n\t\treturn value, nil, nil\n\tcase *GetCombinedCloudClustersMultiStatus:\n\t\treturn nil, value, nil\n\t}\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for kubernetes_protection: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (a *DefaultApiService) ListClusters(ctx _context.Context, localVarOptionals *ListClustersOpts) (Clusters, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Clusters\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/clusters\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Id.IsSet() {\n\t\tt:=localVarOptionals.Id.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotId.IsSet() {\n\t\tt:=localVarOptionals.NotId.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!id[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!id[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.StoryCountMin.IsSet() {\n\t\tlocalVarQueryParams.Add(\"story_count.min\", parameterToString(localVarOptionals.StoryCountMin.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.StoryCountMax.IsSet() {\n\t\tlocalVarQueryParams.Add(\"story_count.max\", parameterToString(localVarOptionals.StoryCountMax.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.TimeStart.IsSet() {\n\t\tlocalVarQueryParams.Add(\"time.start\", parameterToString(localVarOptionals.TimeStart.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.TimeEnd.IsSet() {\n\t\tlocalVarQueryParams.Add(\"time.end\", parameterToString(localVarOptionals.TimeEnd.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EarliestStoryStart.IsSet() {\n\t\tlocalVarQueryParams.Add(\"earliest_story.start\", parameterToString(localVarOptionals.EarliestStoryStart.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.EarliestStoryEnd.IsSet() {\n\t\tlocalVarQueryParams.Add(\"earliest_story.end\", parameterToString(localVarOptionals.EarliestStoryEnd.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.LatestStoryStart.IsSet() {\n\t\tlocalVarQueryParams.Add(\"latest_story.start\", parameterToString(localVarOptionals.LatestStoryStart.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.LatestStoryEnd.IsSet() {\n\t\tlocalVarQueryParams.Add(\"latest_story.end\", parameterToString(localVarOptionals.LatestStoryEnd.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.LocationCountry.IsSet() {\n\t\tt:=localVarOptionals.LocationCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"location.country\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"location.country\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.NotLocationCountry.IsSet() {\n\t\tt:=localVarOptionals.NotLocationCountry.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"!location.country\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"!location.country\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Return_.IsSet() {\n\t\tt:=localVarOptionals.Return_.Value()\n\t\tif reflect.TypeOf(t).Kind() == reflect.Slice {\n\t\t\ts := reflect.ValueOf(t)\n\t\t\tfor i := 0; i < s.Len(); i++ {\n\t\t\t\tlocalVarQueryParams.Add(\"return[]\", parameterToString(s.Index(i), \"multi\"))\n\t\t\t}\n\t\t} else {\n\t\t\tlocalVarQueryParams.Add(\"return[]\", parameterToString(t, \"multi\"))\n\t\t}\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SortBy.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sort_by\", parameterToString(localVarOptionals.SortBy.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.SortDirection.IsSet() {\n\t\tlocalVarQueryParams.Add(\"sort_direction\", parameterToString(localVarOptionals.SortDirection.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Cursor.IsSet() {\n\t\tlocalVarQueryParams.Add(\"cursor\", parameterToString(localVarOptionals.Cursor.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.PerPage.IsSet() {\n\t\tlocalVarQueryParams.Add(\"per_page\", parameterToString(localVarOptionals.PerPage.Value(), \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\", \"text/xml\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-AYLIEN-NewsAPI-Application-ID\"] = key\n\t\t}\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"X-AYLIEN-NewsAPI-Application-Key\"] = key\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 401 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 404 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 422 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 429 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 500 {\n\t\t\tvar v Errors\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func getClusterName(nodes []corev1.Node) string {\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnode := nodes[0]\n\tif node.Labels[clusterNameLabel] != \"\" {\n\t\treturn node.Labels[clusterNameLabel]\n\t}\n\tif node.ClusterName != \"\" {\n\t\treturn node.ClusterName\n\t}\n\n\t// Hack for clusters that don't have ClusterName as a label on the nodes (pre-1.15?)\n\tif _, hasLabel := node.Labels[gkeNodePoolLabel]; hasLabel {\n\t\t// Split/TrimPrefix:\n\t\t// gke-mycluster-1-node-pool-1-b486c6b7-chm7\n\t\t// pre^clusterName^postfix_____________^node-hash\n\t\tprefix := \"gke-\"\n\t\tpostfix := \"-\" + node.Labels[gkeNodePoolLabel]\n\t\tclusterName := strings.Split(strings.TrimPrefix(node.Name, prefix), postfix)[0]\n\t\tlog.Info(\"getClusterName: used a hack to determine the clusterName from hostname\", \"hostname\", node.Name, \"clustername\", clusterName)\n\t\treturn clusterName\n\t}\n\tlog.Error(fmt.Errorf(\"Failed to getClusterName from %#v\", node), \"getClusterName failure\")\n\tpanic(\"ClusterName could not be determined\")\n}", "func (o *QueueManager) GetClusters() []string {\n\tif o == nil {\n\t\tvar ret []string\n\t\treturn ret\n\t}\n\n\treturn o.Clusters\n}", "func fetchCluster(c *gin.Context) string {\n\tconst key = \"cluster\"\n\n\tswitch {\n\tcase len(c.Param(key)) > 0:\n\t\treturn c.Param(key)\n\tcase len(c.Query(key)) > 0:\n\t\treturn c.Query(key)\n\tcase len(c.PostForm(key)) > 0:\n\t\treturn c.PostForm(key)\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func newCluster() *cobra.Command {\n\tvar cluster *[]string\n\n\tcmd := &cobra.Command{\n\t\tUse: \"cluster\",\n\t\tShort: \"display cluster nodes.\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := getLeader(*cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't connect to cluster leader\")\n\t\t\t}\n\t\t\tdefer client.Close()\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tvar leader *dqclient.NodeInfo\n\t\t\tvar nodes []dqclient.NodeInfo\n\t\t\tif leader, err = client.Leader(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get leader\")\n\t\t\t}\n\n\t\t\tif nodes, err = client.Cluster(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get cluster\")\n\t\t\t}\n\n\t\t\tfmt.Printf(\"ID \\tLeader \\tAddress\\n\")\n\t\t\tfor _, node := range nodes {\n\t\t\t\tfmt.Printf(\"%d \\t%v \\t%s\\n\", node.ID, node.ID == leader.ID, node.Address)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tcluster = flags.StringSliceP(\"cluster\", \"c\", defaultCluster, \"addresses of existing cluster nodes\")\n\n\treturn cmd\n}", "func (config *DirectClientConfig) getClusterName() (string, bool) {\n\tif config.overrides != nil && len(config.overrides.Context.Cluster) != 0 {\n\t\treturn config.overrides.Context.Cluster, true\n\t}\n\tcontext, _ := config.getContext()\n\treturn context.Cluster, false\n}", "func DestroyClustersCommand(provider *kind.Provider) *cobra.Command {\n\tflags := &DestroyClusterFlagpole{}\n\tcmd := &cobra.Command{\n\t\tArgs: cobra.NoArgs,\n\t\tUse: \"clusters\",\n\t\tShort: \"Destroy clusters\",\n\t\tLong: \"Destroys clusters\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\t\tvar targetClusters []string\n\t\t\tif len(flags.Clusters) > 0 {\n\t\t\t\ttargetClusters = append(targetClusters, flags.Clusters...)\n\t\t\t} else {\n\t\t\t\tconfigFiles, err := ioutil.ReadDir(defaults.KindConfigDir)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t\tfor _, configFile := range configFiles {\n\t\t\t\t\tclName := strings.FieldsFunc(configFile.Name(), func(r rune) bool { return strings.ContainsRune(\" -.\", r) })[2]\n\t\t\t\t\ttargetClusters = append(targetClusters, clName)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, clName := range targetClusters {\n\t\t\t\tknown, err := cluster.IsKnown(clName, provider)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalf(\"%s: %v\", clName, err)\n\t\t\t\t}\n\t\t\t\tif known {\n\t\t\t\t\terr := cluster.Destroy(clName, provider)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatalf(\"%s: %v\", clName, err)\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tlog.Errorf(\"cluster %q not found.\", clName)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().StringSliceVarP(&flags.Clusters, \"clusters\", \"c\", []string{}, \"comma separated list of cluster names to destroy. eg: cl1,cl6,cl3\")\n\treturn cmd\n}", "func FetchClusters(c *gin.Context) {\n\n\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, \"Start listing clusters\")\n\n\tvar clusters []banzaiSimpleTypes.ClusterSimple\n\tvar response []*cloud.ClusterRepresentation\n\tdatabase.Find(&clusters)\n\n\tif len(clusters) <= 0 {\n\t\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, \"No clusters found\")\n\t\tcloud.SetResponseBodyJson(c, http.StatusNotFound, gin.H{\n\t\t\tcloud.JsonKeyStatus: http.StatusNotFound,\n\t\t\tcloud.JsonKeyMessage: \"No clusters found!\",\n\t\t})\n\t\treturn\n\t}\n\n\tfor _, cl := range clusters {\n\t\tclust := cloud.GetClusterRepresentation(&cl)\n\t\tif clust != nil {\n\t\t\tbanzaiUtils.LogInfo(banzaiConstants.TagListClusters, fmt.Sprintf(\"Append %#v cluster representation to response\", clust))\n\t\t\tresponse = append(response, clust)\n\t\t}\n\n\t}\n\tcloud.SetResponseBodyJson(c, http.StatusOK, gin.H{\n\t\tcloud.JsonKeyStatus: http.StatusOK,\n\t\tcloud.JsonKeyData: response,\n\t})\n}", "func (o AppProjectSpecSyncWindowsOutput) Clusters() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AppProjectSpecSyncWindows) []string { return v.Clusters }).(pulumi.StringArrayOutput)\n}", "func (c *ClientImpl) GetClusters(ctx context.Context, hcpHostURL string) (models.ClusterResp, error) {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, \"Get Clusters\")\n\tdefer span.Finish()\n\n\tsession, err := c.getSession(ctx, hcpHostURL, hcpUserName, hcpPassword)\n\tif err != nil {\n\t\treturn models.ClusterResp{}, err\n\t}\n\n\tstatus = Failure\n\tmonitor := metrics.StartExternalCall(externalSvcName, \"Fetch Clusters\")\n\tdefer func() { monitor.RecordWithStatus(status) }()\n\n\tresp, err := mlopsHttp.ExecuteHTTPRequest(\n\t\tctx,\n\t\tc.client,\n\t\thcpHostURL+clusterPathV2,\n\t\thttp.MethodGet,\n\t\tmap[string]string{sessionHeader: session},\n\t\tbytes.NewReader(nil),\n\t)\n\tif err != nil {\n\t\treturn models.ClusterResp{}, errors.Wrapf(err, \"while fetching clusters in MLOps controller platform.\")\n\t}\n\tresp.Body.Close()\n\n\tstatus = Success\n\n\terr = c.deleteSession(ctx, hcpHostURL, session)\n\tif err != nil {\n\t\treturn models.ClusterResp{}, err\n\t}\n\n\tclustersResp := models.ClusterResp{}\n\tjson.NewDecoder(resp.Body).Decode(&clustersResp)\n\n\treturn clustersResp, nil\n}", "func GetClusterName(executionSpaceName string) (string, error) {\n\tif !strings.HasPrefix(executionSpaceName, ExecutionSpacePrefix) {\n\t\treturn \"\", fmt.Errorf(\"the execution space name is in wrong format\")\n\t}\n\treturn strings.TrimPrefix(executionSpaceName, ExecutionSpacePrefix), nil\n}", "func (c *krakenClusters) Get(name string, options v1.GetOptions) (result *v1alpha1.KrakenCluster, err error) {\n\tresult = &v1alpha1.KrakenCluster{}\n\terr = c.client.Get().\n\t\tNamespace(c.ns).\n\t\tResource(\"krakenclusters\").\n\t\tName(name).\n\t\tVersionedParams(&options, scheme.ParameterCodec).\n\t\tDo().\n\t\tInto(result)\n\treturn\n}", "func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) {\n\tclusterInfos := config.config.Clusters\n\tclusterInfoName, required := config.getClusterName()\n\n\tmergedClusterInfo := clientcmdapi.NewCluster()\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterDefaults, mergo.WithOverride)\n\t}\n\tif configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {\n\t\tmergo.Merge(mergedClusterInfo, configClusterInfo, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Cluster{}, fmt.Errorf(\"cluster %q does not exist\", clusterInfoName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterInfo, mergo.WithOverride)\n\t}\n\n\t// * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data\n\t// otherwise, a kubeconfig containing a CA reference would return an error that \"CA and insecure-skip-tls-verify couldn't both be set\".\n\t// * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence.\n\tif config.overrides != nil {\n\t\tcaLen := len(config.overrides.ClusterInfo.CertificateAuthority)\n\t\tcaDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData)\n\t\tif config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen > 0 || caDataLen > 0 {\n\t\t\tmergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify\n\t\t\tmergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority\n\t\t\tmergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData\n\t\t}\n\n\t\t// if the --tls-server-name has been set in overrides, use that value.\n\t\t// if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property\n\t\t// that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is\n\t\t// usually correct.\n\t\tif config.overrides.ClusterInfo.TLSServerName != \"\" || config.overrides.ClusterInfo.Server != \"\" {\n\t\t\tmergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName\n\t\t}\n\t}\n\n\treturn *mergedClusterInfo, nil\n}", "func getTargetClusterNames(deployment *appsv1.Deployment) (targetClusterNames []string, err error) {\n\tbindingName := names.GenerateBindingName(deployment.Kind, deployment.Name)\n\tfmt.Printf(\"deploy kind is %s, name is %s\\n\", deployment.Kind, deployment.Name)\n\tbinding := &workv1alpha1.ResourceBinding{}\n\n\tfmt.Printf(\"collect the target clusters in resource binding\\n\")\n\terr = wait.Poll(pollInterval, pollTimeout, func() (done bool, err error) {\n\t\terr = controlPlaneClient.Get(context.TODO(), client.ObjectKey{Namespace: deployment.Namespace, Name: bindingName}, binding)\n\t\tif err != nil {\n\t\t\tif errors.IsNotFound(err) {\n\t\t\t\treturn false, nil\n\t\t\t}\n\t\t\treturn false, err\n\t\t}\n\t\treturn true, nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, cluster := range binding.Spec.Clusters {\n\t\ttargetClusterNames = append(targetClusterNames, cluster.Name)\n\t}\n\tfmt.Printf(\"target clusters in resource binding are %s\\n\", targetClusterNames)\n\treturn targetClusterNames, nil\n}", "func ExampleClustersClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armservicefabric.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClustersClient().Get(ctx, \"resRg\", \"myCluster\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.Cluster = armservicefabric.Cluster{\n\t// \tName: to.Ptr(\"myCluster\"),\n\t// \tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \tEtag: to.Ptr(\"W/\\\"636462502169240745\\\"\"),\n\t// \tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster\"),\n\t// \tLocation: to.Ptr(\"eastus\"),\n\t// \tTags: map[string]*string{\n\t// \t},\n\t// \tProperties: &armservicefabric.ClusterProperties{\n\t// \t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager),\n\t// \t\t\tto.Ptr(armservicefabric.AddOnFeaturesDNSService),\n\t// \t\t\tto.Ptr(armservicefabric.AddOnFeaturesBackupRestoreService),\n\t// \t\t\tto.Ptr(armservicefabric.AddOnFeaturesResourceMonitorService)},\n\t// \t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentWindows),\n\t// \t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t}},\n\t// \t\t\tAzureActiveDirectory: &armservicefabric.AzureActiveDirectory{\n\t// \t\t\t\tClientApplication: to.Ptr(\"d151ad89-4bce-4ae8-b3d1-1dc79679fa75\"),\n\t// \t\t\t\tClusterApplication: to.Ptr(\"5886372e-7bf4-4878-a497-8098aba608ae\"),\n\t// \t\t\t\tTenantID: to.Ptr(\"6abcc6a0-8666-43f1-87b8-172cf86a9f9c\"),\n\t// \t\t\t},\n\t// \t\t\tCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t}},\n\t// \t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t},\n\t// \t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\tIsAdmin: to.Ptr(true),\n\t// \t\t\t}},\n\t// \t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tCertificateThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\tIsAdmin: to.Ptr(true),\n\t// \t\t\t}},\n\t// \t\t\tClusterCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\tClusterID: to.Ptr(\"92584666-9889-4ae8-8d02-91902923d37f\"),\n\t// \t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t},\n\t// \t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t}},\n\t// \t\t\tManagementEndpoint: to.Ptr(\"https://myCluster.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t{\n\t// \t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t}},\n\t// \t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\tReverseProxyCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t{\n\t// \t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t}},\n\t// \t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t},\n\t// \t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\tApplicationDeltaHealthPolicies: map[string]*armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\tDefaultServiceTypeDeltaHealthPolicy: &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tServiceTypeDeltaHealthPolicies: map[string]*armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t},\n\t// \t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\tApplicationHealthPolicies: map[string]*armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\tDefaultServiceTypeHealthPolicy: &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tServiceTypeHealthPolicies: map[string]*armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](100),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t},\n\t// \t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t},\n\t// \t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\tVMImage: to.Ptr(\"Windows\"),\n\t// \t\t},\n\t// \t}\n}", "func newCmdClusterList(ctx api.Context) *cobra.Command {\n\tvar attachedOnly bool\n\tvar jsonOutput bool\n\tvar names bool\n\tcmd := &cobra.Command{\n\t\tUse: \"list\",\n\t\tShort: \"List the clusters configured and the ones linked to the current cluster\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif names {\n\t\t\t\tclusters, err := ctx.Clusters()\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\tfor _, cluster := range clusters {\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.Name())\n\t\t\t\t\tfmt.Fprintln(ctx.Out(), cluster.ID())\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tvar filters []lister.Filter\n\t\t\tif attachedOnly {\n\t\t\t\tfilters = append(filters, lister.AttachedOnly())\n\t\t\t} else {\n\t\t\t\tfilters = append(filters, lister.Linked())\n\t\t\t}\n\n\t\t\tconfigManager, err := ctx.ConfigManager()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\titems := lister.New(configManager, ctx.Logger()).List(filters...)\n\t\t\tif attachedOnly && len(items) == 0 {\n\t\t\t\treturn errors.New(\"no cluster is attached. Please run `dcos cluster attach <cluster-name>`\")\n\t\t\t}\n\n\t\t\tif jsonOutput {\n\t\t\t\tenc := json.NewEncoder(ctx.Out())\n\t\t\t\tenc.SetIndent(\"\", \" \")\n\t\t\t\treturn enc.Encode(items)\n\t\t\t}\n\n\t\t\ttable := cli.NewTable(ctx.Out(), []string{\"\", \"NAME\", \"ID\", \"STATUS\", \"VERSION\", \"URL\"})\n\t\t\tfor _, item := range items {\n\t\t\t\tvar attached string\n\t\t\t\tif item.Attached {\n\t\t\t\t\tattached = \"*\"\n\t\t\t\t}\n\t\t\t\ttable.Append([]string{attached, item.Name, item.ID, item.Status, item.Version, item.URL})\n\t\t\t}\n\t\t\ttable.Render()\n\n\t\t\treturn nil\n\t\t},\n\t}\n\tcmd.Flags().BoolVar(&attachedOnly, \"attached\", false, \"returns attached cluster only\")\n\tcmd.Flags().BoolVar(&jsonOutput, \"json\", false, \"returns clusters in json format\")\n\tcmd.Flags().BoolVar(&names, \"names\", false, \"print out a list of cluster names and IDs\")\n\tcmd.Flags().MarkHidden(\"names\")\n\treturn cmd\n}", "func getClusterNameLabel() string {\n\tkey := fmt.Sprintf(\"%s/cluster-name\", getCAPIGroup())\n\treturn key\n}", "func Cluster(context *cli.Context) error {\n\tregion := context.String(flags.RegionFlag)\n\tif err := fieldEmpty(region, flags.RegionFlag); err != nil {\n\t\treturn err\n\t}\n\tclusterProfileName := context.String(flags.ConfigNameFlag)\n\tif err := fieldEmpty(clusterProfileName, flags.ConfigNameFlag); err != nil {\n\t\treturn err\n\t}\n\tcluster := context.String(flags.ClusterFlag)\n\tif err := fieldEmpty(cluster, flags.ClusterFlag); err != nil {\n\t\treturn err\n\t}\n\n\tlaunchType := context.String(flags.DefaultLaunchTypeFlag)\n\tif err := config.ValidateLaunchType(launchType); err != nil {\n\t\treturn err\n\t}\n\n\tcfnStackName := context.String(flags.CFNStackNameFlag)\n\tcomposeServiceNamePrefix := context.String(flags.ComposeServiceNamePrefixFlag)\n\n\tclusterConfig := &config.Cluster{\n\t\tCluster: cluster,\n\t\tRegion: region,\n\t\tCFNStackName: cfnStackName,\n\t\tComposeServiceNamePrefix: composeServiceNamePrefix,\n\t\tDefaultLaunchType: launchType,\n\t}\n\n\trdwr, err := config.NewReadWriter()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error saving cluster configuration\")\n\t}\n\tif err = rdwr.SaveCluster(clusterProfileName, clusterConfig); err != nil {\n\t\treturn errors.Wrap(err, \"Error saving cluster configuration\")\n\t}\n\n\tlogrus.Infof(\"Saved ECS CLI cluster configuration %s.\", clusterProfileName)\n\treturn nil\n}", "func (a ClustersAPI) Get(clusterID string) (httpmodels.GetResp, error) {\n\tvar clusterInfo httpmodels.GetResp\n\n\tdata := struct {\n\t\tClusterID string `json:\"cluster_id,omitempty\" url:\"cluster_id,omitempty\"`\n\t}{\n\t\tclusterID,\n\t}\n\tresp, err := a.Client.performQuery(http.MethodGet, \"/clusters/get\", data, nil)\n\tif err != nil {\n\t\treturn clusterInfo, err\n\t}\n\n\terr = json.Unmarshal(resp, &clusterInfo)\n\treturn clusterInfo, err\n}", "func AzureGetClusters(subscriptionID, clientID, clientSecret, tenantID, resourceGroupName string, admin bool) (string, error) {\n\tctx := context.Background()\n\tclient := containerservice.NewManagedClustersClient(subscriptionID)\n\n\tauthorizer, err := getAzureAuthorizer(clientID, clientSecret, tenantID)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tclient.Authorizer = authorizer\n\n\tvar clusters []string\n\n\tfor list, err := client.ListComplete(ctx); list.NotDone(); err = list.Next() {\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\n\t\tvar res containerservice.CredentialResults\n\t\tname := *list.Value().Name\n\n\t\tif admin {\n\t\t\tres, err = client.ListClusterAdminCredentials(ctx, resourceGroupName, name)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t} else {\n\t\t\tres, err = client.ListClusterUserCredentials(ctx, resourceGroupName, name)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\t\t}\n\n\t\tfor _, kubeconfig := range *res.Kubeconfigs {\n\t\t\tvar kubeconfigJSON interface{}\n\t\t\terr := yaml.Unmarshal(*kubeconfig.Value, &kubeconfigJSON)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tkubeconfigJSON = convert(kubeconfigJSON)\n\t\t\tkubeconfigJSONString, err := json.Marshal(kubeconfigJSON)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", err\n\t\t\t}\n\n\t\t\tclusters = append(clusters, fmt.Sprintf(\"{\\\"name\\\": \\\"%s_%s_%s\\\", \\\"kubeconfig\\\": %s}\", *kubeconfig.Name, resourceGroupName, name, kubeconfigJSONString))\n\t\t}\n\t}\n\n\treturn fmt.Sprintf(\"[%s]\", strings.Join(clusters, \",\")), nil\n}", "func GetClusterNames() ([]string, error) {\n\tclusterMap, err := assertClusterMap()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tout := make([]string, len(clusterMap))\n\ti := 0\n\tfor name := range clusterMap {\n\t\tout[i] = name\n\t\ti++\n\t}\n\treturn out, nil\n}", "func (o AppV2Output) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (e *ECS) ListClusters(req *ListClustersReq) (\n\t*ListClustersResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"ListClusters\")\n\tif req.MaxResults > 0 {\n\t\tparams[\"maxResults\"] = strconv.Itoa(int(req.MaxResults))\n\t}\n\tif req.NextToken != \"\" {\n\t\tparams[\"nextToken\"] = req.NextToken\n\t}\n\n\tresp := new(ListClustersResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func GetCoveredClusters(\n\trepoRoot string,\n\tdiffs []*github.CommitFile,\n\tenv string,\n\tselectedClusterGlobStrs []string,\n\tsubpathOverride string,\n\tmultiSubpaths bool,\n) ([]*config.ClusterConfig, error) {\n\tselectedClusterGlobs := []glob.Glob{}\n\n\tfor _, globStr := range selectedClusterGlobStrs {\n\t\tglobObj, err := glob.Compile(globStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tselectedClusterGlobs = append(selectedClusterGlobs, globObj)\n\t}\n\n\tchangedClusterPaths := map[string][]string{}\n\n\t// Keep map of each config path to its object and all of its files\n\tconfigsMap := map[string]*config.ClusterConfig{}\n\tconfigFilesMap := map[string][]string{}\n\n\t// Walk repo looking for cluster configs\n\terr := filepath.Walk(\n\t\trepoRoot,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif info.IsDir() {\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tif strings.HasSuffix(path, \".yaml\") {\n\t\t\t\tfileContents, err := ioutil.ReadFile(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstringContents := string(fileContents)\n\t\t\t\tif strings.Contains(stringContents, \"cluster:\") {\n\t\t\t\t\tconfigObj, err := config.LoadClusterConfig(path, repoRoot)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Debugf(\n\t\t\t\t\t\t\t\"Error evaluating whether %s is a cluster config: %+v\",\n\t\t\t\t\t\t\tpath,\n\t\t\t\t\t\t\terr,\n\t\t\t\t\t\t)\n\n\t\t\t\t\t\t// Probably not a cluster config, skip over it\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\tlog.Infof(\"Found cluster config: %s\", path)\n\n\t\t\t\t\tif len(selectedClusterGlobs) > 0 {\n\t\t\t\t\t\tvar matches bool\n\n\t\t\t\t\t\tfor _, globObj := range selectedClusterGlobs {\n\t\t\t\t\t\t\tif globObj.Match(configObj.DescriptiveName()) {\n\t\t\t\t\t\t\t\tmatches = true\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif !matches {\n\t\t\t\t\t\t\tlog.Infof(\n\t\t\t\t\t\t\t\t\"Ignoring cluster %s because selectedClusters is set and cluster is not in set\",\n\t\t\t\t\t\t\t\tconfigObj.DescriptiveName(),\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\treturn nil\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tif configObj.GithubIgnore {\n\t\t\t\t\t\tlog.Infof(\n\t\t\t\t\t\t\t\"Ignoring cluster %s because GithubIgnore is true\",\n\t\t\t\t\t\t\tconfigObj.DescriptiveName(),\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\tif env != \"\" && configObj.Env != env {\n\t\t\t\t\t\tlog.Infof(\n\t\t\t\t\t\t\t\"Ignoring cluster %s because env is not %s\",\n\t\t\t\t\t\t\tconfigObj.DescriptiveName(),\n\t\t\t\t\t\t\tenv,\n\t\t\t\t\t\t)\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t}\n\n\t\t\t\t\trelPath, err := filepath.Rel(repoRoot, path)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\tconfigsMap[relPath] = configObj\n\t\t\t\t\tconfigFiles, err := getExpandedConfigFiles(repoRoot, configObj)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\n\t\t\t\t\tif len(selectedClusterGlobs) > 0 {\n\t\t\t\t\t\tchangedClusterPaths[relPath] = []string{}\n\t\t\t\t\t}\n\n\t\t\t\t\tconfigFilesMap[relPath] = configFiles\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Map from each file to the names of the configs that reference it\n\tconfigsPerFile := map[string][]string{}\n\n\tfor configPath, configFiles := range configFilesMap {\n\t\tfor _, configFile := range configFiles {\n\t\t\tif _, ok := configsPerFile[configFile]; !ok {\n\t\t\t\tconfigsPerFile[configFile] = []string{}\n\t\t\t}\n\n\t\t\tconfigsPerFile[configFile] = append(configsPerFile[configFile], configPath)\n\t\t}\n\t}\n\n\tfor _, diff := range diffs {\n\t\tdiffFile := diff.GetFilename()\n\n\t\tconfigPaths, ok := configsPerFile[diffFile]\n\t\tif ok {\n\t\t\tfor _, configPath := range configPaths {\n\t\t\t\tchangedClusterPaths[configPath] = append(\n\t\t\t\t\tchangedClusterPaths[configPath],\n\t\t\t\t\tdiffFile,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\t// In case where someone has used a wildcard, prune clusters that have no changes\n\t// to avoid unexpected applies.\n\thasWildcards := false\n\n\tfor _, globStr := range selectedClusterGlobStrs {\n\t\tif strings.Contains(globStr, \"*\") {\n\t\t\thasWildcards = true\n\t\t\tbreak\n\t\t}\n\t}\n\n\tif hasWildcards {\n\t\tfor cluster, paths := range changedClusterPaths {\n\t\t\tif len(paths) == 0 {\n\t\t\t\tlog.Infof(\"Removing cluster %s because it has no changes\", cluster)\n\t\t\t\tdelete(changedClusterPaths, cluster)\n\t\t\t}\n\t\t}\n\t}\n\n\tlog.Infof(\"Changed cluster paths: %+v\", changedClusterPaths)\n\n\tchangedClusters := []*config.ClusterConfig{}\n\n\tfor clusterPath, changedFiles := range changedClusterPaths {\n\t\tconfig := configsMap[clusterPath]\n\n\t\tif subpathOverride != \"\" {\n\t\t\tconfig.Subpaths = []string{subpathOverride}\n\t\t} else {\n\t\t\trelExpandedPath, err := filepath.Rel(repoRoot, config.ExpandedPath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tif multiSubpaths {\n\t\t\t\tconfig.Subpaths, err = lowestParents(relExpandedPath, changedFiles)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\t// Override subpath based on files that have changed\n\t\t\t\tparentDir, err := lowestParent(relExpandedPath, changedFiles)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tconfig.Subpaths = []string{parentDir}\n\t\t\t}\n\t\t}\n\n\t\tlog.Infof(\"Setting subpaths for cluster %s to %+v\", clusterPath, config.Subpaths)\n\n\t\tchangedClusters = append(changedClusters, config)\n\t}\n\n\t// Sort by path\n\tsort.Slice(\n\t\tchangedClusters,\n\t\tfunc(a, b int) bool {\n\t\t\treturn changedClusters[a].RelPath() < changedClusters[b].RelPath()\n\t\t},\n\t)\n\n\treturn changedClusters, nil\n}", "func (o OceanOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func ExampleClustersClient_ListByResourceGroup() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armservicefabric.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClustersClient().ListByResourceGroup(ctx, \"resRg\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ClusterListResult = armservicefabric.ClusterListResult{\n\t// \tValue: []*armservicefabric.Cluster{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"myCluster\"),\n\t// \t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\tEtag: to.Ptr(\"W/\\\"636462502169240745\\\"\"),\n\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster\"),\n\t// \t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\tTags: map[string]*string{\n\t// \t\t\t},\n\t// \t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesDNSService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesBackupRestoreService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesResourceMonitorService)},\n\t// \t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentWindows),\n\t// \t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tAzureActiveDirectory: &armservicefabric.AzureActiveDirectory{\n\t// \t\t\t\t\t\tClientApplication: to.Ptr(\"d151ad89-4bce-4ae8-b3d1-1dc79679fa75\"),\n\t// \t\t\t\t\t\tClusterApplication: to.Ptr(\"5886372e-7bf4-4878-a497-8098aba608ae\"),\n\t// \t\t\t\t\t\tTenantID: to.Ptr(\"6abcc6a0-8666-43f1-87b8-172cf86a9f9c\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(true),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(false),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\tClusterID: to.Ptr(\"92584666-9889-4ae8-8d02-91902923d37f\"),\n\t// \t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tManagementEndpoint: to.Ptr(\"https://myCluster.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\tReverseProxyCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationDeltaHealthPolicies: map[string]*armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeDeltaHealthPolicy: &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeDeltaHealthPolicies: map[string]*armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationHealthPolicies: map[string]*armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeHealthPolicy: &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeHealthPolicies: map[string]*armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](100),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\tVMImage: to.Ptr(\"Windows\"),\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"myCluster2\"),\n\t// \t\t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\t\tEtag: to.Ptr(\"W/\\\"636462502164040075\\\"\"),\n\t// \t\t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster2\"),\n\t// \t\t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\t\tTags: map[string]*string{\n\t// \t\t\t\t},\n\t// \t\t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager)},\n\t// \t\t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentLinux),\n\t// \t\t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\t\tClusterID: to.Ptr(\"2747e469-b24e-4039-8a0a-46151419523f\"),\n\t// \t\t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tManagementEndpoint: to.Ptr(\"http://myCluster2.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\t\tVMImage: to.Ptr(\"Ubuntu\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t}},\n\t// \t\t}\n}", "func (o ElastigroupIntegrationEcsOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcs) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (m *MockBuilder) Clusters() []string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Clusters\")\n\tret0, _ := ret[0].([]string)\n\treturn ret0\n}", "func (a *ClustersApiService) ListClustersExecute(r ApiListClustersRequest) (ListClustersResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ListClustersResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"ClustersApiService.ListClusters\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/spaces/{space}/clusters\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"space\"+\"}\", _neturl.PathEscape(parameterToString(r.space, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func Clusters() (clusters map[string][]string) {\n\tclusters = make(map[string][]string)\n\tif addr := AccessConsulAddr(); addr != \"\" && Region() != \"\" {\n\t\treturn getClustersFromConsul(addr, Region())\n\t}\n\tcs := Get(\"Key-ClusterMgrCluster\").(map[string]string)\n\tfor key, value := range cs {\n\t\tclusters[key] = strings.Split(value, \" \")\n\t}\n\treturn\n}", "func (r *ReconcileServiceSync) getClusterName() string {\n\tif clusterName != \"\" {\n\t\treturn clusterName\n\t}\n\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tnodes, err := r.getNodes()\n\tlogOnError(err, \"Failed to get nodes for getClusterName\")\n\tclusterName = getClusterName(nodes)\n\treturn clusterName\n}", "func (a *ClusterControllerApiService) GetClustersUsingGET(ctx _context.Context, account string, application string, clusterName string) apiGetClustersUsingGETRequest {\n\treturn apiGetClustersUsingGETRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\taccount: account,\n\t\tapplication: application,\n\t\tclusterName: clusterName,\n\t}\n}", "func (a ClustersApi) ClustersUuidGet(uuid string) (*ClusterIntentResponse, *APIResponse, error) {\n\n\tvar httpMethod = \"Get\"\n\t// create path and map variables\n\tpath := a.Configuration.BasePath + \"/clusters/{uuid}\"\n\tpath = strings.Replace(path, \"{\"+\"uuid\"+\"}\", fmt.Sprintf(\"%v\", uuid), -1)\n\n\theaderParams := make(map[string]string)\n\tqueryParams := url.Values{}\n\tformParams := make(map[string]string)\n\tvar postBody interface{}\n\tvar fileName string\n\tvar fileBytes []byte\n\t// authentication (basicAuth) required\n\n\t// http basic authentication required\n\tif a.Configuration.Username != \"\" || a.Configuration.Password != \"\" {\n\t\theaderParams[\"Authorization\"] = \"Basic \" + a.Configuration.GetBasicAuthEncodedString()\n\t}\n\t// add default headers if any\n\tfor key := range a.Configuration.DefaultHeader {\n\t\theaderParams[key] = a.Configuration.DefaultHeader[key]\n\t}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := a.Configuration.APIClient.SelectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\theaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\n\t\t\"application/json\",\n\t}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := a.Configuration.APIClient.SelectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\theaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tvar successPayload = new(ClusterIntentResponse)\n\thttpResponse, err := a.Configuration.APIClient.CallAPI(path, httpMethod, postBody, headerParams, queryParams, formParams, fileName, fileBytes)\n\tif err != nil {\n\t\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n\t}\n\terr = json.Unmarshal(httpResponse.Body(), &successPayload)\n\treturn successPayload, NewAPIResponse(httpResponse.RawResponse), err\n}", "func (client OpenShiftManagedClustersClient) Get(ctx context.Context, resourceGroupName string, resourceName string) (result v20180930preview.OpenShiftManagedCluster, err error) {\n\treq, err := client.GetPreparer(ctx, resourceGroupName, resourceName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"containerservice.OpenShiftManagedClustersClient\", \"Get\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.GetSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"containerservice.OpenShiftManagedClustersClient\", \"Get\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult, err = client.GetResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"containerservice.OpenShiftManagedClustersClient\", \"Get\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (c *MultiClusterController) GetClusterNames() []string {\n\tc.Lock()\n\tdefer c.Unlock()\n\tvar names []string\n\tfor _, cluster := range c.clusters {\n\t\tnames = append(names, cluster.GetClusterName())\n\t}\n\treturn names\n}", "func ExampleClustersClient_List() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armservicefabric.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClustersClient().List(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ClusterListResult = armservicefabric.ClusterListResult{\n\t// \tValue: []*armservicefabric.Cluster{\n\t// \t\t{\n\t// \t\t\tName: to.Ptr(\"myCluster\"),\n\t// \t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\tEtag: to.Ptr(\"W/\\\"636462502169240745\\\"\"),\n\t// \t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster\"),\n\t// \t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\tTags: map[string]*string{\n\t// \t\t\t},\n\t// \t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesDNSService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesBackupRestoreService),\n\t// \t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesResourceMonitorService)},\n\t// \t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentWindows),\n\t// \t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tAzureActiveDirectory: &armservicefabric.AzureActiveDirectory{\n\t// \t\t\t\t\t\tClientApplication: to.Ptr(\"d151ad89-4bce-4ae8-b3d1-1dc79679fa75\"),\n\t// \t\t\t\t\t\tClusterApplication: to.Ptr(\"5886372e-7bf4-4878-a497-8098aba608ae\"),\n\t// \t\t\t\t\t\tTenantID: to.Ptr(\"6abcc6a0-8666-43f1-87b8-172cf86a9f9c\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(true),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tCertificateThumbprint: to.Ptr(\"5F3660C715EBBDA31DB1FFDCF508302348DE8E7A\"),\n\t// \t\t\t\t\t\t\tIsAdmin: to.Ptr(false),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.480.9494\"),\n\t// \t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\tClusterID: to.Ptr(\"92584666-9889-4ae8-8d02-91902923d37f\"),\n\t// \t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tManagementEndpoint: to.Ptr(\"https://myCluster.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t}},\n\t// \t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\tReverseProxyCertificateCommonNames: &armservicefabric.ServerCertificateCommonNames{\n\t// \t\t\t\t\t\tCommonNames: []*armservicefabric.ServerCertificateCommonName{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCertificateCommonName: to.Ptr(\"abc.com\"),\n\t// \t\t\t\t\t\t\t\tCertificateIssuerThumbprint: to.Ptr(\"12599211F8F14C90AFA9532AD79A6F2CA1C00622\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tX509StoreName: to.Ptr(armservicefabric.StoreNameMy),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationDeltaHealthPolicies: map[string]*armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeDeltaHealthPolicy: &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeDeltaHealthPolicies: map[string]*armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\tApplicationHealthPolicies: map[string]*armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\"fabric:/myApp1\": &armservicefabric.ApplicationHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\tDefaultServiceTypeHealthPolicy: &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\tServiceTypeHealthPolicies: map[string]*armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\"myServiceType1\": &armservicefabric.ServiceTypeHealthPolicy{\n\t// \t\t\t\t\t\t\t\t\t\t\tMaxPercentUnhealthyServices: to.Ptr[int32](100),\n\t// \t\t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\tVMImage: to.Ptr(\"Windows\"),\n\t// \t\t\t\t},\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tName: to.Ptr(\"myCluster2\"),\n\t// \t\t\t\tType: to.Ptr(\"Microsoft.ServiceFabric/clusters\"),\n\t// \t\t\t\tEtag: to.Ptr(\"W/\\\"636462502164040075\\\"\"),\n\t// \t\t\t\tID: to.Ptr(\"/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups/resRg/providers/Microsoft.ServiceFabric/clusters/myCluster2\"),\n\t// \t\t\t\tLocation: to.Ptr(\"eastus\"),\n\t// \t\t\t\tTags: map[string]*string{\n\t// \t\t\t\t},\n\t// \t\t\t\tProperties: &armservicefabric.ClusterProperties{\n\t// \t\t\t\t\tAddOnFeatures: []*armservicefabric.AddOnFeatures{\n\t// \t\t\t\t\t\tto.Ptr(armservicefabric.AddOnFeaturesRepairManager)},\n\t// \t\t\t\t\t\tAvailableClusterVersions: []*armservicefabric.ClusterVersionDetails{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\t\t\tEnvironment: to.Ptr(armservicefabric.ClusterEnvironmentLinux),\n\t// \t\t\t\t\t\t\t\tSupportExpiryUTC: to.Ptr(\"2018-06-15T23:59:59.9999999\"),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tClientCertificateCommonNames: []*armservicefabric.ClientCertificateCommonName{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClientCertificateThumbprints: []*armservicefabric.ClientCertificateThumbprint{\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tClusterCodeVersion: to.Ptr(\"6.1.187.1\"),\n\t// \t\t\t\t\t\tClusterEndpoint: to.Ptr(\"https://eastus.servicefabric.azure.com\"),\n\t// \t\t\t\t\t\tClusterID: to.Ptr(\"2747e469-b24e-4039-8a0a-46151419523f\"),\n\t// \t\t\t\t\t\tClusterState: to.Ptr(armservicefabric.ClusterStateWaitingForNodes),\n\t// \t\t\t\t\t\tDiagnosticsStorageAccountConfig: &armservicefabric.DiagnosticsStorageAccountConfig{\n\t// \t\t\t\t\t\t\tBlobEndpoint: to.Ptr(\"https://diag.blob.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tProtectedAccountKeyName: to.Ptr(\"StorageAccountKey1\"),\n\t// \t\t\t\t\t\t\tQueueEndpoint: to.Ptr(\"https://diag.queue.core.windows.net/\"),\n\t// \t\t\t\t\t\t\tStorageAccountName: to.Ptr(\"diag\"),\n\t// \t\t\t\t\t\t\tTableEndpoint: to.Ptr(\"https://diag.table.core.windows.net/\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tFabricSettings: []*armservicefabric.SettingsSectionDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"UpgradeService\"),\n\t// \t\t\t\t\t\t\t\tParameters: []*armservicefabric.SettingsParameterDescription{\n\t// \t\t\t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\t\t\tName: to.Ptr(\"AppPollIntervalInSeconds\"),\n\t// \t\t\t\t\t\t\t\t\t\tValue: to.Ptr(\"60\"),\n\t// \t\t\t\t\t\t\t\t}},\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tManagementEndpoint: to.Ptr(\"http://myCluster2.eastus.cloudapp.azure.com:19080\"),\n\t// \t\t\t\t\t\tNodeTypes: []*armservicefabric.NodeTypeDescription{\n\t// \t\t\t\t\t\t\t{\n\t// \t\t\t\t\t\t\t\tName: to.Ptr(\"nt1vm\"),\n\t// \t\t\t\t\t\t\t\tApplicationPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](30000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](20000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tClientConnectionEndpointPort: to.Ptr[int32](19000),\n\t// \t\t\t\t\t\t\t\tDurabilityLevel: to.Ptr(armservicefabric.DurabilityLevelBronze),\n\t// \t\t\t\t\t\t\t\tEphemeralPorts: &armservicefabric.EndpointRangeDescription{\n\t// \t\t\t\t\t\t\t\t\tEndPort: to.Ptr[int32](64000),\n\t// \t\t\t\t\t\t\t\t\tStartPort: to.Ptr[int32](49000),\n\t// \t\t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\t\tHTTPGatewayEndpointPort: to.Ptr[int32](19007),\n\t// \t\t\t\t\t\t\t\tIsPrimary: to.Ptr(true),\n\t// \t\t\t\t\t\t\t\tVMInstanceCount: to.Ptr[int32](5),\n\t// \t\t\t\t\t\t}},\n\t// \t\t\t\t\t\tProvisioningState: to.Ptr(armservicefabric.ProvisioningStateSucceeded),\n\t// \t\t\t\t\t\tReliabilityLevel: to.Ptr(armservicefabric.ReliabilityLevelSilver),\n\t// \t\t\t\t\t\tUpgradeDescription: &armservicefabric.ClusterUpgradePolicy{\n\t// \t\t\t\t\t\t\tDeltaHealthPolicy: &armservicefabric.ClusterUpgradeDeltaHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUpgradeDomainDeltaUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tForceRestart: to.Ptr(false),\n\t// \t\t\t\t\t\t\tHealthCheckRetryTimeout: to.Ptr(\"00:05:00\"),\n\t// \t\t\t\t\t\t\tHealthCheckStableDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthCheckWaitDuration: to.Ptr(\"00:00:30\"),\n\t// \t\t\t\t\t\t\tHealthPolicy: &armservicefabric.ClusterHealthPolicy{\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyApplications: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t\tMaxPercentUnhealthyNodes: to.Ptr[int32](0),\n\t// \t\t\t\t\t\t\t},\n\t// \t\t\t\t\t\t\tUpgradeDomainTimeout: to.Ptr(\"00:15:00\"),\n\t// \t\t\t\t\t\t\tUpgradeReplicaSetCheckTimeout: to.Ptr(\"00:10:00\"),\n\t// \t\t\t\t\t\t\tUpgradeTimeout: to.Ptr(\"01:00:00\"),\n\t// \t\t\t\t\t\t},\n\t// \t\t\t\t\t\tUpgradeMode: to.Ptr(armservicefabric.UpgradeModeManual),\n\t// \t\t\t\t\t\tVMImage: to.Ptr(\"Ubuntu\"),\n\t// \t\t\t\t\t},\n\t// \t\t\t}},\n\t// \t\t}\n}", "func (m *Manager) GetClusterList() ([]Cluster, error) {\n\tnames, err := m.specManager.List()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar clusters = []Cluster{}\n\n\tfor _, name := range names {\n\t\tmetadata, err := m.meta(name)\n\t\tif err != nil && !errors.Is(perrs.Cause(err), meta.ErrValidate) &&\n\t\t\t!errors.Is(perrs.Cause(err), spec.ErrNoTiSparkMaster) {\n\t\t\treturn nil, perrs.Trace(err)\n\t\t}\n\n\t\tbase := metadata.GetBaseMeta()\n\n\t\tclusters = append(clusters, Cluster{\n\t\t\tName: name,\n\t\t\tUser: base.User,\n\t\t\tVersion: base.Version,\n\t\t\tPath: m.specManager.Path(name),\n\t\t\tPrivateKey: m.specManager.Path(name, \"ssh\", \"id_rsa\"),\n\t\t})\n\t}\n\n\treturn clusters, nil\n}", "func (o GetClustersResultOutput) ClusterIdentifiers() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetClustersResult) []string { return v.ClusterIdentifiers }).(pulumi.StringArrayOutput)\n}", "func (c *ClientIMPL) GetCluster(ctx context.Context) (resp Cluster, err error) {\n\tvar systemList []Cluster\n\tcluster := Cluster{}\n\tqp := c.APIClient().QueryParamsWithFields(&cluster)\n\n\tmajorMinorVersion, err := c.GetSoftwareMajorMinorVersion(ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"Couldn't find the array version %s\", err.Error())\n\t} else {\n\t\tif majorMinorVersion >= 3.0 {\n\t\t\tqp.Select(\"nvm_subsystem_nqn\")\n\t\t}\n\t}\n\t_, err = c.APIClient().Query(\n\t\tctx,\n\t\tRequestConfig{\n\t\t\tMethod: \"GET\",\n\t\t\tEndpoint: clusterURL,\n\t\t\tQueryParams: qp,\n\t\t},\n\t\t&systemList)\n\terr = WrapErr(err)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treturn systemList[0], err\n}", "func WorkerClustersSelector() string {\n\treturn LabelClusterOn + \"=\" + LabelClusterOnValue\n}", "func (a ClustersAPI) List() ([]httpmodels.GetResp, error) {\n\tvar clusterList = struct {\n\t\tClusters []httpmodels.GetResp `json:\"clusters,omitempty\" url:\"clusters,omitempty\"`\n\t}{}\n\n\tresp, err := a.Client.performQuery(http.MethodGet, \"/clusters/list\", nil, nil)\n\tif err != nil {\n\t\treturn clusterList.Clusters, err\n\t}\n\n\terr = json.Unmarshal(resp, &clusterList)\n\treturn clusterList.Clusters, err\n}", "func clusterName(upstreamName string) string {\n\treturn upstreamName\n}", "func getCloudNames() ([]string, error) {\n\tclouds, err := clientconfig.LoadCloudsYAML()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ti := 0\n\tcloudNames := make([]string, len(clouds))\n\tfor k := range clouds {\n\t\tcloudNames[i] = k\n\t\ti++\n\t}\n\t// Sort cloudNames so we can use sort.SearchStrings\n\tsort.Strings(cloudNames)\n\treturn cloudNames, nil\n}", "func (o ClusterManagedPrivateEndpointOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterManagedPrivateEndpoint) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func handleGetClusters(c *Context, w http.ResponseWriter, r *http.Request) {\n\tpaging, err := parsePaging(r.URL)\n\tif err != nil {\n\t\tc.Logger.WithError(err).Error(\"failed to parse paging parameters\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tfilter := &model.ClusterFilter{\n\t\tPaging: paging,\n\t}\n\n\tclusters, err := c.Store.GetClusterDTOs(filter)\n\tif err != nil {\n\t\tc.Logger.WithError(err).Error(\"failed to query clusters\")\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\tif clusters == nil {\n\t\tclusters = []*model.ClusterDTO{}\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(http.StatusOK)\n\toutputJSON(c, w, clusters)\n}", "func (a *ClustersApiService) ClusterServiceListClusters(ctx context.Context, body Servicev1ClusterQuery) (V1Clusterlist, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Post\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue V1Clusterlist\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/gitops/api/v1/clusters\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tlocalVarQueryParams.Add(\"routingId\", body.AccountIdentifier)\n\t// body params\n\tlocalVarPostBody = &body\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"x-api-key\"] = key\n\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\tif err == nil {\n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v V1Clusterlist\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\tif localVarHttpResponse.StatusCode == 0 {\n\t\t\tvar v GatewayruntimeError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (c *RancherClient) GetCluster(clusterName string) (*client.Cluster, error) {\n\tclusters, err := c.Client.ManagementClient.Cluster.List(clusterListOpts())\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error listing clusters: %s\", err)\n\t}\n\tfor _, cluster := range clusters.Data {\n\t\tif cluster.Name == clusterName {\n\t\t\treturn &cluster, nil\n\t\t}\n\t}\n\n\treturn nil, &rancherError{fmt.Sprintf(\"Could not find cluster: %s\", clusterName), notFoundErr}\n}", "func (m *RateLimitServiceConfig) GetClusterName() string {\n\tif x, ok := m.GetServiceSpecifier().(*RateLimitServiceConfig_ClusterName); ok {\n\t\treturn x.ClusterName\n\t}\n\treturn \"\"\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetClusterName() string {\n\tif o == nil || o.ClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ClusterName\n}", "func getDefaultCluster() string {\n\treturn viper.GetString(\"cluster\")\n}", "func (p provisionedServers) InitialCluster(domain string) string {\n\tmembers := make([]string, len(p))\n\tfor i, s := range p {\n\t\tmembers[i] = fmt.Sprintf(\n\t\t\t\"%v:%v\", s.EtcdMemberName(domain), s.AdvertiseIP)\n\t}\n\treturn strings.Join(members, \",\")\n}", "func GetClusterName() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\ttags, err := GetTags()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to retrieve clustername from EC2: %s\", err)\n\t}\n\n\treturn extractClusterName(tags)\n}", "func (s *ServicesTestSuite) ClusterName(t *testing.T, opts ...Option) {\n\tclusterName, err := services.NewClusterNameWithRandomID(types.ClusterNameSpecV2{\n\t\tClusterName: \"example.com\",\n\t})\n\trequire.NoError(t, err)\n\terr = s.ConfigS.SetClusterName(clusterName)\n\trequire.NoError(t, err)\n\n\tgotName, err := s.ConfigS.GetClusterName()\n\trequire.NoError(t, err)\n\tclusterName.SetResourceID(gotName.GetResourceID())\n\trequire.Empty(t, cmp.Diff(clusterName, gotName))\n\n\terr = s.ConfigS.DeleteClusterName()\n\trequire.NoError(t, err)\n\n\t_, err = s.ConfigS.GetClusterName()\n\trequire.True(t, trace.IsNotFound(err))\n\n\terr = s.ConfigS.UpsertClusterName(clusterName)\n\trequire.NoError(t, err)\n\n\tgotName, err = s.ConfigS.GetClusterName()\n\trequire.NoError(t, err)\n\tclusterName.SetResourceID(gotName.GetResourceID())\n\trequire.Empty(t, cmp.Diff(clusterName, gotName))\n}", "func (k *KubeadmBootstrapper) GetClusterLogsTo(follow bool, out io.Writer) error {\n\tvar flags []string\n\tif follow {\n\t\tflags = append(flags, \"-f\")\n\t}\n\tlogsCommand := fmt.Sprintf(\"sudo journalctl %s -u kubelet\", strings.Join(flags, \" \"))\n\n\tif follow {\n\t\tif err := k.c.CombinedOutputTo(logsCommand, out); err != nil {\n\t\t\treturn errors.Wrap(err, \"getting cluster logs\")\n\t\t}\n\t} else {\n\n\t\tlogs, err := k.c.CombinedOutput(logsCommand)\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"getting cluster logs\")\n\t\t}\n\t\tfmt.Fprint(out, logs)\n\t}\n\treturn nil\n}", "func (c starterClusterServiceOp) List(ctx context.Context) (*[]models.Cluster, *Response, error) {\n\tvar clusterList []models.Cluster\n\tgraphqlRequest := models.GraphqlRequest{\n\t\tName: \"clusters\",\n\t\tOperation: models.Query,\n\t\tInput: clusterList,\n\t\tArgs: models.ClusterListInput{\n\t\t\tProductType: models.Starter,\n\t\t},\n\t\tResponse: clusterList,\n\t}\n\treq, err := c.client.NewRequest(&graphqlRequest)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresp, err := c.client.Do(ctx, req, &clusterList)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn &clusterList, resp, err\n}", "func (c *Context) ClusterName() string {\n\treturn fmt.Sprintf(\"kind-%s\", c.name)\n}", "func ValidateAccessRequestClusterNames(cg ClusterGetter, ar types.AccessRequest) error {\n\tlocalClusterName, err := cg.GetClusterName()\n\tif err != nil {\n\t\treturn trace.Wrap(err)\n\t}\n\tvar invalidClusters []string\n\tfor _, resourceID := range ar.GetRequestedResourceIDs() {\n\t\tif resourceID.ClusterName == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif resourceID.ClusterName == localClusterName.GetClusterName() {\n\t\t\tcontinue\n\t\t}\n\t\t_, err := cg.GetRemoteCluster(resourceID.ClusterName)\n\t\tif err != nil && !trace.IsNotFound(err) {\n\t\t\treturn trace.Wrap(err, \"failed to fetch remote cluster %q\", resourceID.ClusterName)\n\t\t}\n\t\tif trace.IsNotFound(err) {\n\t\t\tinvalidClusters = append(invalidClusters, resourceID.ClusterName)\n\t\t}\n\t}\n\tif len(invalidClusters) > 0 {\n\t\treturn trace.NotFound(\"access request contains invalid or unknown cluster names: %v\",\n\t\t\tstrings.Join(invalidClusters, \", \"))\n\t}\n\treturn nil\n}", "func (o ClusterCapacityProvidersOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterCapacityProviders) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func RetrieveClusters(manifests string) cluster.Map {\n\tklog.V(1).Info(\"retrieving clusters from manifests\")\n\tclusters := cluster.Map{}\n\tdocuments := yamlutils.SplitDocuments(manifests)\n\tscheme := runtime.NewScheme()\n\tif err := clusterv1alpha1.AddToScheme(scheme); err != nil {\n\t\treturn cluster.Map{}\n\t}\n\tserializer := json.NewSerializerWithOptions(json.DefaultMetaFactory, scheme, scheme, json.SerializerOptions{Yaml: true})\n\tfor _, document := range documents {\n\t\tclusterObj := clusterv1alpha1.Cluster{}\n\t\tif _, _, err := serializer.Decode([]byte(document), nil, &clusterObj); err != nil || clusterObj.TypeMeta.Kind != \"Cluster\" {\n\t\t\tcontinue\n\t\t}\n\t\tinternalCluster, err := cluster.NewClusterFromv1alpha1(&clusterObj)\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tclusters[internalCluster.Name] = internalCluster\n\t}\n\treturn clusters\n}", "func ExampleClusterManagersClient_Get() {\n\tcred, err := azidentity.NewDefaultAzureCredential(nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to obtain a credential: %v\", err)\n\t}\n\tctx := context.Background()\n\tclientFactory, err := armnetworkcloud.NewClientFactory(\"<subscription-id>\", cred, nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to create client: %v\", err)\n\t}\n\tres, err := clientFactory.NewClusterManagersClient().Get(ctx, \"resourceGroupName\", \"clusterManagerName\", nil)\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to finish the request: %v\", err)\n\t}\n\t// You could use response here. We use blank identifier for just demo purposes.\n\t_ = res\n\t// If the HTTP response code is 200 as defined in example definition, your response structure would look as follows. Please pay attention that all the values in the output are fake values for just demo purposes.\n\t// res.ClusterManager = armnetworkcloud.ClusterManager{\n\t// \tName: to.Ptr(\"clusterManagerName\"),\n\t// \tType: to.Ptr(\"Microsoft.NetworkCloud/clusterManagers\"),\n\t// \tID: to.Ptr(\"/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/Microsoft.NetworkCloud/clusterManagers/clusterManagerName\"),\n\t// \tSystemData: &armnetworkcloud.SystemData{\n\t// \t\tCreatedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-01-22T13:27:03.008Z\"); return t}()),\n\t// \t\tCreatedBy: to.Ptr(\"identityA\"),\n\t// \t\tCreatedByType: to.Ptr(armnetworkcloud.CreatedByTypeApplication),\n\t// \t\tLastModifiedAt: to.Ptr(func() time.Time { t, _ := time.Parse(time.RFC3339Nano, \"2021-01-22T13:29:03.001Z\"); return t}()),\n\t// \t\tLastModifiedBy: to.Ptr(\"identityB\"),\n\t// \t\tLastModifiedByType: to.Ptr(armnetworkcloud.CreatedByTypeUser),\n\t// \t},\n\t// \tLocation: to.Ptr(\"location\"),\n\t// \tTags: map[string]*string{\n\t// \t\t\"key1\": to.Ptr(\"myvalue1\"),\n\t// \t\t\"key2\": to.Ptr(\"myvalue2\"),\n\t// \t},\n\t// \tProperties: &armnetworkcloud.ClusterManagerProperties{\n\t// \t\tAnalyticsWorkspaceID: to.Ptr(\"/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/microsoft.operationalInsights/workspaces/logAnalyticsWorkspaceName\"),\n\t// \t\tClusterVersions: []*armnetworkcloud.ClusterAvailableVersion{\n\t// \t\t\t{\n\t// \t\t\t\tSupportExpiryDate: to.Ptr(\"2023-04-29\"),\n\t// \t\t\t\tTargetClusterVersion: to.Ptr(\"1.0.0\"),\n\t// \t\t\t},\n\t// \t\t\t{\n\t// \t\t\t\tSupportExpiryDate: to.Ptr(\"2025-01-01\"),\n\t// \t\t\t\tTargetClusterVersion: to.Ptr(\"1.0.2\"),\n\t// \t\t}},\n\t// \t\tDetailedStatus: to.Ptr(armnetworkcloud.ClusterManagerDetailedStatusAvailable),\n\t// \t\tDetailedStatusMessage: to.Ptr(\"cluster manager is up and running\"),\n\t// \t\tFabricControllerID: to.Ptr(\"/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/Microsoft.ManagedNetworkFabric/networkFabricControllers/fabricControllerName\"),\n\t// \t\tManagedResourceGroupConfiguration: &armnetworkcloud.ManagedResourceGroupConfiguration{\n\t// \t\t\tName: to.Ptr(\"my-managed-rg\"),\n\t// \t\t\tLocation: to.Ptr(\"East US\"),\n\t// \t\t},\n\t// \t\tManagerExtendedLocation: &armnetworkcloud.ExtendedLocation{\n\t// \t\t\tName: to.Ptr(\"/subscriptions/123e4567-e89b-12d3-a456-426655440000/resourceGroups/resourceGroupName/providers/Microsoft.ExtendedLocation/customLocations/clusterManagerExtendedLocationName\"),\n\t// \t\t\tType: to.Ptr(\"CustomLocation\"),\n\t// \t\t},\n\t// \t\tProvisioningState: to.Ptr(armnetworkcloud.ClusterManagerProvisioningStateSucceeded),\n\t// \t},\n\t// }\n}", "func GetMulti(envNames []string) ([]*ChefEnvironment, util.Gerror) {\n\tvar envs []*ChefEnvironment\n\tif config.UsingDB() {\n\t\tvar err error\n\t\tenvs, err = getMultiSQL(envNames)\n\t\tif err != nil && err != sql.ErrNoRows {\n\t\t\treturn nil, util.CastErr(err)\n\t\t}\n\t} else {\n\t\tenvs = make([]*ChefEnvironment, 0, len(envNames))\n\t\tfor _, e := range envNames {\n\t\t\teo, _ := Get(e)\n\t\t\tif eo != nil {\n\t\t\t\tenvs = append(envs, eo)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn envs, nil\n}", "func (e *ECS) DescribeClusters(req *DescribeClustersReq) (*DescribeClustersResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"DescribeClusters\")\n\tif len(req.Clusters) > 0 {\n\t\taddParamsList(params, \"clusters.member\", req.Clusters)\n\t}\n\n\tresp := new(DescribeClustersResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}", "func NameArg(p cli.Params) cobra.PositionalArgs {\n\n\treturn func(cmd *cobra.Command, args []string) error {\n\t\tif len(args) == 0 {\n\t\t\treturn errNoPipeline\n\t\t}\n\n\t\tc, err := p.Clients()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tname, ns := args[0], p.Namespace()\n\t\t_, err = c.Tekton.TektonV1alpha1().Pipelines(ns).Get(name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn errInvalidPipeline\n\t\t}\n\n\t\treturn nil\n\t}\n\n}", "func (container *Container) getCommandLine(projectName string, runningPods rkt.Pods, logger *log.Logger) ([]string, error) {\n\t// generate the different components\n\tcommand := make([]string, 0)\n\n\t// get the appName\n\tappName, err := rkt.GetAppName(projectName, container.Name)\n\tif err != nil {\n\t\treturn command, err\n\t}\n\tappNameLine := fmt.Sprintf(\"--name=%s\", appName)\n\n\t// generate environment strings\n\tenvArray := make([]string, 0)\n\tfor varName, varValue := range container.Environment {\n\t\tenvArray = append(envArray, fmt.Sprintf(\"--environment=%s=%s\", varName, varValue))\n\t}\n\n\t// exec string\n\texecArray := make([]string, 0)\n\tif container.Exec != \"\" {\n\t\texec_parts := util.ShellSplit(container.Exec)\n\n\t\tif len(exec_parts) > 0 {\n\t\t\t// first prime our array\n\t\t\texecArray = append(execArray, \"--exec\")\n\t\t\t// split our string into parts\n\t\t\texecArray = append(execArray, exec_parts[0])\n\t\t}\n\t\t// if there is more than one part the rkt command requires that other compoments come after a double hyphen\n\t\tif len(exec_parts) > 1 {\n\t\t\texecArray = append(execArray, \"--\")\n\t\t\texecArray = append(execArray, exec_parts[1:]...)\n\t\t}\n\t}\n\n\t// mount strings\n\tmountArray := make([]string, 0)\n\tfor _, mount := range container.Mounts {\n\t\tmountArray = append(mountArray, mount.GenerateCommandLine()...)\n\t}\n\n\tdepIPMap, err := container.GetDepChainIPs(projectName, runningPods, logger)\n\tif err != nil {\n\t\treturn command, err\n\t}\n\n\thostsArray := make([]string, 0)\n\tfor name, IPs := range depIPMap {\n\t\tfor _, IP := range IPs {\n\t\t\thostsArray = append(hostsArray, fmt.Sprintf(\"--hosts-entry=%s=%s\", IP, name))\n\t\t}\n\t}\n\n\t// create the hostname\n\thostnameLine := fmt.Sprintf(\"--hostname=%s\", container.Name)\n\n\t// combine our command parts\n\tcommand = append(command, container.Image)\n\tcommand = append(command, hostnameLine)\n\tcommand = append(command, envArray...)\n\tcommand = append(command, mountArray...)\n\tcommand = append(command, hostsArray...)\n\tcommand = append(command, appNameLine)\n\tcommand = append(command, execArray...)\n\n\treturn command, nil\n}", "func StopCluster(c *cli.Context) error {\n\tclusters, err := getClusters(c.Bool(\"all\"), c.String(\"name\"))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx := context.Background()\n\tdocker, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())\n\tif err != nil {\n\t\treturn fmt.Errorf(\" Couldn't create docker client\\n%+v\", err)\n\t}\n\n\t// remove clusters one by one instead of appending all names to the docker command\n\t// this allows for more granular error handling and logging\n\tfor _, cluster := range clusters {\n\t\tlog.Printf(\"Stopping cluster [%s]\", cluster.name)\n\t\tif len(cluster.workers) > 0 {\n\t\t\tlog.Printf(\"...Stopping %d workers\\n\", len(cluster.workers))\n\t\t\tfor _, worker := range cluster.workers {\n\t\t\t\tif err := docker.ContainerStop(ctx, worker.ID, nil); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tlog.Println(\"...Stopping server\")\n\t\tif err := docker.ContainerStop(ctx, cluster.server.ID, nil); err != nil {\n\t\t\treturn fmt.Errorf(\" Couldn't stop server for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tlog.Infof(\"Stopped cluster [%s]\", cluster.name)\n\t}\n\n\treturn nil\n}", "func DeleteCluster(c *cli.Context) error {\n\n\tclusters, err := getClusters(c.Bool(\"all\"), c.String(\"name\"))\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(clusters) == 0 {\n\t\tif !c.IsSet(\"all\") && !c.IsSet(\"name\") {\n\t\t\treturn fmt.Errorf(\"No cluster with name '%s' found (You can add `--all` and `--name <CLUSTER-NAME>` to delete other clusters)\", c.String(\"name\"))\n\t\t}\n\t\treturn fmt.Errorf(\"No cluster(s) found\")\n\t}\n\n\t// remove clusters one by one instead of appending all names to the docker command\n\t// this allows for more granular error handling and logging\n\tfor _, cluster := range clusters {\n\t\tlog.Printf(\"Removing cluster [%s]\", cluster.name)\n\t\tif len(cluster.workers) > 0 {\n\t\t\t// TODO: this could be done in goroutines\n\t\t\tlog.Printf(\"...Removing %d workers\\n\", len(cluster.workers))\n\t\t\tfor _, worker := range cluster.workers {\n\t\t\t\tif err := removeContainer(worker.ID); err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tdeleteClusterDir(cluster.name)\n\t\tlog.Println(\"...Removing server\")\n\t\tif err := removeContainer(cluster.server.ID); err != nil {\n\t\t\treturn fmt.Errorf(\" Couldn't remove server for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tif err := disconnectRegistryFromNetwork(cluster.name, c.IsSet(\"keep-registry-volume\")); err != nil {\n\t\t\tlog.Warningf(\"Couldn't disconnect Registry from network %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tif c.IsSet(\"prune\") {\n\t\t\t// disconnect any other container that is connected to the k3d network\n\t\t\tnid, err := getClusterNetwork(cluster.name)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"Couldn't get the network for cluster %q\\n%+v\", cluster.name, err)\n\t\t\t}\n\t\t\tcids, err := getContainersInNetwork(nid)\n\t\t\tif err != nil {\n\t\t\t\tlog.Warningf(\"Couldn't get the list of containers connected to network %q\\n%+v\", nid, err)\n\t\t\t}\n\t\t\tfor _, cid := range cids {\n\t\t\t\terr := disconnectContainerFromNetwork(cid, nid)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Warningf(\"Couldn't disconnect container %q from network %q\", cid, nid)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tlog.Printf(\"...%q has been forced to disconnect from %q's network\", cid, cluster.name)\n\t\t\t}\n\t\t}\n\n\t\tif err := deleteClusterNetwork(cluster.name); err != nil {\n\t\t\tlog.Warningf(\"Couldn't delete cluster network for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tlog.Println(\"...Removing docker image volume\")\n\t\tif err := deleteImageVolume(cluster.name); err != nil {\n\t\t\tlog.Warningf(\"Couldn't delete image docker volume for cluster %s\\n%+v\", cluster.name, err)\n\t\t}\n\n\t\tlog.Infof(\"Removed cluster [%s]\", cluster.name)\n\t}\n\n\treturn nil\n}", "func ListClusters(c *cli.Context) error {\n\tif err := printClusters(); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (d *Dao) OverlordClusters(c context.Context, zone, appid string) (ocs []*model.OverlordCluster, err error) {\n\tvar res struct {\n\t\tData []*model.OverlordApiserver `json:\"grouped_clusters\"`\n\t}\n\tif err = d.client.RESTfulGet(c, apiserverURI, \"\", nil, &res, appid); err != nil {\n\t\tlog.Error(\"overlord cluster url(%s) appid(%s) error(%v)\", apiserverURI, appid, err)\n\t\treturn\n\t}\nGETALL:\n\tfor _, oa := range res.Data {\n\t\tif zone == \"\" || oa.Group == zone {\n\t\t\tfor _, oc := range oa.Clusters {\n\t\t\t\tcluster := &model.OverlordCluster{\n\t\t\t\t\tName: oc.Name,\n\t\t\t\t\tType: oc.Type,\n\t\t\t\t\tZone: zone,\n\t\t\t\t\tHashMethod: \"fnv1a_64\",\n\t\t\t\t\tHashDistribution: \"ketama\",\n\t\t\t\t\tHashTag: \"{}\",\n\t\t\t\t\tListenProto: \"tcp\",\n\t\t\t\t\tListenAddr: net.JoinHostPort(\"0.0.0.0\", strconv.Itoa(oc.FrontEndPort)),\n\t\t\t\t\tDailTimeout: 1000,\n\t\t\t\t\tReadTimeout: 1000,\n\t\t\t\t\tWriteTimeout: 1000,\n\t\t\t\t\tNodeConn: 2,\n\t\t\t\t\tPingFailLimit: 3,\n\t\t\t\t\tPingAutoEject: true,\n\t\t\t\t}\n\t\t\t\tfor _, oci := range oc.Instances {\n\t\t\t\t\tif oc.Type == \"redis_cluster\" && oci.Role != \"master\" {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\ton := &model.OverlordNode{\n\t\t\t\t\t\tAlias: oci.Alias,\n\t\t\t\t\t\tAddr: net.JoinHostPort(oci.IP, strconv.Itoa(oci.Port)),\n\t\t\t\t\t\tWeight: oci.Weight,\n\t\t\t\t\t}\n\t\t\t\t\tcluster.Nodes = append(cluster.Nodes, on)\n\t\t\t\t}\n\t\t\t\tocs = append(ocs, cluster)\n\t\t\t}\n\t\t}\n\t}\n\tif len(ocs) == 0 && zone != \"\" {\n\t\tzone = \"\"\n\t\tgoto GETALL\n\t}\n\treturn\n}", "func (a *Client) ListClusters(params *ListClustersParams, authInfo runtime.ClientAuthInfoWriter) (*ListClustersOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewListClustersParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"ListClusters\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/api/v1/clusters\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &ListClustersReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*ListClustersOK), nil\n\n}", "func (adm Admin) ListClusters() (string, error) {\n\tvar clusters []string\n\n\tchildren, err := adm.zkClient.Children(\"/\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range children {\n\t\tif ok, err := adm.isClusterSetup(cluster); ok && err == nil {\n\t\t\tclusters = append(clusters, cluster)\n\t\t}\n\t}\n\n\tvar buffer bytes.Buffer\n\tbuffer.WriteString(\"Existing clusters: \\n\")\n\n\tfor _, cluster := range clusters {\n\t\tbuffer.WriteString(\" \" + cluster + \"\\n\")\n\t}\n\treturn buffer.String(), nil\n}", "func (c *SetClusterConfigCommand) CommandName() string {\n\treturn \"etcd:setClusterConfig\"\n}", "func K3sServerArgs() []string {\n\tresults, err := K3sCmd(\"kubectl\", \"get\", \"nodes\", \"-o\", `jsonpath='{.items[0].metadata.annotations.k3s\\.io/node-args}'`)\n\tif err != nil {\n\t\treturn nil\n\t}\n\tres := strings.ReplaceAll(results, \"'\", \"\")\n\tvar args []string\n\tif err := json.Unmarshal([]byte(res), &args); err != nil {\n\t\tlogrus.Error(err)\n\t\treturn nil\n\t}\n\treturn args\n}", "func generateClusterName() string {\n\treturn string(uuid.NewUUID())\n}", "func (a *ClustersApiService) ListClusters(ctx _context.Context, space string) ApiListClustersRequest {\n\treturn ApiListClustersRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tspace: space,\n\t}\n}", "func selectedClusters(objMeta *metav1.ObjectMeta, selector func(map[string]string, map[string]string) (bool, error), clusters []*federationapi.Cluster) ([]*federationapi.Cluster, []*federationapi.Cluster, error) {\n\tselectedClusters := []*federationapi.Cluster{}\n\tunselectedClusters := []*federationapi.Cluster{}\n\n\tfor _, cluster := range clusters {\n\t\tsend, err := selector(cluster.Labels, objMeta.Annotations)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t} else if !send {\n\t\t\tunselectedClusters = append(unselectedClusters, cluster)\n\t\t} else {\n\t\t\tselectedClusters = append(selectedClusters, cluster)\n\t\t}\n\t}\n\treturn selectedClusters, unselectedClusters, nil\n}", "func (us *ClusterStore) GetAllByName(name string) ([]model.Cluster, error) {\n\tvar clusters []model.Cluster\n\tif err := us.db.\n\t\tPreload(clause.Associations).\n\t\tWhere(&model.Cluster{ClusterName: name}).\n\t\tFind(&clusters).\n\t\tError; err != nil {\n\t\tif errors.Is(err, gorm.ErrRecordNotFound) {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn nil, err\n\t}\n\treturn clusters, nil\n}" ]
[ "0.63905376", "0.6215127", "0.61287344", "0.5982906", "0.5893215", "0.57639354", "0.55499226", "0.55045515", "0.5501147", "0.54514647", "0.5423453", "0.54203576", "0.53890306", "0.53613067", "0.53399837", "0.5328997", "0.5296841", "0.5290517", "0.5251998", "0.5164787", "0.5163924", "0.5156697", "0.51519614", "0.5145142", "0.5138548", "0.5124054", "0.51015323", "0.5073584", "0.5053089", "0.5036385", "0.5033521", "0.5019526", "0.5007854", "0.49948624", "0.4987096", "0.49707422", "0.4961253", "0.49498245", "0.49396348", "0.49166408", "0.49166378", "0.49034128", "0.4888056", "0.4886776", "0.4866727", "0.486485", "0.48636034", "0.48588464", "0.4855311", "0.4833897", "0.48250324", "0.48137006", "0.47967747", "0.47889575", "0.47865206", "0.47814304", "0.47727653", "0.47646922", "0.47557664", "0.47519815", "0.47432017", "0.473299", "0.47315332", "0.4730726", "0.47232744", "0.4721357", "0.47201443", "0.4715593", "0.4712701", "0.46984485", "0.46961173", "0.46932358", "0.46891493", "0.46862882", "0.46791318", "0.46749684", "0.46593028", "0.4658498", "0.46573743", "0.4654573", "0.4649767", "0.46388954", "0.4633425", "0.4632286", "0.4623115", "0.46183535", "0.4600755", "0.45997348", "0.45950657", "0.45935538", "0.45922384", "0.4583876", "0.45748016", "0.45697424", "0.4567946", "0.4567402", "0.45669943", "0.45652953", "0.4562371", "0.45568755" ]
0.8905924
0
GetOneClusterName retrive from the CLI (cobra) arguments one cluster name which could be valid or not
func GetOneClusterName(cmd *cobra.Command, args []string, validate bool) (clusterName string, err error) { if len(args) == 0 { return "", UserErrorf("requires a cluster name") } if len(args) != 1 { return "", UserErrorf("accepts 1 cluster name, received %d. %v", len(args), args) } if len(args[0]) == 0 { return "", UserErrorf("cluster name cannot be empty") } if validate { return kluster.ValidClusterName(args[0]) } return args[0], nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetClusterNameOrDie() string {\n\tc, err := clientcmd.LoadFromFile(framework.TestContext.KubeConfig)\n\tframework.ExpectNoError(err, \"failed to load kubeconfig from file\")\n\n\tauthInfo := c.AuthInfos[c.Contexts[c.CurrentContext].AuthInfo]\n\n\tfor i, v := range authInfo.Exec.Args {\n\t\t// aws-iam-authenticator token\n\t\tif v == \"-i\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t\t// aws eks get-token\n\t\tif v == \"--cluster-name\" {\n\t\t\treturn authInfo.Exec.Args[i+1]\n\t\t}\n\t}\n\tframework.Fail(\"failed to get EKS cluster name\")\n\treturn \"\"\n}", "func GetClusterName(self *C.PyObject, args *C.PyObject) *C.PyObject {\n\tclusterName := clustername.GetClusterName()\n\n\tcStr := C.CString(clusterName)\n\tpyStr := C.PyString_FromString(cStr)\n\tC.free(unsafe.Pointer(cStr))\n\treturn pyStr\n}", "func bootstrapClusterName() string {\n\t// This constitutes a \"bootstrap\" invocation of \"kubectl\", we can't use the configuration because we are actually creating it\n\tcmd := exec.Command(\"kubectl\", \"config\", \"view\", \"--minify\", \"--output\", \"jsonpath={.clusters[0].name}\")\n\tif stdout, err := cmd.Output(); err == nil {\n\t\tif clusterName := strings.TrimSpace(string(stdout)); clusterName != \"\" {\n\t\t\treturn clusterName\n\t\t}\n\t}\n\treturn \"default\"\n}", "func GetMultipleClustersName(cmd *cobra.Command, args []string) ([]string, error) {\n\tif len(args) == 0 {\n\t\treturn nil, UserErrorf(\"requires a cluster name\")\n\t}\n\treturn args, nil\n}", "func GetClusterName(executionSpaceName string) (string, error) {\n\tif !strings.HasPrefix(executionSpaceName, ExecutionSpacePrefix) {\n\t\treturn \"\", fmt.Errorf(\"the execution space name is in wrong format\")\n\t}\n\treturn strings.TrimPrefix(executionSpaceName, ExecutionSpacePrefix), nil\n}", "func (config *DirectClientConfig) getClusterName() (string, bool) {\n\tif config.overrides != nil && len(config.overrides.Context.Cluster) != 0 {\n\t\treturn config.overrides.Context.Cluster, true\n\t}\n\tcontext, _ := config.getContext()\n\treturn context.Cluster, false\n}", "func getClusterName(nodes []corev1.Node) string {\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tif len(nodes) == 0 {\n\t\treturn \"\"\n\t}\n\n\tnode := nodes[0]\n\tif node.Labels[clusterNameLabel] != \"\" {\n\t\treturn node.Labels[clusterNameLabel]\n\t}\n\tif node.ClusterName != \"\" {\n\t\treturn node.ClusterName\n\t}\n\n\t// Hack for clusters that don't have ClusterName as a label on the nodes (pre-1.15?)\n\tif _, hasLabel := node.Labels[gkeNodePoolLabel]; hasLabel {\n\t\t// Split/TrimPrefix:\n\t\t// gke-mycluster-1-node-pool-1-b486c6b7-chm7\n\t\t// pre^clusterName^postfix_____________^node-hash\n\t\tprefix := \"gke-\"\n\t\tpostfix := \"-\" + node.Labels[gkeNodePoolLabel]\n\t\tclusterName := strings.Split(strings.TrimPrefix(node.Name, prefix), postfix)[0]\n\t\tlog.Info(\"getClusterName: used a hack to determine the clusterName from hostname\", \"hostname\", node.Name, \"clustername\", clusterName)\n\t\treturn clusterName\n\t}\n\tlog.Error(fmt.Errorf(\"Failed to getClusterName from %#v\", node), \"getClusterName failure\")\n\tpanic(\"ClusterName could not be determined\")\n}", "func getClusterName(utils detectorUtils) (string, error) {\n\tresp, err := utils.fetchString(\"GET\", k8sSvcURL+cwConfigmapPath)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: %w\", err)\n\t}\n\n\t// parse JSON object returned from HTTP request\n\tvar respmap map[string]json.RawMessage\n\terr = json.Unmarshal([]byte(resp), &respmap)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\tvar d data\n\terr = json.Unmarshal(respmap[\"data\"], &d)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"getClusterName() error: cannot parse JSON: %w\", err)\n\t}\n\n\tclusterName := d.ClusterName\n\n\treturn clusterName, nil\n}", "func (r *ReconcileServiceSync) getClusterName() string {\n\tif clusterName != \"\" {\n\t\treturn clusterName\n\t}\n\n\tif os.Getenv(\"CLUSTER_NAME\") != \"\" {\n\t\tclusterName = os.Getenv(\"CLUSTER_NAME\")\n\t\treturn clusterName\n\t}\n\n\tnodes, err := r.getNodes()\n\tlogOnError(err, \"Failed to get nodes for getClusterName\")\n\tclusterName = getClusterName(nodes)\n\treturn clusterName\n}", "func (o OceanOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Ocean) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func getDefaultCluster() string {\n\treturn viper.GetString(\"cluster\")\n}", "func (o AppV2Output) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetClusterNameOk() (*string, bool) {\n\tif o == nil || o.ClusterName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ClusterName, true\n}", "func getClusterNameFromZone(ctx context.Context, availabilityZone string) string {\n\tclusterName := \"\"\n\tclusterComputeResourceList, _, err := getClusterName(ctx, &e2eVSphere)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tnimbusGeneratedVcPwd := GetAndExpectStringEnvVar(vcUIPwd)\n\tcmd := fmt.Sprintf(\"dcli +username %s +password %s +skip +show com vmware \"+\n\t\t\"vcenter consumptiondomains zones cluster associations get --zone \"+\n\t\t\"%s\", adminUser, nimbusGeneratedVcPwd, availabilityZone)\n\tvcAddress := e2eVSphere.Config.Global.VCenterHostname + \":\" + sshdPort\n\tframework.Logf(\"Invoking command %v on vCenter host %v\", cmd, vcAddress)\n\tresult, err := fssh.SSH(cmd, vcAddress, framework.TestContext.Provider)\n\tframework.Logf(\"result: %v\", result)\n\tclusterId := strings.Split(result.Stdout, \"- \")[1]\n\tclusterID := strings.TrimSpace(clusterId)\n\tframework.Logf(\"clusterId: %v\", clusterID)\n\tfmt.Print(clusterId)\n\tif err != nil || result.Code != 0 {\n\t\tfssh.LogResult(result)\n\t\tframework.Failf(\"couldn't execute command: %s on vCenter host: %v\", cmd, err)\n\t}\n\tfor _, cluster := range clusterComputeResourceList {\n\t\tclusterMoId := cluster.Reference().Value\n\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\tframework.Logf(\"cluster MOID %v\", clusterMoId)\n\t\tif clusterMoId == clusterID {\n\t\t\tframework.Logf(\"Found matching cluster domain!!\")\n\t\t\tclusterName = cluster.Name()\n\t\t\tbreak\n\t\t}\n\t}\n\tframework.Logf(\"cluster on zone is: %s\", clusterName)\n\tif clusterName == \"\" {\n\t\tframework.Failf(\"couldn't find cluster on zone %s\", availabilityZone)\n\t}\n\treturn clusterName\n\n}", "func (s *ServicesTestSuite) ClusterName(t *testing.T, opts ...Option) {\n\tclusterName, err := services.NewClusterNameWithRandomID(types.ClusterNameSpecV2{\n\t\tClusterName: \"example.com\",\n\t})\n\trequire.NoError(t, err)\n\terr = s.ConfigS.SetClusterName(clusterName)\n\trequire.NoError(t, err)\n\n\tgotName, err := s.ConfigS.GetClusterName()\n\trequire.NoError(t, err)\n\tclusterName.SetResourceID(gotName.GetResourceID())\n\trequire.Empty(t, cmp.Diff(clusterName, gotName))\n\n\terr = s.ConfigS.DeleteClusterName()\n\trequire.NoError(t, err)\n\n\t_, err = s.ConfigS.GetClusterName()\n\trequire.True(t, trace.IsNotFound(err))\n\n\terr = s.ConfigS.UpsertClusterName(clusterName)\n\trequire.NoError(t, err)\n\n\tgotName, err = s.ConfigS.GetClusterName()\n\trequire.NoError(t, err)\n\tclusterName.SetResourceID(gotName.GetResourceID())\n\trequire.Empty(t, cmp.Diff(clusterName, gotName))\n}", "func getKubeClusterName(args []string, teleportClusterName string) (string, error) {\n\tkubeconfigLocation, selectedContext := extractKubeConfigAndContext(args)\n\tif selectedContext == \"\" {\n\t\tkubeName, err := kubeconfig.SelectedKubeCluster(kubeconfigLocation, teleportClusterName)\n\t\treturn kubeName, trace.Wrap(err)\n\t}\n\tkc, err := kubeconfig.Load(kubeconfigLocation)\n\tif err != nil {\n\t\treturn \"\", trace.Wrap(err)\n\t}\n\tkubeName := kubeconfig.KubeClusterFromContext(selectedContext, kc.Contexts[selectedContext], teleportClusterName)\n\tif kubeName == \"\" {\n\t\treturn \"\", trace.BadParameter(\"selected context %q does not belong to Teleport cluster %q\", selectedContext, teleportClusterName)\n\t}\n\treturn kubeName, nil\n}", "func (m *RateLimitServiceConfig) GetClusterName() string {\n\tif x, ok := m.GetServiceSpecifier().(*RateLimitServiceConfig_ClusterName); ok {\n\t\treturn x.ClusterName\n\t}\n\treturn \"\"\n}", "func (c *GCEModelContext) SafeClusterName() string {\n\treturn gce.SafeClusterName(c.Cluster.ObjectMeta.Name)\n}", "func (o *NiatelemetryNexusDashboardsAllOf) GetClusterName() string {\n\tif o == nil || o.ClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ClusterName\n}", "func Cluster(context *cli.Context) error {\n\tregion := context.String(flags.RegionFlag)\n\tif err := fieldEmpty(region, flags.RegionFlag); err != nil {\n\t\treturn err\n\t}\n\tclusterProfileName := context.String(flags.ConfigNameFlag)\n\tif err := fieldEmpty(clusterProfileName, flags.ConfigNameFlag); err != nil {\n\t\treturn err\n\t}\n\tcluster := context.String(flags.ClusterFlag)\n\tif err := fieldEmpty(cluster, flags.ClusterFlag); err != nil {\n\t\treturn err\n\t}\n\n\tlaunchType := context.String(flags.DefaultLaunchTypeFlag)\n\tif err := config.ValidateLaunchType(launchType); err != nil {\n\t\treturn err\n\t}\n\n\tcfnStackName := context.String(flags.CFNStackNameFlag)\n\tcomposeServiceNamePrefix := context.String(flags.ComposeServiceNamePrefixFlag)\n\n\tclusterConfig := &config.Cluster{\n\t\tCluster: cluster,\n\t\tRegion: region,\n\t\tCFNStackName: cfnStackName,\n\t\tComposeServiceNamePrefix: composeServiceNamePrefix,\n\t\tDefaultLaunchType: launchType,\n\t}\n\n\trdwr, err := config.NewReadWriter()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"Error saving cluster configuration\")\n\t}\n\tif err = rdwr.SaveCluster(clusterProfileName, clusterConfig); err != nil {\n\t\treturn errors.Wrap(err, \"Error saving cluster configuration\")\n\t}\n\n\tlogrus.Infof(\"Saved ECS CLI cluster configuration %s.\", clusterProfileName)\n\treturn nil\n}", "func (o *VirtualizationIweClusterAllOf) GetClusterNameOk() (*string, bool) {\n\tif o == nil || o.ClusterName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.ClusterName, true\n}", "func (o ElastigroupIntegrationEcsOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ElastigroupIntegrationEcs) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func (o GetClustersClusterOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.ClusterName }).(pulumi.StringOutput)\n}", "func cmdCluster(c *cli.Context, subCmd string) string {\n\troute := \"_cluster/\"\n\turl := c.GlobalString(\"baseurl\")\n\n\tvar arg string\n\tswitch subCmd {\n\tcase \"health\":\n\t\targ = \"health\"\n\tcase \"state\":\n\t\targ = \"state\"\n\tdefault:\n\t\targ = \"\"\n\t}\n\treturn url + route + arg\n}", "func (o ClusterManagedPrivateEndpointOutput) ClusterName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterManagedPrivateEndpoint) pulumi.StringOutput { return v.ClusterName }).(pulumi.StringOutput)\n}", "func getClusterNameLabel() string {\n\tkey := fmt.Sprintf(\"%s/cluster-name\", getCAPIGroup())\n\treturn key\n}", "func generateClusterName() string {\n\treturn string(uuid.NewUUID())\n}", "func (c *ClusterInfoResolver) ClusterName() *string {\n\treturn c.clusterName\n}", "func (c *Context) ClusterName() string {\n\treturn fmt.Sprintf(\"kind-%s\", c.name)\n}", "func fetchCluster(c *gin.Context) string {\n\tconst key = \"cluster\"\n\n\tswitch {\n\tcase len(c.Param(key)) > 0:\n\t\treturn c.Param(key)\n\tcase len(c.Query(key)) > 0:\n\t\treturn c.Query(key)\n\tcase len(c.PostForm(key)) > 0:\n\t\treturn c.PostForm(key)\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func TestMinimalLongClusterName(t *testing.T) {\n\tnewIntegrationTest(\"this.is.truly.a.really.really.long.cluster-name.minimal.example.com\", \"minimal-longclustername\").\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}", "func clusterName(upstreamName string) string {\n\treturn upstreamName\n}", "func clusterNameFromARN(ecsClusterARN string) string {\n\ta, err := arn.Parse(ecsClusterARN)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\n\tresourceParts := strings.Split(a.Resource, \"/\")\n\tif len(resourceParts) < 2 || resourceParts[0] != \"cluster\" {\n\t\treturn \"\"\n\t}\n\n\treturn resourceParts[1]\n}", "func ValidateClusterNameFormat(name string) error {\n\tif matched, _ := regexp.MatchString(clusterNameRegex, name); !matched {\n\t\treturn errors.Errorf(\"Cluster name format is not valid: '%s'. \"+\n\t\t\t\"Name must consist of lower-case letters, numbers and hyphens. \"+\n\t\t\t\"It must start with a letter and end with a letter or number.\", name)\n\t}\n\treturn nil\n}", "func (config *DirectClientConfig) getCluster() (clientcmdapi.Cluster, error) {\n\tclusterInfos := config.config.Clusters\n\tclusterInfoName, required := config.getClusterName()\n\n\tmergedClusterInfo := clientcmdapi.NewCluster()\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterDefaults, mergo.WithOverride)\n\t}\n\tif configClusterInfo, exists := clusterInfos[clusterInfoName]; exists {\n\t\tmergo.Merge(mergedClusterInfo, configClusterInfo, mergo.WithOverride)\n\t} else if required {\n\t\treturn clientcmdapi.Cluster{}, fmt.Errorf(\"cluster %q does not exist\", clusterInfoName)\n\t}\n\tif config.overrides != nil {\n\t\tmergo.Merge(mergedClusterInfo, config.overrides.ClusterInfo, mergo.WithOverride)\n\t}\n\n\t// * An override of --insecure-skip-tls-verify=true and no accompanying CA/CA data should clear already-set CA/CA data\n\t// otherwise, a kubeconfig containing a CA reference would return an error that \"CA and insecure-skip-tls-verify couldn't both be set\".\n\t// * An override of --certificate-authority should also override TLS skip settings and CA data, otherwise existing CA data will take precedence.\n\tif config.overrides != nil {\n\t\tcaLen := len(config.overrides.ClusterInfo.CertificateAuthority)\n\t\tcaDataLen := len(config.overrides.ClusterInfo.CertificateAuthorityData)\n\t\tif config.overrides.ClusterInfo.InsecureSkipTLSVerify || caLen > 0 || caDataLen > 0 {\n\t\t\tmergedClusterInfo.InsecureSkipTLSVerify = config.overrides.ClusterInfo.InsecureSkipTLSVerify\n\t\t\tmergedClusterInfo.CertificateAuthority = config.overrides.ClusterInfo.CertificateAuthority\n\t\t\tmergedClusterInfo.CertificateAuthorityData = config.overrides.ClusterInfo.CertificateAuthorityData\n\t\t}\n\n\t\t// if the --tls-server-name has been set in overrides, use that value.\n\t\t// if the --server has been set in overrides, then use the value of --tls-server-name specified on the CLI too. This gives the property\n\t\t// that setting a --server will effectively clear the KUBECONFIG value of tls-server-name if it is specified on the command line which is\n\t\t// usually correct.\n\t\tif config.overrides.ClusterInfo.TLSServerName != \"\" || config.overrides.ClusterInfo.Server != \"\" {\n\t\t\tmergedClusterInfo.TLSServerName = config.overrides.ClusterInfo.TLSServerName\n\t\t}\n\t}\n\n\treturn *mergedClusterInfo, nil\n}", "func TestClusterNameDigit(t *testing.T) {\n\tnewIntegrationTest(\"123.example.com\", \"digit\").\n\t\twithOIDCDiscovery().\n\t\twithServiceAccountRole(\"myserviceaccount.default\", false).\n\t\twithServiceAccountRole(\"myotherserviceaccount.myapp\", true).\n\t\twithAddons(\n\t\t\tawsEBSCSIAddon,\n\t\t\tdnsControllerAddon,\n\t\t\tawsCCMAddon,\n\t\t).\n\t\trunTestTerraformAWS(t)\n}", "func (t *Tester) GetRandomClusterName() (string, error) {\n\tmanagedClusterList, err := t.ClusterClient.ClusterV1().ManagedClusters().List(context.TODO(), metav1.ListOptions{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, managedCluster := range managedClusterList.Items {\n\t\tclusterName := managedCluster.Name\n\t\tif !strings.HasPrefix(clusterName, \"e2e-\") {\n\t\t\treturn clusterName, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"there is no managedCluster with the random name\")\n}", "func GetClusterAddress(cluster string) (string, string, error) {\n\tvar clusteraddress string\n\tfor i := range config.Cluster {\n\t\tif cluster == config.Cluster[i].Name {\n\t\t\tclusteraddress = config.Cluster[i].Address\n\t\t\tclusteraddress = fmt.Sprintf(\"%s%s\", clusteraddress, config.Cluster[i].ProtocolVersion)\n\t\t\tbreak\n\t\t}\n\t}\n\tif clusteraddress == \"\" {\n\t\ttext := fmt.Sprintf(\"Cluster %s not found in configuration\", cluster)\n\t\tfmt.Printf(\"%s\\n\", text)\n\t\treturn \"\", \"\", errors.New(text)\n\t}\n\tlog.Println(\"Chosen cluster: \", cluster, clusteraddress)\n\treturn clusteraddress, cluster, nil\n}", "func (m *GetClusterRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o UsageLimitOutput) ClusterIdentifier() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *UsageLimit) pulumi.StringOutput { return v.ClusterIdentifier }).(pulumi.StringOutput)\n}", "func GetMetaClusterNameText(ctx context.Context, hostname string) string {\n\treturn \"\"\n}", "func (o *VirtualizationIweClusterAllOf) GetClusterName() string {\n\tif o == nil || o.ClusterName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.ClusterName\n}", "func (o StorageClusterStatusOutput) ClusterName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v StorageClusterStatus) *string { return v.ClusterName }).(pulumi.StringPtrOutput)\n}", "func (r *Cluster) ClusterName() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"clusterName\"])\n}", "func (c *Controller) getDeployCluster(hr *appv1.HelmRequest) string {\n\tif hr.Spec.ClusterName != \"\" {\n\t\treturn hr.Spec.ClusterName\n\t}\n\n\treturn hr.ClusterName\n}", "func (m *Info) GetClusterName() string {\n\tif m.ec2Tags != nil {\n\t\treturn m.ec2Tags.getClusterName()\n\t}\n\n\treturn \"\"\n}", "func GetMetaClusterNameText(ctx context.Context, hostname string) string {\n\tcompliantClusterName, initialClusterName := getRFC1123CompliantClusterName(ctx, hostname)\n\tif compliantClusterName != initialClusterName {\n\t\treturn fmt.Sprintf(\"%s (original name: %s)\", compliantClusterName, initialClusterName)\n\t}\n\treturn compliantClusterName\n}", "func GetClusterNameByID(client *rancher.Client, clusterID string) (string, error) {\n\tclusterList, err := client.Management.Cluster.List(&types.ListOpts{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range clusterList.Data {\n\t\tif cluster.ID == clusterID {\n\t\t\treturn cluster.Name, nil\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func (o ElastigroupIntegrationEcsPtrOutput) ClusterName() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ElastigroupIntegrationEcs) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.ClusterName\n\t}).(pulumi.StringPtrOutput)\n}", "func validCluster(clusterName string, env string) bool {\n\tif env == \"prod\" || env == \"uat\" {\n\t\treturn strings.Contains(clusterName, \"prod.kops\")\n\t}\n\treturn !strings.Contains(clusterName, \"prod.kops\")\n}", "func ValidateCluster(cluster string) error {\n\tnames, err := GetClusterNames()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, name := range names {\n\t\tif name == cluster {\n\t\t\treturn nil\n\t\t}\n\t}\n\treturn fmt.Errorf(\"Cluster not found: %s\", cluster)\n}", "func TranslateClusterName(cluster string) string {\n\t// Use a hash to fit the resource name restriction on GCE subject to RFC1035\n\treturn fmt.Sprintf(\"robotest-%x\", Hash(cluster))\n}", "func getClusterNameForMultiVC(ctx context.Context, vs *multiVCvSphere,\n\tclientIndex int) ([]*object.ClusterComputeResource,\n\t*VsanClient, error) {\n\n\tvar vsanHealthClient *VsanClient\n\tvar err error\n\tc := newClientForMultiVC(ctx, vs)\n\n\tdatacenter := strings.Split(multiVCe2eVSphere.multivcConfig.Global.Datacenters, \",\")\n\n\tfor i, client := range c {\n\t\tif clientIndex == i {\n\t\t\tvsanHealthClient, err = newVsanHealthSvcClient(ctx, client.Client)\n\t\t\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\t\t}\n\t}\n\n\tfinder := find.NewFinder(vsanHealthClient.vim25Client, false)\n\tdc, err := finder.Datacenter(ctx, datacenter[0])\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tfinder.SetDatacenter(dc)\n\n\tclusterComputeResource, err := finder.ClusterComputeResourceList(ctx, \"*\")\n\tframework.Logf(\"clusterComputeResource %v\", clusterComputeResource)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\treturn clusterComputeResource, vsanHealthClient, err\n}", "func (m *SetMasterAuthRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (m *CreateNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func NewCluster(ctx *pulumi.Context,\n\tname string, args *ClusterArgs, opts ...pulumi.ResourceOpt) (*Cluster, error) {\n\tinputs := make(map[string]interface{})\n\tif args == nil {\n\t\tinputs[\"applyImmediately\"] = nil\n\t\tinputs[\"availabilityZones\"] = nil\n\t\tinputs[\"backupRetentionPeriod\"] = nil\n\t\tinputs[\"clusterIdentifier\"] = nil\n\t\tinputs[\"clusterIdentifierPrefix\"] = nil\n\t\tinputs[\"engine\"] = nil\n\t\tinputs[\"engineVersion\"] = nil\n\t\tinputs[\"finalSnapshotIdentifier\"] = nil\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = nil\n\t\tinputs[\"iamRoles\"] = nil\n\t\tinputs[\"kmsKeyArn\"] = nil\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = nil\n\t\tinputs[\"neptuneSubnetGroupName\"] = nil\n\t\tinputs[\"port\"] = nil\n\t\tinputs[\"preferredBackupWindow\"] = nil\n\t\tinputs[\"preferredMaintenanceWindow\"] = nil\n\t\tinputs[\"replicationSourceIdentifier\"] = nil\n\t\tinputs[\"skipFinalSnapshot\"] = nil\n\t\tinputs[\"snapshotIdentifier\"] = nil\n\t\tinputs[\"storageEncrypted\"] = nil\n\t\tinputs[\"tags\"] = nil\n\t\tinputs[\"vpcSecurityGroupIds\"] = nil\n\t} else {\n\t\tinputs[\"applyImmediately\"] = args.ApplyImmediately\n\t\tinputs[\"availabilityZones\"] = args.AvailabilityZones\n\t\tinputs[\"backupRetentionPeriod\"] = args.BackupRetentionPeriod\n\t\tinputs[\"clusterIdentifier\"] = args.ClusterIdentifier\n\t\tinputs[\"clusterIdentifierPrefix\"] = args.ClusterIdentifierPrefix\n\t\tinputs[\"engine\"] = args.Engine\n\t\tinputs[\"engineVersion\"] = args.EngineVersion\n\t\tinputs[\"finalSnapshotIdentifier\"] = args.FinalSnapshotIdentifier\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = args.IamDatabaseAuthenticationEnabled\n\t\tinputs[\"iamRoles\"] = args.IamRoles\n\t\tinputs[\"kmsKeyArn\"] = args.KmsKeyArn\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = args.NeptuneClusterParameterGroupName\n\t\tinputs[\"neptuneSubnetGroupName\"] = args.NeptuneSubnetGroupName\n\t\tinputs[\"port\"] = args.Port\n\t\tinputs[\"preferredBackupWindow\"] = args.PreferredBackupWindow\n\t\tinputs[\"preferredMaintenanceWindow\"] = args.PreferredMaintenanceWindow\n\t\tinputs[\"replicationSourceIdentifier\"] = args.ReplicationSourceIdentifier\n\t\tinputs[\"skipFinalSnapshot\"] = args.SkipFinalSnapshot\n\t\tinputs[\"snapshotIdentifier\"] = args.SnapshotIdentifier\n\t\tinputs[\"storageEncrypted\"] = args.StorageEncrypted\n\t\tinputs[\"tags\"] = args.Tags\n\t\tinputs[\"vpcSecurityGroupIds\"] = args.VpcSecurityGroupIds\n\t}\n\tinputs[\"arn\"] = nil\n\tinputs[\"clusterMembers\"] = nil\n\tinputs[\"clusterResourceId\"] = nil\n\tinputs[\"endpoint\"] = nil\n\tinputs[\"hostedZoneId\"] = nil\n\tinputs[\"readerEndpoint\"] = nil\n\ts, err := ctx.RegisterResource(\"aws:neptune/cluster:Cluster\", name, true, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{s: s}, nil\n}", "func (o GetClustersClusterOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GetClustersCluster) string { return v.ClusterId }).(pulumi.StringOutput)\n}", "func TestMinimalGCELongClusterName(t *testing.T) {\n\tnewIntegrationTest(\"minimal-gce-with-a-very-very-very-very-very-long-name.example.com\", \"minimal_gce_longclustername\").\n\t\twithAddons(\n\t\t\tdnsControllerAddon,\n\t\t\tgcpCCMAddon,\n\t\t\tgcpPDCSIAddon,\n\t\t).\n\t\trunTestTerraformGCE(t)\n}", "func (m *UpdateMasterRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o AppProfileSingleClusterRoutingOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AppProfileSingleClusterRouting) string { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (o DatabaseReplicaOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DatabaseReplica) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (o ClusterOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (m *GetNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func GetClusterIDByName(client *rancher.Client, clusterName string) (string, error) {\n\tclusterList, err := client.Management.Cluster.List(&types.ListOpts{})\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, cluster := range clusterList.Data {\n\t\tif cluster.Name == clusterName {\n\t\t\treturn cluster.ID, nil\n\t\t}\n\t}\n\n\treturn \"\", nil\n}", "func CreateRKE1Cluster(client *rancher.Client, rke1Cluster *management.Cluster) (*management.Cluster, error) {\n\tcluster, err := client.Management.Cluster.Create(rke1Cluster)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient, err = client.ReLogin()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.Session.RegisterCleanupFunc(func() error {\n\t\tadminClient, err := rancher.NewClient(client.RancherConfig.AdminToken, client.Session)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclusterResp, err := client.Management.Cluster.ByID(cluster.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twatchInterface, err := adminClient.GetManagementWatchInterface(management.ClusterType, metav1.ListOptions{\n\t\t\tFieldSelector: \"metadata.name=\" + clusterResp.ID,\n\t\t\tTimeoutSeconds: &defaults.WatchTimeoutSeconds,\n\t\t})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tclient, err = client.ReLogin()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\terr = client.Management.Cluster.Delete(clusterResp)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\treturn wait.WatchWait(watchInterface, func(event watch.Event) (ready bool, err error) {\n\t\t\tif event.Type == watch.Error {\n\t\t\t\treturn false, fmt.Errorf(\"there was an error deleting cluster\")\n\t\t\t} else if event.Type == watch.Deleted {\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\treturn false, nil\n\t\t})\n\t})\n\n\treturn cluster, nil\n}", "func (o AppV2Output) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *AppV2) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (metadata *metadataImpl) GetCurrentClusterName() string {\n\treturn metadata.currentClusterName\n}", "func machineContainerName(cluster, machine string) string {\n\tif strings.HasPrefix(machine, cluster) {\n\t\treturn machine\n\t}\n\treturn fmt.Sprintf(\"%s-%s\", cluster, machine)\n}", "func (s *ClusterScope) ClusterName() string {\n\treturn s.Cluster.Name\n}", "func QualifiedClusterNameFor(configMap *v1.ConfigMap) (string, error) {\n\tif !LooksLikeACassandraConfigMap(configMap) {\n\t\treturn \"\", fmt.Errorf(\"configMap name %s does not follow the naming convention for a cluster\", configMap.Name)\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", configMap.Namespace, strings.Replace(configMap.Name, \"-config\", \"\", -1)), nil\n}", "func (o KubernetesAddonOutput) ClusterId() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *KubernetesAddon) pulumi.StringOutput { return v.ClusterId }).(pulumi.StringOutput)\n}", "func (s *Server) GetTenantName(reqCrt *x509.Certificate) (string, error) {\n\tvcLst := &tenancyv1alpha1.VirtualclusterList{}\n\tif err := s.superMasterClient.List(context.TODO(), vcLst, &client.ListOptions{}); err != nil {\n\t\treturn \"\", errors.Wrap(err, \"fail to list Virtualclusters on the super master\")\n\t}\n\n\treqSig := reqCrt.Signature\n\n\tfor _, vc := range vcLst.Items {\n\t\tsigB64, exist := vc.Annotations[constants.AnnoX509SignatureBase64]\n\t\tif !exist {\n\t\t\tcontinue\n\t\t}\n\t\tsig, err := base64.StdEncoding.DecodeString(sigB64)\n\t\tif err != nil {\n\t\t\treturn \"\", errors.Wrap(err, \"fail to decode signature content from the base64 format\")\n\t\t}\n\t\tif bytes.Equal(reqSig, sig) {\n\t\t\tklog.V(4).Infof(\"received request from vc %s\", vc.GetName())\n\t\t\treturn conversion.ToClusterKey(&vc), nil\n\t\t}\n\t}\n\treturn \"\", errors.New(\"there exist no virtualcluster that matches the signature in the request\")\n}", "func CreateCluster(c *cli.Context) error {\n\n\t// On Error delete the cluster. If there createCluster() encounter any error,\n\t// call this function to remove all resources allocated for the cluster so far\n\t// so that they don't linger around.\n\tdeleteCluster := func() {\n\t\tlog.Println(\"ERROR: Cluster creation failed, rolling back...\")\n\t\tif err := DeleteCluster(c); err != nil {\n\t\t\tlog.Printf(\"Error: Failed to delete cluster %s\", c.String(\"name\"))\n\t\t}\n\t}\n\n\t// validate --wait flag\n\tif c.IsSet(\"wait\") && c.Int(\"wait\") < 0 {\n\t\tlog.Fatalf(\"Negative value for '--wait' not allowed (set '%d')\", c.Int(\"wait\"))\n\t}\n\n\t/**********************\n\t *\t\t\t\t\t\t\t\t\t\t*\n\t *\t\tCONFIGURATION\t\t*\n\t * vvvvvvvvvvvvvvvvvv *\n\t **********************/\n\n\t/*\n\t * --name, -n\n\t * Name of the cluster\n\t */\n\n\t// ensure that it's a valid hostname, because it will be part of container names\n\tif err := CheckClusterName(c.String(\"name\")); err != nil {\n\t\treturn err\n\t}\n\n\t// check if the cluster name is already taken\n\tif cluster, err := getClusters(false, c.String(\"name\")); err != nil {\n\t\treturn err\n\t} else if len(cluster) != 0 {\n\t\t// A cluster exists with the same name. Return with an error.\n\t\treturn fmt.Errorf(\" Cluster %s already exists\", c.String(\"name\"))\n\t}\n\n\t/*\n\t * --image, -i\n\t * The k3s image used for the k3d node containers\n\t */\n\t// define image\n\timage := c.String(\"image\")\n\t// if no registry was provided, use the default docker.io\n\tif len(strings.Split(image, \"/\")) <= 2 {\n\t\timage = fmt.Sprintf(\"%s/%s\", DefaultRegistry, image)\n\t}\n\n\t/*\n\t * Cluster network\n\t * For proper communication, all k3d node containers have to be in the same docker network\n\t */\n\t// create cluster network\n\tnetworkID, err := createClusterNetwork(c.String(\"name\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.Printf(\"Created cluster network with ID %s\", networkID)\n\n\t/*\n\t * --env, -e\n\t * Environment variables that will be passed into the k3d node containers\n\t */\n\t// environment variables\n\tenv := []string{\"K3S_KUBECONFIG_OUTPUT=/output/kubeconfig.yaml\"}\n\tenv = append(env, c.StringSlice(\"env\")...)\n\tenv = append(env, fmt.Sprintf(\"K3S_CLUSTER_SECRET=%s\", GenerateRandomString(20)))\n\n\t/*\n\t * --label, -l\n\t * Docker container labels that will be added to the k3d node containers\n\t */\n\t// labels\n\tlabelmap, err := mapNodesToLabelSpecs(c.StringSlice(\"label\"), GetAllContainerNames(c.String(\"name\"), DefaultServerCount, c.Int(\"workers\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t/*\n\t * Arguments passed on to the k3s server and agent, will be filled later\n\t */\n\tk3AgentArgs := []string{}\n\tk3sServerArgs := []string{}\n\n\t/*\n\t * --api-port, -a\n\t * The port that will be used by the k3s API-Server\n\t * It will be mapped to localhost or to another hist interface, if specified\n\t * If another host is chosen, we also add a tls-san argument for the server to allow connections\n\t */\n\tapiPort, err := parseAPIPort(c.String(\"api-port\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\tk3sServerArgs = append(k3sServerArgs, \"--https-listen-port\", apiPort.Port)\n\n\t// When the 'host' is not provided by --api-port, try to fill it using Docker Machine's IP address.\n\tif apiPort.Host == \"\" {\n\t\tapiPort.Host, err = getDockerMachineIp()\n\t\t// IP address is the same as the host\n\t\tapiPort.HostIP = apiPort.Host\n\t\t// In case of error, Log a warning message, and continue on. Since it more likely caused by a miss configured\n\t\t// DOCKER_MACHINE_NAME environment variable.\n\t\tif err != nil {\n\t\t\tlog.Warning(\"Failed to get docker machine IP address, ignoring the DOCKER_MACHINE_NAME environment variable setting.\")\n\t\t}\n\t}\n\n\t// Add TLS SAN for non default host name\n\tif apiPort.Host != \"\" {\n\t\tlog.Printf(\"Add TLS SAN for %s\", apiPort.Host)\n\t\tk3sServerArgs = append(k3sServerArgs, \"--tls-san\", apiPort.Host)\n\t}\n\n\t/*\n\t * --server-arg, -x\n\t * Add user-supplied arguments for the k3s server\n\t */\n\tif c.IsSet(\"server-arg\") || c.IsSet(\"x\") {\n\t\tk3sServerArgs = append(k3sServerArgs, c.StringSlice(\"server-arg\")...)\n\t}\n\n\t/*\n\t * --agent-arg\n\t * Add user-supplied arguments for the k3s agent\n\t */\n\tif c.IsSet(\"agent-arg\") {\n\t\tif c.Int(\"workers\") < 1 {\n\t\t\tlog.Warnln(\"--agent-arg supplied, but --workers is 0, so no agents will be created\")\n\t\t}\n\t\tk3AgentArgs = append(k3AgentArgs, c.StringSlice(\"agent-arg\")...)\n\t}\n\n\t/*\n\t * --port, -p, --publish, --add-port\n\t * List of ports, that should be mapped from some or all k3d node containers to the host system (or other interface)\n\t */\n\t// new port map\n\tportmap, err := mapNodesToPortSpecs(c.StringSlice(\"port\"), GetAllContainerNames(c.String(\"name\"), DefaultServerCount, c.Int(\"workers\")))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t/*\n\t * Image Volume\n\t * A docker volume that will be shared by every k3d node container in the cluster.\n\t * This volume will be used for the `import-image` command.\n\t * On it, all node containers can access the image tarball.\n\t */\n\t// create a docker volume for sharing image tarballs with the cluster\n\timageVolume, err := createImageVolume(c.String(\"name\"))\n\tlog.Println(\"Created docker volume \", imageVolume.Name)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t/*\n\t * --volume, -v\n\t * List of volumes: host directory mounts for some or all k3d node containers in the cluster\n\t */\n\tvolumes := c.StringSlice(\"volume\")\n\n\tvolumesSpec, err := NewVolumes(volumes)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvolumesSpec.DefaultVolumes = append(volumesSpec.DefaultVolumes, fmt.Sprintf(\"%s:/images\", imageVolume.Name))\n\n\t/*\n\t * --registry-file\n\t * check if there is a registries file\n\t */\n\tregistriesFile := \"\"\n\tif c.IsSet(\"registries-file\") {\n\t\tregistriesFile = c.String(\"registries-file\")\n\t\tif !fileExists(registriesFile) {\n\t\t\tlog.Fatalf(\"registries-file %q does not exists\", registriesFile)\n\t\t}\n\t} else {\n\t\tregistriesFile, err = getGlobalRegistriesConfFilename()\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tif !fileExists(registriesFile) {\n\t\t\t// if the default registries file does not exists, go ahead but do not try to load it\n\t\t\tregistriesFile = \"\"\n\t\t}\n\t}\n\n\t/*\n\t * clusterSpec\n\t * Defines, with which specifications, the cluster and the nodes inside should be created\n\t */\n\tclusterSpec := &ClusterSpec{\n\t\tAgentArgs: k3AgentArgs,\n\t\tAPIPort: *apiPort,\n\t\tAutoRestart: c.Bool(\"auto-restart\"),\n\t\tClusterName: c.String(\"name\"),\n\t\tEnv: env,\n\t\tNodeToLabelSpecMap: labelmap,\n\t\tImage: image,\n\t\tNodeToPortSpecMap: portmap,\n\t\tPortAutoOffset: c.Int(\"port-auto-offset\"),\n\t\tRegistriesFile: registriesFile,\n\t\tRegistryEnabled: c.Bool(\"enable-registry\"),\n\t\tRegistryCacheEnabled: c.Bool(\"enable-registry-cache\"),\n\t\tRegistryName: c.String(\"registry-name\"),\n\t\tRegistryPort: c.Int(\"registry-port\"),\n\t\tRegistryVolume: c.String(\"registry-volume\"),\n\t\tServerArgs: k3sServerArgs,\n\t\tVolumes: volumesSpec,\n\t}\n\n\t/******************\n\t *\t\t\t\t\t\t\t\t*\n\t *\t\tCREATION\t\t*\n\t * vvvvvvvvvvvvvv\t*\n\t ******************/\n\n\tlog.Printf(\"Creating cluster [%s]\", c.String(\"name\"))\n\n\t/*\n\t * Cluster Directory\n\t */\n\t// create the directory where we will put the kubeconfig file by default (when running `k3d get-config`)\n\tcreateClusterDir(c.String(\"name\"))\n\n\t/* (1)\n\t * Registry (optional)\n\t * Create the (optional) registry container\n\t */\n\tvar registryNameExists *dnsNameCheck\n\tif clusterSpec.RegistryEnabled {\n\t\tregistryNameExists = newAsyncNameExists(clusterSpec.RegistryName, 1*time.Second)\n\t\tif _, err = createRegistry(*clusterSpec); err != nil {\n\t\t\tdeleteCluster()\n\t\t\treturn err\n\t\t}\n\t}\n\n\t/* (2)\n\t * Server\n\t * Create the server node container\n\t */\n\tserverContainerID, err := createServer(clusterSpec)\n\tif err != nil {\n\t\tdeleteCluster()\n\t\treturn err\n\t}\n\n\t/* (2.1)\n\t * Wait\n\t * Wait for k3s server to be done initializing, if wanted\n\t */\n\t// We're simply scanning the container logs for a line that tells us that everything's up and running\n\t// TODO: also wait for worker nodes\n\tif c.IsSet(\"wait\") {\n\t\tif err := waitForContainerLogMessage(serverContainerID, \"Wrote kubeconfig\", c.Int(\"wait\")); err != nil {\n\t\t\tdeleteCluster()\n\t\t\treturn fmt.Errorf(\"ERROR: failed while waiting for server to come up\\n%+v\", err)\n\t\t}\n\t}\n\n\t/* (3)\n\t * Workers\n\t * Create the worker node containers\n\t */\n\t// TODO: do this concurrently in different goroutines\n\tif c.Int(\"workers\") > 0 {\n\t\tlog.Printf(\"Booting %s workers for cluster %s\", strconv.Itoa(c.Int(\"workers\")), c.String(\"name\"))\n\t\tfor i := 0; i < c.Int(\"workers\"); i++ {\n\t\t\tworkerID, err := createWorker(clusterSpec, i)\n\t\t\tif err != nil {\n\t\t\t\tdeleteCluster()\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tlog.Printf(\"Created worker with ID %s\\n\", workerID)\n\t\t}\n\t}\n\n\t/* (4)\n\t * Done\n\t * Finished creating resources.\n\t */\n\tlog.Printf(\"SUCCESS: created cluster [%s]\", c.String(\"name\"))\n\n\tif clusterSpec.RegistryEnabled {\n\t\tlog.Printf(\"A local registry has been started as %s:%d\", clusterSpec.RegistryName, clusterSpec.RegistryPort)\n\n\t\texists, err := registryNameExists.Exists()\n\t\tif !exists || err != nil {\n\t\t\tlog.Printf(\"Make sure you have an alias in your /etc/hosts file like '127.0.0.1 %s'\", clusterSpec.RegistryName)\n\t\t}\n\t}\n\n\tlog.Printf(`You can now use the cluster with:\n\nexport KUBECONFIG=\"$(%s get-kubeconfig --name='%s')\"\nkubectl cluster-info`, os.Args[0], c.String(\"name\"))\n\n\treturn nil\n}", "func (m *RollbackNodePoolUpgradeRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (s *BasePlSqlParserListener) ExitCluster_name(ctx *Cluster_nameContext) {}", "func ValidateClusterName(clusterName string) error {\n\tif len(clusterName) == 0 {\n\t\treturn errors.New(\"clusterName must not be empty\")\n\t}\n\tif strings.Contains(clusterName, \"/\") || strings.Contains(clusterName, \".\") ||\n\t\tstrings.Contains(clusterName, \"=\") || strings.Contains(clusterName, \"'\") {\n\t\treturn errors.New(\"clusterName contains illegal characters: /, ., =, or '\")\n\t}\n\treturn nil\n}", "func newCluster() *cobra.Command {\n\tvar cluster *[]string\n\n\tcmd := &cobra.Command{\n\t\tUse: \"cluster\",\n\t\tShort: \"display cluster nodes.\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclient, err := getLeader(*cluster)\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't connect to cluster leader\")\n\t\t\t}\n\t\t\tdefer client.Close()\n\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), time.Second)\n\t\t\tdefer cancel()\n\n\t\t\tvar leader *dqclient.NodeInfo\n\t\t\tvar nodes []dqclient.NodeInfo\n\t\t\tif leader, err = client.Leader(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get leader\")\n\t\t\t}\n\n\t\t\tif nodes, err = client.Cluster(ctx); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"can't get cluster\")\n\t\t\t}\n\n\t\t\tfmt.Printf(\"ID \\tLeader \\tAddress\\n\")\n\t\t\tfor _, node := range nodes {\n\t\t\t\tfmt.Printf(\"%d \\t%v \\t%s\\n\", node.ID, node.ID == leader.ID, node.Address)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\tcluster = flags.StringSliceP(\"cluster\", \"c\", defaultCluster, \"addresses of existing cluster nodes\")\n\n\treturn cmd\n}", "func (m *SetLegacyAbacRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (m *SetNetworkPolicyRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func GetClusterId() string {\n\treturn axClusterId\n}", "func (o ClusterOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Cluster) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (m *MockManagedClusterScope) ClusterName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClusterName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (a *AdminClient) ClusterID(ctx context.Context) (clusterID string, err error) {\n\terr = a.verifyClient()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tresponseChan := make(chan *C.char, 1)\n\n\tgo func() {\n\t\tresponseChan <- C.rd_kafka_clusterid(a.handle.rk, cTimeoutFromContext(ctx))\n\t}()\n\n\tselect {\n\tcase <-ctx.Done():\n\t\tif cClusterID := <-responseChan; cClusterID != nil {\n\t\t\tC.rd_kafka_mem_free(a.handle.rk, unsafe.Pointer(cClusterID))\n\t\t}\n\t\treturn \"\", ctx.Err()\n\n\tcase cClusterID := <-responseChan:\n\t\tif cClusterID == nil { // C timeout\n\t\t\t<-ctx.Done()\n\t\t\treturn \"\", ctx.Err()\n\t\t}\n\t\tdefer C.rd_kafka_mem_free(a.handle.rk, unsafe.Pointer(cClusterID))\n\t\treturn C.GoString(cClusterID), nil\n\t}\n}", "func (q *QueryResolver) Cluster(ctx context.Context, args *clusterArgs) (*ClusterInfoResolver, error) {\n\tgrpcAPI := q.Env.VizierClusterInfo\n\tres, err := grpcAPI.GetClusterInfo(ctx, &cloudpb.GetClusterInfoRequest{\n\t\tID: utils.ProtoFromUUIDStrOrNil(string(args.ID)),\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(res.Clusters) == 0 {\n\t\treturn nil, errors.New(\"org has no matching clusters\")\n\t}\n\tif len(res.Clusters) != 1 {\n\t\treturn nil, errors.New(\"got multiple matching clusters for ID\")\n\t}\n\treturn clusterInfoToResolver(res.Clusters[0])\n}", "func (o BareMetalAdminClusterOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *BareMetalAdminCluster) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o PartnerOutput) ClusterIdentifier() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Partner) pulumi.StringOutput { return v.ClusterIdentifier }).(pulumi.StringOutput)\n}", "func (m *UpdateNodePoolRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func GetClusterName() (string, error) {\n\tif !config.IsCloudProviderEnabled(CloudProviderName) {\n\t\treturn \"\", fmt.Errorf(\"cloud provider is disabled by configuration\")\n\t}\n\ttags, err := GetTags()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"unable to retrieve clustername from EC2: %s\", err)\n\t}\n\n\treturn extractClusterName(tags)\n}", "func (m *SetNodePoolManagementRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (o *ProjectDeploymentRuleResponse) GetCluster() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Cluster\n}", "func (c *ClusterInfoResolver) PrettyClusterName() *string {\n\treturn c.prettyClusterName\n}", "func GetCluster(ctx *pulumi.Context,\n\tname string, id pulumi.ID, state *ClusterState, opts ...pulumi.ResourceOpt) (*Cluster, error) {\n\tinputs := make(map[string]interface{})\n\tif state != nil {\n\t\tinputs[\"applyImmediately\"] = state.ApplyImmediately\n\t\tinputs[\"arn\"] = state.Arn\n\t\tinputs[\"availabilityZones\"] = state.AvailabilityZones\n\t\tinputs[\"backupRetentionPeriod\"] = state.BackupRetentionPeriod\n\t\tinputs[\"clusterIdentifier\"] = state.ClusterIdentifier\n\t\tinputs[\"clusterIdentifierPrefix\"] = state.ClusterIdentifierPrefix\n\t\tinputs[\"clusterMembers\"] = state.ClusterMembers\n\t\tinputs[\"clusterResourceId\"] = state.ClusterResourceId\n\t\tinputs[\"endpoint\"] = state.Endpoint\n\t\tinputs[\"engine\"] = state.Engine\n\t\tinputs[\"engineVersion\"] = state.EngineVersion\n\t\tinputs[\"finalSnapshotIdentifier\"] = state.FinalSnapshotIdentifier\n\t\tinputs[\"hostedZoneId\"] = state.HostedZoneId\n\t\tinputs[\"iamDatabaseAuthenticationEnabled\"] = state.IamDatabaseAuthenticationEnabled\n\t\tinputs[\"iamRoles\"] = state.IamRoles\n\t\tinputs[\"kmsKeyArn\"] = state.KmsKeyArn\n\t\tinputs[\"neptuneClusterParameterGroupName\"] = state.NeptuneClusterParameterGroupName\n\t\tinputs[\"neptuneSubnetGroupName\"] = state.NeptuneSubnetGroupName\n\t\tinputs[\"port\"] = state.Port\n\t\tinputs[\"preferredBackupWindow\"] = state.PreferredBackupWindow\n\t\tinputs[\"preferredMaintenanceWindow\"] = state.PreferredMaintenanceWindow\n\t\tinputs[\"readerEndpoint\"] = state.ReaderEndpoint\n\t\tinputs[\"replicationSourceIdentifier\"] = state.ReplicationSourceIdentifier\n\t\tinputs[\"skipFinalSnapshot\"] = state.SkipFinalSnapshot\n\t\tinputs[\"snapshotIdentifier\"] = state.SnapshotIdentifier\n\t\tinputs[\"storageEncrypted\"] = state.StorageEncrypted\n\t\tinputs[\"tags\"] = state.Tags\n\t\tinputs[\"vpcSecurityGroupIds\"] = state.VpcSecurityGroupIds\n\t}\n\ts, err := ctx.ReadResource(\"aws:neptune/cluster:Cluster\", name, id, inputs, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Cluster{s: s}, nil\n}", "func (m *MockClusterScoper) ClusterName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClusterName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (cb *clientBase) GetCluster() string {\n\treturn cb.cluster\n}", "func (o ClusterInstanceOutput) ClusterIdentifier() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ClusterInstance) pulumi.StringOutput { return v.ClusterIdentifier }).(pulumi.StringOutput)\n}", "func (m *CompleteIPRotationRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func (saIdentityRequest *ServiceAccountIdentityRequest) GetClusterID() string {\n\treturn saIdentityRequest.ClusterID\n}", "func (m *MockManagedClusterScoper) ClusterName() string {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ClusterName\")\n\tret0, _ := ret[0].(string)\n\treturn ret0\n}", "func (m *StartIPRotationRequest) GetClusterId() string {\n\tif m != nil {\n\t\treturn m.ClusterId\n\t}\n\treturn \"\"\n}", "func getHost(rancherClient *client.RancherClient, cluster *client.Cluster) string {\n\tu, _ := url.Parse(rancherClient.GetOpts().Url)\n\tu.Path = \"/k8s/clusters/\"\n\tclusterOverrideURL := u.String()\n\tif clusterOverrideURL != \"\" {\n\t\treturn clusterOverrideURL + cluster.Id\n\t}\n\tif strings.HasSuffix(cluster.K8sClientConfig.Address, \"443\") {\n\t\treturn \"https://\" + cluster.K8sClientConfig.Address\n\t}\n\treturn \"http://\" + cluster.K8sClientConfig.Address\n}" ]
[ "0.6778686", "0.6565807", "0.63791955", "0.6376339", "0.6252303", "0.6182027", "0.6154467", "0.6083232", "0.60200775", "0.59961", "0.5979632", "0.59744346", "0.59714293", "0.59470075", "0.5914465", "0.5825949", "0.57707316", "0.57299614", "0.57193047", "0.57002264", "0.5700057", "0.5690134", "0.5677853", "0.567308", "0.56710154", "0.567094", "0.5627707", "0.56233466", "0.56086105", "0.55910206", "0.5579096", "0.55787826", "0.5552229", "0.55195796", "0.5487997", "0.54358405", "0.54346055", "0.54274017", "0.54263216", "0.542302", "0.54177237", "0.5413867", "0.540513", "0.5384431", "0.5354973", "0.5352627", "0.5344725", "0.5340589", "0.53304744", "0.53273886", "0.53258604", "0.53229326", "0.53192043", "0.531266", "0.5289878", "0.5271501", "0.52690375", "0.52687144", "0.5262454", "0.5248459", "0.5228346", "0.52278185", "0.5227558", "0.52258843", "0.52240247", "0.5213187", "0.5208592", "0.5203433", "0.51983654", "0.51881254", "0.51634127", "0.5157733", "0.5153745", "0.51485527", "0.51405984", "0.51390123", "0.51276666", "0.5125706", "0.5123933", "0.51175076", "0.51172227", "0.5109106", "0.5109006", "0.51088417", "0.51075995", "0.5103358", "0.5093819", "0.50929487", "0.50920534", "0.5089204", "0.50874233", "0.50818264", "0.5072403", "0.50705343", "0.5068455", "0.5061116", "0.5049502", "0.504464", "0.5043294", "0.5038962" ]
0.86150014
0
InitGetOpts get the `init` command parameters from the cobra commands and arguments
func InitGetOpts(cmd *cobra.Command, args []string) (opts *InitOpts, warns []string, err error) { warns = make([]string, 0) // Validate cluster name clusterName, err := GetOneClusterName(cmd, args, true) if err != nil { if clusterName == "" { return nil, warns, err } warns = append(warns, fmt.Sprintf("%s. They were replaced and the new cluster name is: %q", err, clusterName)) } // The `--update` flag will be deprecated and replaced by the `update` command update := false updateFlag := cmd.Flags().Lookup("update") if updateFlag != nil { update = updateFlag.Value.String() == "true" } // Validate platform (required unless it's an update) platform := cmd.Flags().Lookup("platform").Value.String() if len(platform) == 0 && !update { return nil, warns, UserErrorf("platform is required") } platform = strings.ToLower(platform) // The `--path` and `--format` flags are only part of the `kubekit` binary var path string if pathFlag := cmd.Flags().Lookup("path"); pathFlag != nil { path = pathFlag.Value.String() } var format string if formatFlag := cmd.Flags().Lookup("format"); formatFlag != nil { format = formatFlag.Value.String() } // TODO: templateName will be used later to create a cluster from a template var templateName string if templateNameFlag := cmd.Flags().Lookup("template"); templateNameFlag != nil { templateName = templateNameFlag.Value.String() } // Variables: varsStr := cmd.Flags().Lookup("var").Value.String() variables, warnV, errV := GetVariables(varsStr) if errV != nil { return nil, warns, err } if len(warnV) != 0 { warns = append(warns, warnV...) } // Credentials: creds := GetCredentials(platform, cmd) return &InitOpts{ ClusterName: clusterName, Platform: platform, Path: path, Format: format, Variables: variables, Credentials: creds, TemplateName: templateName, Update: update, }, warns, nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func CmdInit(c *cli.Context) error {\n\n\topt := InitOpt{\n\t\tConfig: Config{\n\t\t\tPackage: c.GlobalString(PackageFlag),\n\t\t\tHomebrew: c.GlobalString(HomebrewFlag),\n\t\t},\n\t\tUserName: c.Args().First(),\n\t\tRepository: c.Args().Get(1),\n\t\tDescription: c.String(\"desc\"),\n\t}\n\treturn cmdInit(&opt)\n\n}", "func argsInit() {\n\tArgs = make([]string, 0, 0)\n\tArgs = append(Args, os.Args...)\n\tExecFile = options.GetExecFileByPid(os.Getpid())\n\t// default opt Parser\n\t// do not include ExecFile\n\topts = options.NewOptParser(Args[1:])\n\tArgLine = options.ArgsToSpLine(Args)\n\tArgFullLine = options.CleanArgLine(os.Args[0] + \" \" + opts.String())\n\t//\n}", "func Init() {\n\targs, errs := options.Parse(optMap)\n\n\tif len(errs) != 0 {\n\t\tfmtc.Println(\"Arguments parsing errors:\")\n\n\t\tfor _, err := range errs {\n\t\t\tfmtc.Printf(\" %s\\n\", err.Error())\n\t\t}\n\n\t\tos.Exit(1)\n\t}\n\n\tif options.Has(OPT_COMPLETION) {\n\t\tgenCompletion()\n\t}\n\n\tif options.GetB(OPT_NO_COLOR) {\n\t\tfmtc.DisableColors = true\n\t}\n\n\tif options.GetB(OPT_VER) {\n\t\tshowAbout()\n\t\treturn\n\t}\n\n\tif options.GetB(OPT_HELP) || len(args) == 0 {\n\t\tshowUsage()\n\t\treturn\n\t}\n\n\tswitch len(args) {\n\tcase 1:\n\t\tprocess(args[0], \"\")\n\tcase 2:\n\t\tprocess(args[0], args[1])\n\tdefault:\n\t\tshowUsage()\n\t}\n}", "func (co *ConfigOption) Init(cmd *cobra.Command) error {\n\t// Bind the command line and environment variable name\n\t// Unless overriden, default to a transform like tls-key -> TLS_KEY\n\tif co.EnvVar == \"\" {\n\t\tco.EnvVar = strutils.KebabToConstantCase(co.Name)\n\t}\n\t// Initialise and bind the persistent flags\n\treturn co.setFlag(cmd)\n}", "func (c *Client) GetInitParams(ctx context.Context, req *pdpb.GetInitParamsReq) (*pdpb.GetInitParamsRsp, error) {\n\trsp, err := c.proxyRPC(ctx,\n\t\treq,\n\t\tfunc() {\n\t\t\treq.From = c.name\n\t\t\treq.ID = c.seq\n\t\t},\n\t\tfunc(cc context.Context) (interface{}, error) {\n\t\t\treturn c.pd.GetInitParams(cc, req, grpc.FailFast(true))\n\t\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn rsp.(*pdpb.GetInitParamsRsp), nil\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\tRootCmd.PersistentFlags().StringP(\"config\", \"\", \"\", \"config file to use\")\n\tRootCmd.PersistentFlags().BoolP(\"verbose\", \"v\", false, \"verbose output\")\n\n\tRootCmd.Flags().StringSlice(\"kafka.brokers\", []string{\"localhost:9092\"}, \"kafka brokers address\")\n\tRootCmd.Flags().String(\"metrics.addr\", \"127.0.0.1:9100\", \"metrics address\")\n\n\tif err := viper.BindPFlags(RootCmd.PersistentFlags()); err != nil {\n\t\tlog.WithError(err).Error(\"Could not bind persistent flags\")\n\t}\n\n\tif err := viper.BindPFlags(RootCmd.Flags()); err != nil {\n\t\tlog.WithError(err).Error(\"Could not bind flags\")\n\t}\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\trootCmd.PersistentFlags().BoolVar(&loglevel, \"debug\", false, \"Set log level to Debug\") //nolint\n\trootCmd.PersistentFlags().StringVar(&jaegerurl, \"jaegerurl\", \"\", \"Set jaegger collector endpoint\")\n\trootCmd.PersistentFlags().BoolVar(&version, \"version\", false, \"version\")\n\n\trootCmd.Flags().BoolP(\"toggle\", \"t\", false, \"Help message for toggle\")\n\terr := viper.BindPFlag(\"jaegerurl\", rootCmd.PersistentFlags().Lookup(\"jaegerurl\"))\n\tif err != nil {\n\t\tlog.Error().Msgf(\"Error binding jaegerurl value: %v\", err.Error())\n\t}\n\tviper.SetDefault(\"jaegerurl\", \"\")\n\n}", "func init() {\n\tprepareOptionsFromCommandline(&configFromInit)\n\tparseConfigFromEnvironment(&configFromInit)\n}", "func (s *sysCC) InitArgs() [][]byte {\n\treturn s.initArgs\n}", "func (cmd *GetUserListCmd) Init() {\n\tcmd.cmd = \"getuserlist\"\n\tcmd.flagSet = flag.NewFlagSet(cmd.cmd, flag.ExitOnError)\n}", "func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []string) error {\n\to.Context = ctx\n\to.Cmd = c\n\to.Args = argsIn\n\n\tenv, err := GetEnv(o.Cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.Env = env\n\tapp, err := appfile.LoadApplication(env.Namespace, o.Args[0], o.VelaC)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.App = app\n\n\tcf := genericclioptions.NewConfigFlags(true)\n\tcf.Namespace = &o.Env.Namespace\n\to.f = k8scmdutil.NewFactory(k8scmdutil.NewMatchVersionFlags(cf))\n\n\tif o.ClientSet == nil {\n\t\tc, err := kubernetes.NewForConfig(o.VelaC.Config)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\to.ClientSet = c\n\t}\n\treturn nil\n}", "func InitCommand(cmd *cobra.Command) *cobra.Command {\n\tflags := pflag.NewFlagSet(\"tmp\", pflag.ContinueOnError)\n\tcli.AddKubectlFlagsToSet(flags)\n\t// copy k8s persistent flags into argocd command flags\n\tflags.VisitAll(func(flag *pflag.Flag) {\n\t\t// skip Kubernetes server flags since argocd has it's own server flag\n\t\tif flag.Name == \"server\" {\n\t\t\treturn\n\t\t}\n\t\tcmd.Flags().AddFlag(flag)\n\t})\n\treturn cmd\n}", "func (c *Command) Init(commandName string, options []*Option) {\n\tc.commandName = commandName\n\tc.ParseOptions(options)\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\n\t// load the defaults from the default map here, add new defaults on the map\n\tfor key, val := range defaults {\n\t\tviper.SetDefault(key, val)\n\t}\n\n\trootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.xendit-account-service.yaml)\")\n}", "func init() {\n\n\tcobra.OnInitialize(func() {\n\t\tconfig.Initialize(rootCmd)\n\t})\n\n\tconfig.InitializeFlags(rootCmd)\n}", "func init() {\n\tcobra.OnInitialize(mainconfig.ConfigInit)\n\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"Debug output\")\n\t_ = viper.BindPFlag(\"debug\", rootCmd.PersistentFlags().Lookup(\"debug\"))\n\t_ = viper.BindEnv(\"debug\", \"DEBUG\")\n\n\trootCmd.PersistentFlags().StringP(\"token\", \"t\", \"\", \"Connect Token\")\n\trootCmd.PersistentFlags().String(\"host\", \"\", \"Connect Host\")\n\n\t_ = viper.BindPFlag(\"test.token\", rootCmd.PersistentFlags().Lookup(\"token\"))\n\t_ = viper.BindPFlag(\"test.host\", rootCmd.PersistentFlags().Lookup(\"host\"))\n\t_ = viper.BindEnv(\"test.token\", \"OP_TOKEN\")\n\t_ = viper.BindEnv(\"test.host\", \"OP_HOST\")\n}", "func (t *Terraform) initArgs(p types.ProviderType, cfg map[string]interface{}, clusterDir string) []string {\n\targs := make([]string, 0)\n\n\tvarsFile := filepath.Join(clusterDir, tfVarsFile)\n\n\targs = append(args, fmt.Sprintf(\"-var-file=%s\", varsFile), clusterDir)\n\n\treturn args\n}", "func InitArgs(cliArgs cli.Args) (*Args, error) {\n\targs := Args{Pattern: cliArgs.Get(0)}\n\tpath, err := filepath.Abs(cliArgs.Get(1))\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, path)\n\t}\n\targs.Path = path\n\treturn &args, nil\n}", "func (k *kafkaCommon) CobraInit(cmd *cobra.Command) {\n\tKafkaCommonCobraInit(cmd, k.conf)\n}", "func (k *kubernetes) Init(opts ...runtime.Option) error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tfor _, o := range opts {\n\t\to(&k.options)\n\t}\n\n\treturn nil\n}", "func (cc *CopyCommand) Init(args []string, options OptionMapType) error {\n\treturn cc.command.Init(args, options, cc)\n}", "func InitCommand(parentCmd *cobra.Command) {\n\tcmd := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"Get an object\",\n\t\tLong: \"\",\n\t\tAliases: []string{\"read\"},\n\t}\n\tparentCmd.AddCommand(cmd)\n\tinitUnitCommand(cmd)\n\tinitUserCommand(cmd)\n\tinitGroupCommand(cmd)\n}", "func (c *Subcommand) InitFlags(flags *flag.FlagSet) {\n\tif c.flagFn != nil {\n\t\tc.flagFn(flags)\n\t}\n}", "func InitFlags(flagset *flag.FlagSet) {\n\tif flagset == nil {\n\t\tflagset = flag.CommandLine\n\t}\n\n\tcommandLine.VisitAll(func(f *flag.Flag) {\n\t\tflagset.Var(f.Value, f.Name, f.Usage)\n\t})\n}", "func (c *Option) Init() (err error) {\n\t// --clear-cache doesn't conduct the scan\n\tif c.ClearCache {\n\t\treturn nil\n\t}\n\n\tc.CustomHeaders = splitCustomHeaders(c.customHeaders)\n\n\t// add token to custom headers\n\tif c.token != \"\" {\n\t\tc.CustomHeaders.Set(c.tokenHeader, c.token)\n\t}\n\n\tif err := c.ReportOption.Init(c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.ArtifactOption.Init(c.Context, c.Logger); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (n *NetworkInspectCommand) Init(c *Cli) {\n\tn.cli = c\n\n\tn.cmd = &cobra.Command{\n\t\tUse: \"inspect [OPTIONS] Network [Network...]\",\n\t\tShort: \"Inspect one or more pouch networks\",\n\t\tLong: networkInspectDescription,\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn n.runNetworkInspect(args)\n\t\t},\n\t\tExample: networkInspectExample(),\n\t}\n\n\tn.addFlags()\n}", "func (cos ConfigOptions) Init(cmd *cobra.Command) error {\n\tfor _, co := range cos {\n\t\tif err := co.Init(cmd); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tco.SetDeprecated(cmd)\n\t}\n\treturn nil\n}", "func (o PgbenchSpecOutput) InitArgs() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v PgbenchSpec) *string { return v.InitArgs }).(pulumi.StringPtrOutput)\n}", "func (p Plugin) GetInitSubcommand() plugin.InitSubcommand { return &p.initSubcommand }", "func (i *ImageInspectCommand) Init(c *Cli) {\n\ti.cli = c\n\ti.cmd = &cobra.Command{\n\t\tUse: \"inspect [OPTIONS] IMAGE [IMAGE...]\",\n\t\tShort: \"Display detailed information on one or more images\",\n\t\tLong: imageInspectDescription,\n\t\tArgs: cobra.MinimumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn i.runInspect(args)\n\t\t},\n\t\tExample: i.example(),\n\t}\n\ti.addFlags()\n}", "func init() {\n\tRootCmd.AddCommand(AdminCmd)\n\tAdminCmd.AddCommand(UnsubscribeCmd, HealthCheckDb, HealthCheckStore, HealthCheckStats, SetVasCmd, SetConfig, DeleteConfig)\n\tSetVasCmd.Flags().String(FlagUserID, \"\", \"\")\n\tSetVasCmd.Flags().Bool(FlagEnabled, false, \"\")\n\tSetConfig.Flags().String(FlagKey, \"\", \"\")\n\tSetConfig.Flags().String(FlagValue, \"\", \"\")\n\tDeleteConfig.Flags().String(FlagKey, \"\", \"\")\n}", "func (o *VelaExecOptions) Init(ctx context.Context, c *cobra.Command, argsIn []string) error {\n\to.Cmd = c\n\to.Args = argsIn\n\n\tnamespace, err := c.Flags().GetString(FlagNamespace)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get `%s`\", FlagNamespace)\n\t}\n\tif namespace == \"\" {\n\t\tenv, err := GetFlagEnvOrCurrent(o.Cmd, o.VelaC)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tnamespace = env.Namespace\n\t}\n\tapp, err := appfile.LoadApplication(namespace, o.Args[0], o.VelaC)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.App = app\n\n\ttargetResource, err := common.AskToChooseOneEnvResource(o.App)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcf := genericclioptions.NewConfigFlags(true)\n\tcf.Namespace = &targetResource.Namespace\n\tcf.WrapConfigFn = func(cfg *rest.Config) *rest.Config {\n\t\tcfg.Wrap(multicluster.NewClusterGatewayRoundTripperWrapperGenerator(targetResource.Cluster))\n\t\treturn cfg\n\t}\n\to.f = k8scmdutil.NewFactory(k8scmdutil.NewMatchVersionFlags(cf))\n\to.resourceName = targetResource.Name\n\to.Ctx = multicluster.ContextWithClusterName(ctx, targetResource.Cluster)\n\to.resourceNamespace = targetResource.Namespace\n\to.VelaC.Config.Wrap(multicluster.NewSecretModeMultiClusterRoundTripper)\n\tk8sClient, err := kubernetes.NewForConfig(o.VelaC.Config)\n\tif err != nil {\n\t\treturn err\n\t}\n\to.ClientSet = k8sClient\n\n\to.kcExecOptions.In = c.InOrStdin()\n\to.kcExecOptions.Out = c.OutOrStdout()\n\to.kcExecOptions.ErrOut = c.OutOrStderr()\n\treturn nil\n}", "func init() {\n\t// initialize config through viper\n\tcobra.OnInitialize(initConfig)\n\t// Define the flags to be supported.\n\tRootCmd.PersistentFlags().StringVar(&cfgFile, \"config\", \"\", \"config file (default is $HOME/.go-webserver.yaml)\")\n}", "func init() {\n\tcobra.OnInitialize(initConfig)\n\tcolorize = color.New(color.FgRed).PrintfFunc()\n\n\trootCmd.Version = \"2.1.0\"\n\n\trootCmd.PersistentFlags().StringVar(&profile, \"profile\", \"default\",\n\t\t\"(Optional) The AWS CLI Profile to use for the request.\")\n\n\trootCmd.PersistentFlags().StringVarP(&filter, \"filter\", \"f\", \"\",\n\t\t\"(Optional) After the Parameter Store API call returns results, filter the names and values \"+\n\t\t\t\"by substring match.\")\n\n\trootCmd.PersistentFlags().StringVarP(&regex, \"regex\", \"r\", \"\",\n\t\t\"(Optional) After the Parameter Store API call returns results, filter the names and values \"+\n\t\t\t\"by RE2 regular expression.\")\n\n\trootCmd.PersistentFlags().BoolVar(&debug, \"debug\", false,\n\t\t\"(Optional) Enable DEBUG logging.\")\n\n\trootCmd.PersistentFlags().BoolVarP(&quiet, \"quiet\", \"q\", false,\n\t\t\"(Optional) Do not display any messages during the fetching of data.\")\n}", "func (b *BuildCommand) Init(c *Cli) {\n\tb.cli = c\n\n\tb.cmd = &cobra.Command{\n\t\tUse: \"build [OPTION] PATH\",\n\t\tShort: \"Build an image from a Dockerfile\",\n\t\tLong: buildDescription,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn b.runBuild(args)\n\t\t},\n\t}\n\tb.addFlags()\n}", "func init() {\n\tflag.StringVar(&KubectlPath, \"kubectl-path\", \"\", \"Path to the kubectl binary\")\n\tflag.StringVar(&ClusterctlPath, \"clusterctl-path\", \"\", \"Path to the clusterctl binary\")\n\tflag.StringVar(&DumpPath, \"dump-path\", \"\", \"Path to the kubevirt artifacts dump cmd binary\")\n\tflag.StringVar(&WorkingDir, \"working-dir\", \"\", \"Path used for e2e test files\")\n}", "func (s *svc) Init(opts ...router.Option) error {\n\ts.Lock()\n\tdefer s.Unlock()\n\n\tfor _, o := range opts {\n\t\to(&s.opts)\n\t}\n\n\treturn nil\n}", "func (a *App) InitDiffFlags(cmd *cobra.Command) {\n\tcmd.ResetFlags()\n\n\tcmd.Flags().StringArrayVarP(&a.Config.LocalFlags.DiffPath, \"path\", \"\", []string{}, \"diff request paths\")\n\tcmd.Flags().StringVarP(&a.Config.LocalFlags.DiffRef, \"ref\", \"\", \"\", \"reference gNMI target to compare the other targets to\")\n\tcmd.MarkFlagRequired(\"ref\")\n\tcmd.Flags().StringArrayVarP(&a.Config.LocalFlags.DiffCompare, \"compare\", \"\", []string{}, \"gNMI targets to compare to the reference\")\n\tcmd.MarkFlagRequired(\"compare\")\n\tcmd.Flags().StringVarP(&a.Config.LocalFlags.DiffPrefix, \"prefix\", \"\", \"\", \"diff request prefix\")\n\tcmd.Flags().StringSliceVarP(&a.Config.LocalFlags.DiffModel, \"model\", \"\", []string{}, \"diff request models\")\n\tcmd.Flags().StringVarP(&a.Config.LocalFlags.DiffType, \"type\", \"t\", \"ALL\", \"data type requested from the target. one of: ALL, CONFIG, STATE, OPERATIONAL\")\n\tcmd.Flags().StringVarP(&a.Config.LocalFlags.DiffTarget, \"target\", \"\", \"\", \"get request target\")\n\tcmd.Flags().BoolVarP(&a.Config.LocalFlags.DiffSub, \"sub\", \"\", false, \"use subscribe ONCE mode instead of a get request\")\n\tcmd.Flags().Uint32VarP(&a.Config.LocalFlags.DiffQos, \"qos\", \"\", 0, \"QoS marking in case subscribe RPC is used\")\n\n\tcmd.LocalFlags().VisitAll(func(flag *pflag.Flag) {\n\t\ta.Config.FileConfig.BindPFlag(fmt.Sprintf(\"%s-%s\", cmd.Name(), flag.Name), flag)\n\t})\n}", "func (rc *RemoveCommand) Init(args []string, options OptionMapType) error {\n\treturn rc.command.Init(args, options, rc)\n}", "func initConfig() {\n\thome, err := homedir.Dir()\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\t// Find home directory.\n\t\tcobra.CheckErr(err)\n\n\t\t// Search config in home directory with name \".clk_cli\" (without extension).\n\t\tviper.AddConfigPath(home)\n\t\tviper.SetConfigName(\".clk_config\")\n\t\tviper.SetConfigType(\"yaml\")\n\t}\n\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tfmt.Fprintln(os.Stdout, \"Using config file:\", viper.ConfigFileUsed())\n\t\tfmt.Println(err.Error())\n\t\treturn\n\t}\n\n\tif flag := rootCmd.PersistentFlags().Lookup(\"workspace\"); flag.Value.String() != \"\" {\n\t\t// Workspace flag is set and the id needs to be found\n\t\tfmt.Println(\"Finding workspace id from flag:\", flag.Value.String())\n\t\tworkspaceID, err := util.GetWorkspaceIDFromName(viper.GetString(\"workspace_name\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not find workspace id from --workspace flag:\", err.Error())\n\t\t}\n\t\tviper.Set(\"workspace_id\", workspaceID)\n\t}\n\n\tif flag := rootCmd.PersistentFlags().Lookup(\"project\"); flag.Value.String() != \"\" {\n\t\t// Workspace flag is set and the id needs to be found\n\t\tfmt.Println(\"Finding project id from flag:\", flag.Value.String())\n\t\tprojectID, err := util.GetProjectIDFromName(viper.GetString(\"project_name\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Could not find project id from --project flag:\", err.Error())\n\t\t}\n\t\tviper.Set(\"project_id\", projectID)\n\t}\n\n\tif viper.GetString(\"api_key\") == \"\" {\n\t\tfmt.Print(\"Missing api key from clockify, enter it: \")\n\t\tvar input string\n\t\tfmt.Scanln(&input)\n\t\tviper.Set(\"api_key\", input)\n\t\tif util.IsApiKeyUseable() {\n\t\t\tfmt.Println(\"Saving config to:\", fmt.Sprint(home, \"/.clk_config.yaml\"))\n\t\t\tif err := viper.WriteConfigAs(fmt.Sprint(home, \"/.clk_config.yaml\")); err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\t\tfmt.Println(\"Got here\")\n\t\t} else {\n\t\t\tfmt.Println(\"Unusable api key, try another\")\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}", "func initArgs(){\n\t//master -config ./master.json\n\tflag.StringVar(&confFile, \"config\", \"./master.json\", \"specify master.json as config file\")\n\tflag.Parse()\n}", "func init() {\n\tcli.InitConfig(configName)\n}", "func init() {\n\tcli.InitConfig(configName)\n}", "func InitCommand(cfg *config.Config) *cli.Command {\n\treturn &cli.Command{\n\t\tName: \"init\",\n\t\tUsage: \"initialise an ocis config\",\n\t\tFlags: []cli.Flag{\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"insecure\",\n\t\t\t\tEnvVars: []string{\"OCIS_INSECURE\"},\n\t\t\t\tValue: \"ask\",\n\t\t\t\tUsage: \"Allow insecure oCIS config\",\n\t\t\t},\n\t\t\t&cli.BoolFlag{\n\t\t\t\tName: \"force-overwrite\",\n\t\t\t\tAliases: []string{\"f\"},\n\t\t\t\tEnvVars: []string{\"OCIS_FORCE_CONFIG_OVERWRITE\"},\n\t\t\t\tValue: false,\n\t\t\t\tUsage: \"Force overwrite existing config file\",\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"config-path\",\n\t\t\t\tValue: defaults.BaseConfigPath(),\n\t\t\t\tUsage: \"Config path for the ocis runtime\",\n\t\t\t\tEnvVars: []string{\"OCIS_CONFIG_DIR\"},\n\t\t\t},\n\t\t\t&cli.StringFlag{\n\t\t\t\tName: \"admin-password\",\n\t\t\t\tAliases: []string{\"ap\"},\n\t\t\t\tEnvVars: []string{\"ADMIN_PASSWORD\", \"IDM_ADMIN_PASSWORD\"},\n\t\t\t\tUsage: \"Set admin password instead of using a random generated one\",\n\t\t\t},\n\t\t},\n\t\tAction: func(c *cli.Context) error {\n\t\t\tinsecureFlag := c.String(\"insecure\")\n\t\t\tinsecure := false\n\t\t\tif insecureFlag == \"ask\" {\n\t\t\t\tanswer := strings.ToLower(stringPrompt(\"Do you want to configure Infinite Scale with certificate checking disabled?\\n This is not recommended for public instances! [yes | no = default]\"))\n\t\t\t\tif answer == \"yes\" || answer == \"y\" {\n\t\t\t\t\tinsecure = true\n\t\t\t\t}\n\t\t\t} else if insecureFlag == strings.ToLower(\"true\") || insecureFlag == strings.ToLower(\"yes\") || insecureFlag == strings.ToLower(\"y\") {\n\t\t\t\tinsecure = true\n\t\t\t}\n\t\t\terr := ocisinit.CreateConfig(insecure, c.Bool(\"force-overwrite\"), c.String(\"config-path\"), c.String(\"admin-password\"))\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Could not create config: %s\", err)\n\t\t\t}\n\t\t\treturn nil\n\t\t},\n\t}\n}", "func init() {\n\trootCmd.AddCommand(listServersCmd)\n\trootCmd.AddCommand(lsCmd)\n\n\taddFlags(listServersCmd)\n\taddFlags(lsCmd)\n}", "func initConfig(*cobra.Command, []string) {\n\tif cfgFile != \"\" {\n\t\t// Use config file from the flag.\n\t\tviper.SetConfigFile(cfgFile)\n\t} else {\n\t\tLogErr(\"config file path is required\\n\")\n\t}\n\n\tviper.AutomaticEnv()\n\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tLogErr(\"Err reading config file: %s\\n\", err)\n\t}\n\n\tLogInfo(\"using config file: %s\\n\", viper.ConfigFileUsed())\n}", "func (p *PullCommand) Init(c *Cli) {\n\tp.cli = c\n\n\tp.cmd = &cobra.Command{\n\t\tUse: \"pull IMAGE\",\n\t\tShort: \"Pull an image from registry\",\n\t\tLong: pullDescription,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn p.runPull(args)\n\t\t},\n\t\tExample: pullExample(),\n\t}\n\tp.addFlags()\n}", "func init() {\n\tflag.StringVar(&apikey, \"apikey\", os.Getenv(\"VT_API_KEY\"), \"Set environment variable VT_API_KEY to your VT API Key or specify on prompt\")\n\tflag.StringVar(&apiurl, \"apiurl\", \"https://www.virustotal.com/vtapi/v2/\", \"URL of the VirusTotal API to be used.\")\n\tflag.StringVar(&domain, \"domain\", \"\", \"a domain to ask information about from VT.\")\n}", "func (c *Command) Init() error {\n\tc.alias = dao.NewAlias(c.app.factory)\n\tif _, err := c.alias.Ensure(); err != nil {\n\t\tlog.Error().Err(err).Msgf(\"command init failed!\")\n\t\treturn err\n\t}\n\tcustomViewers = loadCustomViewers()\n\n\treturn nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tvar err error\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"aead_type\":\n\t\t\t\topts.WithAeadType = wrapping.AeadTypeMap(v)\n\t\t\tcase \"hash_type\":\n\t\t\t\topts.WithHashType = wrapping.HashTypeMap(v)\n\t\t\tcase \"key\":\n\t\t\t\topts.WithKey, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding key value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"salt\":\n\t\t\t\topts.WithSalt, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding salt value: %w\", err)\n\t\t\t\t}\n\t\t\tcase \"info\":\n\t\t\t\topts.WithInfo, err = base64.StdEncoding.DecodeString(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"error base64-decoding info value: %w\", err)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func InitFlags() {\n\n pflag.CommandLine.SetNormalizerFunc(WordSepNormalizeFunc)\n pflag.CommandLine.AddGoFlagSet(goflag.ComamndLine)\n pflag.Parse()\n pflag.VisitAll(func(flag *pflag.Flag)) {\n \tglog.V(2).Infof(\"FLAG: --%s=%q\", flag.Name, flag.Value)\n }\n}", "func Init(options ...micro.Option) {\n\n\tsetupApp(cmd.App(), options...)\n\n\tcmd.Init(\n\t\tcmd.Name(Name),\n\t\tcmd.Description(Description),\n\t\tcmd.Version(BuildVersion()),\n\t)\n}", "func (l *TKGFlags) Init(c *cobraLintConfig) {\n\tl.cmd = c.cmd.Parent()\n\tl.cmdFlags = c.cliTerms.CmdFlags\n\tl.globalFlags = c.cliTerms.GlobalFlags\n\tr := make(Results)\n\tl.results = &r\n}", "func (n *NetworkConnectCommand) Init(c *Cli) {\n\tn.cli = c\n\n\tn.cmd = &cobra.Command{\n\t\tUse: \"connect [OPTIONS] NETWORK CONTAINER\",\n\t\tShort: \"Connect a container to a network\",\n\t\tLong: networkConnectDescription,\n\t\tArgs: cobra.ExactArgs(2),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn n.runNetworkConnect(args)\n\t\t},\n\t\tExample: networkConnectExample(),\n\t}\n\n\tn.addFlags()\n}", "func (g *UICommand) Init(args []string) error {\n\terr := g.fs.Parse(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tg.ProcessDefaults()\n\n\t// load config file if we have one\n\tif g.config != \"\" {\n\t\terr = g.meshConfig.LoadConfigFromFile(g.config)\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Config read error\")\n\t\t\treturn fmt.Errorf(\"Unable to read configuration from %s\", g.config)\n\t\t}\n\t}\n\n\terr = g.fs.Parse(args)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlog.WithField(\"cfg\", g.meshConfig).Trace(\"Read\")\n\tlog.WithField(\"cfg.agent\", g.meshConfig.Agent).Trace(\"Read\")\n\n\treturn nil\n}", "func prepareInitCommand(terragruntOptions *options.TerragruntOptions, terragruntConfig *config.TerragruntConfig, allowSourceDownload bool) error {\n\tif terragruntConfig.RemoteState != nil {\n\t\t// Initialize the remote state if necessary (e.g. create S3 bucket and DynamoDB table)\n\t\tremoteStateNeedsInit, err := remoteStateNeedsInit(terragruntConfig.RemoteState, terragruntOptions)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif remoteStateNeedsInit {\n\t\t\tif err := terragruntConfig.RemoteState.Initialize(terragruntOptions); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\t// Add backend config arguments to the command\n\t\tterragruntOptions.InsertTerraformCliArgs(terragruntConfig.RemoteState.ToTerraformInitArgs()...)\n\t}\n\treturn nil\n}", "func buildEnvInitCmd() *cobra.Command {\n\tvars := initEnvVars{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"init\",\n\t\tShort: \"Creates a new environment in your application.\",\n\t\tExample: `\n Creates a test environment in your \"default\" AWS profile using default configuration.\n /code $ copilot env init --name test --profile default --default-config\n\n Creates a prod-iad environment using your \"prod-admin\" AWS profile.\n /code $ copilot env init --name prod-iad --profile prod-admin --prod\n\n Creates an environment with imported VPC resources.\n /code $ copilot env init --import-vpc-id vpc-099c32d2b98cdcf47 \\\n /code --import-public-subnets subnet-013e8b691862966cf,subnet -014661ebb7ab8681a \\\n /code --import-private-subnets subnet-055fafef48fb3c547,subnet-00c9e76f288363e7f\n\n Creates an environment with overrided CIDRs.\n /code $ copilot env init --override-vpc-cidr 10.1.0.0/16 \\\n /code --override-public-cidrs 10.1.0.0/24,10.1.1.0/24 \\\n /code --override-private-cidrs 10.1.2.0/24,10.1.3.0/24`,\n\t\tRunE: runCmdE(func(cmd *cobra.Command, args []string) error {\n\t\t\topts, err := newInitEnvOpts(vars)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Validate(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err := opts.Ask(); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn opts.Execute()\n\t\t}),\n\t}\n\tcmd.Flags().StringVarP(&vars.appName, appFlag, appFlagShort, tryReadingAppName(), appFlagDescription)\n\tcmd.Flags().StringVarP(&vars.name, nameFlag, nameFlagShort, \"\", envFlagDescription)\n\tcmd.Flags().StringVar(&vars.profile, profileFlag, \"\", profileFlagDescription)\n\tcmd.Flags().StringVar(&vars.tempCreds.AccessKeyID, accessKeyIDFlag, \"\", accessKeyIDFlagDescription)\n\tcmd.Flags().StringVar(&vars.tempCreds.SecretAccessKey, secretAccessKeyFlag, \"\", secretAccessKeyFlagDescription)\n\tcmd.Flags().StringVar(&vars.tempCreds.SessionToken, sessionTokenFlag, \"\", sessionTokenFlagDescription)\n\tcmd.Flags().StringVar(&vars.region, regionFlag, \"\", envRegionTokenFlagDescription)\n\n\tcmd.Flags().BoolVar(&vars.isProduction, prodEnvFlag, false, prodEnvFlagDescription)\n\n\tcmd.Flags().StringVar(&vars.importVPC.ID, vpcIDFlag, \"\", vpcIDFlagDescription)\n\tcmd.Flags().StringSliceVar(&vars.importVPC.PublicSubnetIDs, publicSubnetsFlag, nil, publicSubnetsFlagDescription)\n\tcmd.Flags().StringSliceVar(&vars.importVPC.PrivateSubnetIDs, privateSubnetsFlag, nil, privateSubnetsFlagDescription)\n\n\tcmd.Flags().IPNetVar(&vars.adjustVPC.CIDR, vpcCIDRFlag, net.IPNet{}, vpcCIDRFlagDescription)\n\t// TODO: use IPNetSliceVar when it is available (https://github.com/spf13/pflag/issues/273).\n\tcmd.Flags().StringSliceVar(&vars.adjustVPC.PublicSubnetCIDRs, publicSubnetCIDRsFlag, nil, publicSubnetCIDRsFlagDescription)\n\tcmd.Flags().StringSliceVar(&vars.adjustVPC.PrivateSubnetCIDRs, privateSubnetCIDRsFlag, nil, privateSubnetCIDRsFlagDescription)\n\tcmd.Flags().BoolVar(&vars.defaultConfig, defaultConfigFlag, false, defaultConfigFlagDescription)\n\n\tflags := pflag.NewFlagSet(\"Common\", pflag.ContinueOnError)\n\tflags.AddFlag(cmd.Flags().Lookup(appFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(nameFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(profileFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(accessKeyIDFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(secretAccessKeyFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(sessionTokenFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(regionFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(defaultConfigFlag))\n\tflags.AddFlag(cmd.Flags().Lookup(prodEnvFlag))\n\n\tresourcesImportFlag := pflag.NewFlagSet(\"Import Existing Resources\", pflag.ContinueOnError)\n\tresourcesImportFlag.AddFlag(cmd.Flags().Lookup(vpcIDFlag))\n\tresourcesImportFlag.AddFlag(cmd.Flags().Lookup(publicSubnetsFlag))\n\tresourcesImportFlag.AddFlag(cmd.Flags().Lookup(privateSubnetsFlag))\n\n\tresourcesConfigFlag := pflag.NewFlagSet(\"Configure Default Resources\", pflag.ContinueOnError)\n\tresourcesConfigFlag.AddFlag(cmd.Flags().Lookup(vpcCIDRFlag))\n\tresourcesConfigFlag.AddFlag(cmd.Flags().Lookup(publicSubnetCIDRsFlag))\n\tresourcesConfigFlag.AddFlag(cmd.Flags().Lookup(privateSubnetCIDRsFlag))\n\n\tcmd.Annotations = map[string]string{\n\t\t// The order of the sections we want to display.\n\t\t\"sections\": \"Common,Import Existing Resources,Configure Default Resources\",\n\t\t\"Common\": flags.FlagUsages(),\n\t\t\"Import Existing Resources\": resourcesImportFlag.FlagUsages(),\n\t\t\"Configure Default Resources\": resourcesConfigFlag.FlagUsages(),\n\t}\n\n\tcmd.SetUsageTemplate(`{{h1 \"Usage\"}}{{if .Runnable}}\n {{.UseLine}}{{end}}{{$annotations := .Annotations}}{{$sections := split .Annotations.sections \",\"}}{{if gt (len $sections) 0}}\n\n{{range $i, $sectionName := $sections}}{{h1 (print $sectionName \" Flags\")}}\n{{(index $annotations $sectionName) | trimTrailingWhitespaces}}{{if ne (inc $i) (len $sections)}}\n\n{{end}}{{end}}{{end}}{{if .HasAvailableInheritedFlags}}\n\n{{h1 \"Global Flags\"}}\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasExample}}\n\n{{h1 \"Examples\"}}{{code .Example}}{{end}}\n`)\n\n\treturn cmd\n}", "func initCommonFlags(cmd *cobra.Command) {\n\tcmd.Flags().StringVarP(&basePath, \"project-root\", \"r\", \"root for project\", \"root project dirrectory relative to $GOPATH/src\")\n\tcmd.Flags().StringVarP(&author, \"author\", \"a\", \"your name\", \"author name for copyright\")\n\tcmd.Flags().StringVarP(&email, \"email\", \"e\", \"your email\", \"your email adress to show up on the files\")\n\tcmd.Flags().BoolVarP(&license, \"license\", \"l\", false, \"name of the license to use\")\n}", "func (t *TransformCmd) Init(args []string) error {\n\n\tif err := t.fs.Parse(args); err != nil {\n\t\treturn err\n\t}\n\n\tif t.transFile == \"\" {\n\t\treturn errors.New(\"No transformation file provided\")\n\t}\n\n\tif t.fs.NArg() < 1 {\n\t\treturn errors.New(\"No input file(s) provided\")\n\t}\n\n\tt.inFiles = t.fs.Args()\n\n\treturn nil\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"mount_path\":\n\t\t\t\topts.withMountPath = v\n\t\t\tcase \"key_name\":\n\t\t\t\topts.withKeyName = v\n\t\t\tcase \"disable_renewal\":\n\t\t\t\topts.withDisableRenewal = v\n\t\t\tcase \"namespace\":\n\t\t\t\topts.withNamespace = v\n\t\t\tcase \"address\":\n\t\t\t\topts.withAddress = v\n\t\t\tcase \"tls_ca_cert\":\n\t\t\t\topts.withTlsCaCert = v\n\t\t\tcase \"tls_ca_path\":\n\t\t\t\topts.withTlsCaPath = v\n\t\t\tcase \"tls_client_cert\":\n\t\t\t\topts.withTlsClientCert = v\n\t\t\tcase \"tls_client_key\":\n\t\t\t\topts.withTlsClientKey = v\n\t\t\tcase \"tls_server_name\":\n\t\t\t\topts.withTlsServerName = v\n\t\t\tcase \"tls_skip_verify\":\n\t\t\t\tvar err error\n\t\t\t\topts.withTlsSkipVerify, err = strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tcase \"token\":\n\t\t\t\topts.withToken = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func InitCMD() error {\n\tapp := &cli.App{\n\t\tName: Name,\n\t\tHelpName: Name,\n\t\tUsage: Usage,\n\t\tUsageText: UsageText,\n\t\tArgsUsage: \"\",\n\t\tVersion: Version,\n\t\tDescription: Des,\n\t\tCommands: getCommandsGroup(),\n\t\tFlags: getFlagsGroup(),\n\t\tEnableBashCompletion: false,\n\t\tHideHelp: false,\n\t\tHideHelpCommand: false,\n\t\tHideVersion: false,\n\t\tBashComplete: nil,\n\t\tBefore: nil,\n\t\tAfter: nil,\n\t\tAction: \t\t\t\tinitAction,\n\t\tCommandNotFound: cmdNotFound,\n\t\tOnUsageError: usageError,\n\t\tCompiled: time.Time{},\n\t\tAuthors: Author,\n\t\tCopyright: CopyRight,\n\t\tReader: nil,\n\t\tWriter: nil,\n\t\tErrWriter: nil,\n\t\tExitErrHandler: nil,\n\t\tMetadata: nil,\n\t\tExtraInfo: nil,\n\t\tCustomAppHelpTemplate: \"\",\n\t\tUseShortOptionHandling: false,\n\t}\n\t// init cmd\n\treturn app.Run(os.Args)\n}", "func NewCmdInit(ioStreams genericclioptions.IOStreams) *cobra.Command {\n\tio := config.NewInitOptions(ioStreams)\n\tcmd := &cobra.Command{\n\t\tUse: \"init DIRECTORY\",\n\t\tDisableFlagsInUseLine: true,\n\t\tShort: i18n.T(\"Create a prune manifest ConfigMap as a inventory object\"),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\terr := io.Complete(args)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn io.Run()\n\t\t},\n\t}\n\tcmd.Flags().StringVarP(&io.InventoryID, \"inventory-id\", \"i\", \"\", \"Identifier for group of applied resources. Must be composed of valid label characters.\")\n\tcmd.Flags().StringVarP(&io.Namespace, \"inventory-namespace\", \"\", \"\", \"namespace for the resources to be initialized\")\n\treturn cmd\n}", "func CmdInit(c *cli.Context) error {\n\tif c.NArg() == 0 {\n\t\tlog.Fatal(\"No project name specified\")\n\t} else if c.NArg() > 1 {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"project\": c.Args().Get(0),\n\t\t}).Warn(\"Multi project name specified. First one will use\")\n\t}\n\n\tproject := c.Args().Get(0)\n\tcfgCtrl, err := config.NewController()\n\tif err != nil {\n\t\tlog.Fatal(err.Error())\n\t}\n\n\tif cfgCtrl.PjAlreadyCreated {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"path\": cfgCtrl.ProjectRoot,\n\t\t}).Fatal(\"envrionment already exists\")\n\t}\n\n\tif err := cfgCtrl.Init(); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Fatal(\"Failed to init config file\")\n\t}\n\n\ts := skeleton.Skeleton{Path: cfgCtrl.ProjectRoot}\n\tif err := s.Init(&skeleton.InitExecutable{Project: project}); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Fatal(\"Failed to Exec template\")\n\t}\n\n\tcfg := &config.Config{Project: project}\n\tif err := cfgCtrl.Write(cfg); err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"error\": err,\n\t\t}).Fatal(\"Failed to dump config into file\")\n\t}\n\n\tlog.WithFields(log.Fields{\n\t\t\"name\": project,\n\t}).Infof(\"Project initialized. Environments created\")\n\treturn nil\n}", "func argInit() args {\n\n\tvar a args\n\tflag.Float64Var(&a.x1, \"x1\", -2.0, \"left position of real axis\")\n\tflag.Float64Var(&a.x2, \"x2\", 1.0, \"right position of real axis\")\n\tflag.Float64Var(&a.y1, \"y1\", -1.5, \"down position of imaginary axis\")\n\tflag.Float64Var(&a.y2, \"y2\", 1.5, \"up position of imaginary axis\")\n\tflag.Float64Var(&a.threshold, \"th\", 4.0, \"squared threshold of the function\")\n\tflag.IntVar(&a.w, \"w\", 1000, \"width in pixels of the image\")\n\tflag.IntVar(&a.h, \"h\", 1000, \"height in pixels of the image\")\n\tflag.IntVar(&a.nIter, \"ni\", 100, \"maximum number of iterations for pixel\")\n\tflag.IntVar(&a.nRoutines, \"nr\", 4, \"number of go routines to be used\")\n\tflag.StringVar(&a.path, \"p\", \"./\", \"path to the generated png image\")\n\n\tflag.Parse()\n\treturn a\n}", "func initFlag(cmd *cobra.Command) {\n\t//\tcobra.OnInitialize(initConfig)\n\t// add Pesistent flags\n\tcmd.PersistentFlags().StringP(\"server\", \"s\", \"localhost:6789\", \"katib manager API endpoint\")\n\n\t//bind viper\n\tviper.BindPFlag(\"server\", cmd.PersistentFlags().Lookup(\"server\"))\n}", "func (c *MigrationsCmd) Init() {\n\tc.common.SetArgs(c.CheckArgs)\n\tc.common.SetRun(c.Run)\n}", "func (n *NetworkListCommand) Init(c *Cli) {\n\tn.cli = c\n\n\tn.cmd = &cobra.Command{\n\t\tUse: \"list\",\n\t\tAliases: []string{\"ls\"},\n\t\tShort: \"List pouch networks\",\n\t\tLong: networkListDescription,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn n.runNetworkList(args)\n\t\t},\n\t\tExample: networkListExample(),\n\t}\n\n\tn.addFlags()\n}", "func getOpts(opt ...wrapping.Option) (*options, error) {\n\t// First, separate out options into local and global\n\topts := getDefaultOptions()\n\tvar wrappingOptions []wrapping.Option\n\tvar localOptions []OptionFunc\n\tfor _, o := range opt {\n\t\tif o == nil {\n\t\t\tcontinue\n\t\t}\n\t\tiface := o()\n\t\tswitch to := iface.(type) {\n\t\tcase wrapping.OptionFunc:\n\t\t\twrappingOptions = append(wrappingOptions, o)\n\t\tcase OptionFunc:\n\t\t\tlocalOptions = append(localOptions, to)\n\t\t}\n\t}\n\n\t// Parse the global options\n\tvar err error\n\topts.Options, err = wrapping.GetOpts(wrappingOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Don't ever return blank options\n\tif opts.Options == nil {\n\t\topts.Options = new(wrapping.Options)\n\t}\n\n\t// Local options can be provided either via the WithConfigMap field\n\t// (for over the plugin barrier or embedding) or via local option functions\n\t// (for embedding). First pull from the option.\n\tif opts.WithConfigMap != nil {\n\t\tfor k, v := range opts.WithConfigMap {\n\t\t\tswitch k {\n\t\t\tcase \"key_not_required\":\n\t\t\t\tkeyNotRequired, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\topts.withKeyNotRequired = keyNotRequired\n\t\t\tcase \"user_agent\":\n\t\t\t\topts.withUserAgent = v\n\t\t\tcase \"credentials\":\n\t\t\t\topts.withCredentials = v\n\t\t\tcase \"project\":\n\t\t\t\topts.withProject = v\n\t\t\tcase \"region\":\n\t\t\t\topts.withRegion = v\n\t\t\tcase \"key_ring\":\n\t\t\t\topts.withKeyRing = v\n\t\t\tcase \"crypto_key\":\n\t\t\t\topts.withCryptoKey = v\n\t\t\t}\n\t\t}\n\t}\n\n\t// Now run the local options functions. This may overwrite options set by\n\t// the options above.\n\tfor _, o := range localOptions {\n\t\tif o != nil {\n\t\t\tif err := o(&opts); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn &opts, nil\n}", "func GetUinitArgs() []string {\n\tuinitargs, _ := Flag(\"uroot.uinitargs\")\n\treturn shlex.Argv(uinitargs)\n}", "func GetCommandArgs(ctx context.Context,\n\tcr *CommandReference,\n\ts *State) interface{} {\n\tswitch cr.Type {\n\tcase CommandType_cmd_vkCmdBeginRenderPass:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBeginRenderPass.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdEndRenderPass:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdEndRenderPass.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdNextSubpass:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdNextSubpass.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBindPipeline:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBindPipeline.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBindDescriptorSets:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBindDescriptorSets.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBindVertexBuffers:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBindVertexBuffers.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBindIndexBuffer:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBindIndexBuffer.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdPipelineBarrier:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdPipelineBarrier.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdWaitEvents:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdWaitEvents.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBeginQuery:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBeginQuery.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdBlitImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdBlitImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdClearAttachments:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdClearAttachments.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdClearColorImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdClearColorImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdClearDepthStencilImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdClearDepthStencilImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdCopyBuffer:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdCopyBuffer.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdCopyBufferToImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdCopyBufferToImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdCopyImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdCopyImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdCopyImageToBuffer:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdCopyImageToBuffer.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdCopyQueryPoolResults:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdCopyQueryPoolResults.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDispatch:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDispatch.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDispatchIndirect:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDispatchIndirect.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDraw:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDraw.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDrawIndexed:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDrawIndexed.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDrawIndexedIndirect:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDrawIndexedIndirect.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDrawIndirect:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDrawIndirect.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdEndQuery:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdEndQuery.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdExecuteCommands:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdExecuteCommands.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdFillBuffer:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdFillBuffer.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdPushConstants:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdPushConstants.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdResetQueryPool:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdResetQueryPool.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdResolveImage:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdResolveImage.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetBlendConstants:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetBlendConstants.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetDepthBias:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetDepthBias.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetDepthBounds:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetDepthBounds.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetEvent:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetEvent.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdResetEvent:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdResetEvent.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetLineWidth:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetLineWidth.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetScissor:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetScissor.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetStencilCompareMask:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetStencilCompareMask.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetStencilReference:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetStencilReference.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetStencilWriteMask:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetStencilWriteMask.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdSetViewport:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdSetViewport.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdUpdateBuffer:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdUpdateBuffer.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdWriteTimestamp:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdWriteTimestamp.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDebugMarkerBeginEXT:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDebugMarkerBeginEXT.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDebugMarkerEndEXT:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDebugMarkerEndEXT.Get(cr.MapIndex)\n\tcase CommandType_cmd_vkCmdDebugMarkerInsertEXT:\n\t\treturn s.CommandBuffers.Get(cr.Buffer).BufferCommands.VkCmdDebugMarkerInsertEXT.Get(cr.MapIndex)\n\tdefault:\n\t\tx := fmt.Sprintf(\"Should not reach here: %T\", cr)\n\t\tpanic(x)\n\t}\n}", "func NewCmdInit(cmdOut io.Writer, pathOptions *clientcmd.PathOptions, defaultServerImage, defaultEtcdImage string) *cobra.Command {\n\topts := &initClusterRegistryOptions{}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"init CLUSTER_REGISTRY_NAME --host-cluster-context=HOST_CONTEXT\",\n\t\tShort: \"Initialize a cluster registry\",\n\t\tLong: init_long,\n\t\tExample: init_example,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\terr := opts.commonOptions.SetName(args)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\n\t\t\terr = validateOptions(opts)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\n\t\t\terr = marshalOptions(opts)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\n\t\t\thostConfig, err := util.GetClientConfig(pathOptions, opts.commonOptions.Host, opts.commonOptions.Kubeconfig).ClientConfig()\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\t\t\thostClientset, err := client.NewForConfig(hostConfig)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\t\t\terr = Run(opts, cmdOut, hostClientset, pathOptions)\n\t\t\tif err != nil {\n\t\t\t\tglog.Fatalf(\"error: %v\", err)\n\t\t\t}\n\t\t},\n\t}\n\n\tflags := cmd.Flags()\n\topts.commonOptions.Bind(flags)\n\topts.Bind(flags, defaultServerImage, defaultEtcdImage)\n\n\treturn cmd\n}", "func (c *impl) initCmd() {\n\tc.commandMap = make(map[string]core.Command)\n\tc.commandSet = make(map[string]core.Command)\n\tc.registerBaseCommands()\n}", "func init() {\n\troot.RootCmd.AddCommand(rootCmd)\n\trootCmd.PersistentFlags().StringVar(&walletDir, \"wallet_dir\", common.DefaultWalletDir, \"Specify directory to search keystore files\")\n\trootCmd.AddCommand(\n\t\t&cobra.Command{\n\t\t\tUse: \"issue [issuer] [owner] [name] [symbol] [supply] [decimal]\",\n\t\t\tShort: \"issue a new token\",\n\t\t\tRun: createTokenCmdFunc,\n\t\t},\n\t\t&cobra.Command{\n\t\t\tUse: \"transfer [from] [tokenID] [addr1,addr2...] [amount1,amount2 ...]\",\n\t\t\tShort: \"transfer tokens\",\n\t\t\tRun: transferTokenCmdFunc,\n\t\t},\n\t\t&cobra.Command{\n\t\t\tUse: \"getbalance [tokenID] [addr1, addr2 ...]\",\n\t\t\tShort: \"get token balance\",\n\t\t\tRun: getTokenBalanceCmdFunc,\n\t\t},\n\t)\n}", "func getEnterArgv(p *pod, imageID *types.Hash, cmdArgs []string) ([]string, error) {\n\tvar argv []string\n\tif len(cmdArgs) < 2 {\n\t\tstderr(\"No command specified, assuming %q\", defaultCmd)\n\t\targv = []string{defaultCmd}\n\t} else {\n\t\targv = cmdArgs[1:]\n\t}\n\n\treturn argv, nil\n}", "func (v *VersionCommand) Init(c *Cli) {\n\tv.cli = c\n\tv.cmd = &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print versions about Pouch CLI and Pouchd\",\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn v.runVersion()\n\t\t},\n\t\tExample: versionExample(),\n\t}\n\tv.addFlags()\n}", "func extractKubeConfigAndContextFromCommand(command *cobra.Command, args []string) (kubeconfig string, context string) {\n\tif len(args) <= 2 {\n\t\treturn\n\t}\n\n\t// Find subcommand.\n\tif subcommand, _, err := command.Find(args[1:]); err == nil {\n\t\tcommand = subcommand\n\t}\n\n\t// Ignore errors from ParseFlags.\n\tcommand.ParseFlags(args[1:])\n\n\tkubeconfig = command.Flag(\"kubeconfig\").Value.String()\n\tcontext = command.Flag(\"context\").Value.String()\n\treturn\n}", "func (n *NetworkRemoveCommand) Init(c *Cli) {\n\tn.cli = c\n\n\tn.cmd = &cobra.Command{\n\t\tUse: \"remove [OPTIONS] NAME\",\n\t\tAliases: []string{\"rm\"},\n\t\tShort: \"Remove a pouch network\",\n\t\tLong: networkRemoveDescription,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn n.runNetworkRemove(args)\n\t\t},\n\t\tExample: networkRemoveExample(),\n\t}\n\n\tn.addFlags()\n}", "func NewCmdInit(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {\n\toptions := &InitOptions{\n\t\tCommonOptions: CommonOptions{\n\t\t\tFactory: f,\n\t\t\tOut: out,\n\t\t\tErr: errOut,\n\t\t},\n\t}\n\n\tcmd := &cobra.Command{\n\t\tUse: \"init\",\n\t\tShort: \"Init Jenkins X\",\n\t\tLong: initLong,\n\t\tExample: initExample,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\toptions.Cmd = cmd\n\t\t\toptions.Args = args\n\t\t\terr := options.Run()\n\t\t\tcmdutil.CheckErr(err)\n\t\t},\n\t}\n\n\toptions.addCommonFlags(cmd)\n\n\tcmd.Flags().StringVarP(&options.Flags.Provider, \"provider\", \"\", \"\", \"Cloud service providing the kubernetes cluster. Supported providers: [minikube,gke,aks]\")\n\toptions.addInitFlags(cmd)\n\treturn cmd\n}", "func getOpts() []htindex.Option {\n\tvar opts []htindex.Option\n\tcfg := &config{}\n\terr := viper.Unmarshal(cfg)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif cfg.Root != \"\" {\n\t\topts = append(opts, htindex.OptRoot(cfg.Root))\n\t}\n\tif cfg.Input != \"\" {\n\t\topts = append(opts, htindex.OptInput(cfg.Input))\n\t}\n\tif cfg.Output != \"\" {\n\t\topts = append(opts, htindex.OptOutput(cfg.Output))\n\t}\n\tif cfg.Jobs > 0 {\n\t\topts = append(opts, htindex.OptJobs(cfg.Jobs))\n\t}\n\tif cfg.WordsAround > 0 {\n\t\topts = append(opts, htindex.OptWordsAround(cfg.WordsAround))\n\t}\n\tif cfg.ProgressNum > 0 {\n\t\topts = append(opts, htindex.OptProgressNum(cfg.ProgressNum))\n\t}\n\treturn opts\n}", "func init() {\n\trootCmd.AddCommand(reportCmd)\n\treportCmd.PersistentFlags().Int8Var(&before, \"before\", 12, \"Specified before uptime in hour report will be generate\")\n\terr := viper.BindPFlag(\"before\", reportCmd.PersistentFlags().Lookup(\"before\"))\n\tif err != nil {\n\t\tlog.Error().Msgf(\"Error binding before value: %v\", err.Error())\n\t}\n\tviper.SetDefault(\"before\", 12)\n\treportCmd.PersistentFlags().StringVar(&credfile, \"credfile\", \"~/.aws/credentials\", \"Specify aws credential file\")\n\terr = viper.BindPFlag(\"credfile\", reportCmd.PersistentFlags().Lookup(\"credfile\"))\n\tif err != nil {\n\t\tlog.Error().Msgf(\"Error binding credfile value: %v\", err.Error())\n\t}\n\tviper.SetDefault(\"credfile\", \"/.aws/credentials\")\n}", "func initConfig(cmd *cobra.Command) {\n\tviper.SetConfigName(\".skelly\") // name of config file (without extension)\n\tviper.AddConfigPath(\"$HOME\") // adding home directory as first search path\n\tviper.SetConfigType(\"json\")\n\tviper.AutomaticEnv() // read in environment variables that match\n\n\tfmt.Println(\"got here\")\n\t// If a config file is found, read it in.\n\tif err := viper.ReadInConfig(); err == nil {\n\t\tfmt.Println(\"Using config file:\", viper.ConfigFileUsed())\n\t}\n\n\t// Make sure that go src var is set\n\tgopath = viper.GetString(\"gopath\")\n\tif len(gopath) <= 0 {\n\t\tgopath = joinPath(os.Getenv(\"GOPATH\"), \"src\")\n\t\tviper.Set(\"gopath\", gopath)\n\t}\n\n\tif cmd.Flags().Lookup(\"project-root\").Changed {\n\t\tviper.Set(\"project-root\", basePath)\n\t}\n\tif cmd.Flags().Lookup(\"author\").Changed {\n\t\tfmt.Println(\"adding author\")\n\t\tviper.Set(\"author\", author)\n\t}\n\tif cmd.Flags().Lookup(\"email\").Changed {\n\t\tviper.Set(\"email\", email)\n\t}\n\tfmt.Println(email)\n\tif cmd.Flags().Lookup(\"license\").Changed {\n\t\tviper.Set(\"license\", license)\n\t}\n}", "func Init(svr *grpc.Server) {\n\tsds, _ := grpcreflect.LoadServiceDescriptors(svr)\n\tmethodStore = make(map[string]*pbbase.OptionBase)\n\tfor _, sd := range sds {\n\t\tfor _, md := range sd.GetMethods() {\n\t\t\topts := md.GetMethodOptions()\n\n\t\t\tval, err := proto.GetExtension(opts, pbbase.E_OptionBase)\n\t\t\tif err == nil {\n\t\t\t\toption, ok := val.(*pbbase.OptionBase)\n\t\t\t\tif ok {\n\t\t\t\t\tmethodStore[fmt.Sprintf(\"/%s/%s\", sd.GetFullyQualifiedName(), md.GetName())] = option\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}", "func InitFlags() *FactoryOptions {\n\ttesting.Init()\n\t_, err := types.NewAttachedGinkgoFlagSet(flag.CommandLine, types.GinkgoFlags{}, nil, types.GinkgoFlagSections{}, types.GinkgoFlagSection{})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\ttestOptions := &FactoryOptions{}\n\ttestOptions.BindFlags(flag.CommandLine)\n\tflag.Parse()\n\n\treturn testOptions\n}", "func getFlags(opts []htindex.Option, cmd *cobra.Command) []htindex.Option {\n\troot, err := cmd.Flags().GetString(\"root\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif root != \"\" {\n\t\topts = append(opts, htindex.OptRoot(root))\n\t}\n\tinput, err := cmd.Flags().GetString(\"input\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif input != \"\" {\n\t\topts = append(opts, htindex.OptInput(input))\n\t}\n\toutput, err := cmd.Flags().GetString(\"output\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif output != \"\" {\n\t\topts = append(opts, htindex.OptOutput(output))\n\t}\n\tjobs, err := cmd.Flags().GetInt(\"jobs\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif jobs > 0 {\n\t\topts = append(opts, htindex.OptJobs(jobs))\n\t}\n\twords, err := cmd.Flags().GetInt(\"words-around\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif words > 0 {\n\t\topts = append(opts, htindex.OptWordsAround(words))\n\t}\n\tprogress, err := cmd.Flags().GetInt(\"progress\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\tif progress > 0 {\n\t\topts = append(opts, htindex.OptProgressNum(progress))\n\t}\n\treturn opts\n}", "func (n *NetworkCreateCommand) Init(c *Cli) {\n\tn.cli = c\n\n\tn.cmd = &cobra.Command{\n\t\tUse: \"create [OPTIONS] [NAME]\",\n\t\tShort: \"Create a pouch network\",\n\t\tLong: networkCreateDescription,\n\t\tArgs: cobra.MaximumNArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\treturn n.runNetworkCreate(args)\n\t\t},\n\t\tExample: networkCreateExample(),\n\t}\n\n\tn.addFlags()\n}", "func configInitCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"init\",\n\t\tAliases: []string{\"i\"},\n\t\tShort: \"Creates a default home directory at path defined by --home\",\n\t\tRunE: func(cmd *cobra.Command, args []string) (err error) {\n\n\t\t\terr = viper.SafeWriteConfig()\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"error saving config(%s): %v\", viper.ConfigFileUsed(), err)\n\t\t\t}\n\t\t\treturn\n\n\t\t},\n\t}\n\treturn cmd\n}", "func (c *PruneCommand) Init(args []string) error {\n\treturn c.fs.Parse(args)\n}", "func ExtractArgs(o *options.Options, cmd *cobra.Command, args []string) (*options.Options, error) {\n\tvar err error\n\n\tif o == nil {\n\t\to = options.NewOptions()\n\t}\n\n\to.Tests, err = ExtractTests(args)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\to.Start = o.Tests[0]\n\n\treturn o, nil\n}", "func initCmd(mbm module.BasicManager, customAppState app.GenesisState, defaultNodeHome string) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"init [moniker]\",\n\t\tShort: \"Initialize private validator, p2p, genesis, and application configuration files\",\n\t\tLong: `Initialize validators's and node's configuration files.`,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tclientCtx := client.GetClientContextFromCmd(cmd)\n\n\t\t\tserverCtx := server.GetServerContextFromCmd(cmd)\n\t\t\t// config for app.toml file\n\t\t\tappConfg := srvconfig.DefaultConfig()\n\t\t\tappConfg.API.Enable = true\n\t\t\t// config for config.toml file\n\t\t\tconfig := serverCtx.Config\n\n\t\t\tconfig.SetRoot(clientCtx.HomeDir)\n\n\t\t\tchainID, _ := cmd.Flags().GetString(flags.FlagChainID)\n\t\t\tif chainID == \"\" {\n\t\t\t\tchainID = fmt.Sprintf(\"test-chain-%v\", tmrand.Str(6))\n\t\t\t}\n\n\t\t\t// Get bip39 mnemonic\n\t\t\tvar mnemonic string\n\t\t\trecover, _ := cmd.Flags().GetBool(FlagRecover)\n\t\t\tif recover {\n\t\t\t\tinBuf := bufio.NewReader(cmd.InOrStdin())\n\t\t\t\tmnemonic, err := input.GetString(\"Enter your bip39 mnemonic\", inBuf)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\t\t\t\tif !bip39.IsMnemonicValid(mnemonic) {\n\t\t\t\t\treturn errors.New(\"invalid mnemonic\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tnodeID, _, err := genutil.InitializeNodeValidatorFilesFromMnemonic(config, mnemonic)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tconfig.Moniker = args[0]\n\t\t\tconfig.P2P.MaxNumInboundPeers = 100\n\t\t\tconfig.P2P.MaxNumOutboundPeers = 100\n\n\t\t\tgenFile := config.GenesisFile()\n\t\t\toverwrite, _ := cmd.Flags().GetBool(FlagOverwrite)\n\n\t\t\tif !overwrite && tmos.FileExists(genFile) {\n\t\t\t\treturn fmt.Errorf(\"genesis.json file already exists: %v\", genFile)\n\t\t\t}\n\t\t\tappState, err := json.MarshalIndent(customAppState, \"\", \" \")\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Failed to marshall default genesis state\")\n\t\t\t}\n\n\t\t\tgenDoc := &types.GenesisDoc{}\n\t\t\tif _, err := os.Stat(genFile); err != nil {\n\t\t\t\tif !os.IsNotExist(err) {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tgenDoc, err = types.GenesisDocFromFile(genFile)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn errors.Wrap(err, \"Failed to read genesis doc from file\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tgenDoc.ChainID = chainID\n\t\t\tgenDoc.Validators = nil\n\t\t\tgenDoc.AppState = appState\n\t\t\tif err = genutil.ExportGenesisFile(genDoc, genFile); err != nil {\n\t\t\t\treturn errors.Wrap(err, \"Failed to export gensis file\")\n\t\t\t}\n\n\t\t\ttoPrint := newPrintInfo(config.Moniker, chainID, nodeID, \"\", appState)\n\n\t\t\tcfg.WriteConfigFile(filepath.Join(config.RootDir, \"config\", \"config.toml\"), config)\n\t\t\tsrvconfig.WriteConfigFile(filepath.Join(config.RootDir, \"config/app.toml\"), appConfg)\n\t\t\treturn displayInfo(toPrint)\n\t\t},\n\t}\n\n\tcmd.Flags().String(cli.HomeFlag, defaultNodeHome, \"node's home directory\")\n\tcmd.Flags().BoolP(FlagOverwrite, \"o\", false, \"overwrite the genesis.json file\")\n\tcmd.Flags().Bool(FlagRecover, false, \"provide seed phrase to recover existing key instead of creating\")\n\tcmd.Flags().String(flags.FlagChainID, \"\", \"genesis file chain-id, if left blank will be randomly created\")\n\n\treturn cmd\n}", "func (v *VersionCommand) Init(c *Cli) {\n\tv.cli = c\n\n\tv.cmd = &cobra.Command{\n\t\tUse: \"version\",\n\t\tShort: \"Print version\",\n\t}\n}", "func (c *Cmd) Init() {}", "func (s *service) Init(opts ...Option) {\n\t// process options\n\tfor _, o := range opts {\n\t\to(&s.opts)\n\t}\n\n\ts.once.Do(func() {\n\t\t// set cmd name\n\t\tif len(s.opts.Cmd.App().Name) == 0 {\n\t\t\ts.opts.Cmd.App().Name = s.Server().Options().Name\n\t\t}\n\n\t\t// Initialise the command flags, overriding new service\n\t\tif err := s.opts.Cmd.Init(\n\t\t\tcmd.Auth(&s.opts.Auth),\n\t\t\tcmd.Broker(&s.opts.Broker),\n\t\t\tcmd.Registry(&s.opts.Registry),\n\t\t\tcmd.Runtime(&s.opts.Runtime),\n\t\t\tcmd.Transport(&s.opts.Transport),\n\t\t\tcmd.Client(&s.opts.Client),\n\t\t\tcmd.Config(&s.opts.Config),\n\t\t\tcmd.Server(&s.opts.Server),\n\t\t\tcmd.Store(&s.opts.Store),\n\t\t\tcmd.Profile(&s.opts.Profile),\n\t\t); err != nil {\n\t\t\ts.opts.Logger.Log(log.FatalLevel, err)\n\t\t}\n\n\t\t// Explicitly set the table name to the service name\n\t\tname := s.opts.Cmd.App().Name\n\t\terr := s.opts.Store.Init(store.Table(name))\n\t\tif err != nil {\n\t\t\ts.opts.Logger.Log(log.FatalLevel, err)\n\t\t}\n\t})\n}", "func InitOptions(vip *viper.Viper) error {\n\t// Add default values for all the options\n\tfor _, op := range Options {\n\t\tvip.SetDefault(op.name, op.def) \n\t}\n\n\treturn nil\n}", "func init() {\n\tRootCmd.AddCommand(GetProjectCmd)\n}", "func GetCliParams(args []string) CliParams {\n\tdefer FuncEnding(FuncStarting())\n\tvar err error\n\trv := CliParams{}\n\tfor i := 0; i < len(args); i++ {\n\t\tswitch {\n\t\t// Flag cases go first.\n\t\tcase IsOneOfStrFold(args[i], \"--help\", \"-h\", \"help\"):\n\t\t\tDebugf(\"Help flag found: [%s].\", args[i])\n\t\t\t// Using fmt.Printf here instead of my stdout function because the extra formatting is annoying with help text.\n\t\t\tfmt.Printf(\"Usage: %s [<input file>]\\n\", GetCmdName())\n\t\t\tfmt.Printf(\"Default <input file> is %s\\n\", default_input_file)\n\t\t\trv.HelpPrinted = true\n\t\tcase HasPrefixFold(args[i], \"--debug\"):\n\t\t\tDebugf(\"Debug option found: [%s], args left: %q.\", args[i], args[i:])\n\t\t\tvar extraI int\n\t\t\trv.Debug, extraI, err = ParseFlagBool(args[i:])\n\t\t\ti += extraI\n\t\t\trv.AppendError(err)\n\t\t\tif err == nil {\n\t\t\t\tswitch {\n\t\t\t\tcase !debug && rv.Debug:\n\t\t\t\t\tdebug = rv.Debug\n\t\t\t\t\tStderr(\"Debugging enabled by CLI arguments.\")\n\t\t\t\tcase debug && !rv.Debug:\n\t\t\t\t\tStderr(\"Debugging disabled by CLI arguments.\")\n\t\t\t\t\tdebug = rv.Debug\n\t\t\t\t}\n\t\t\t}\n\t\tcase HasOneOfPrefixesFold(args[i], \"--input\", \"--input-file\"):\n\t\t\tDebugf(\"Input file option found: [%s], args left: %q.\", args[i], args[i:])\n\t\t\tvar extraI int\n\t\t\trv.InputFile, extraI, err = ParseFlagString(args[i:])\n\t\t\ti += extraI\n\t\t\trv.AppendError(err)\n\t\tcase HasOneOfPrefixesFold(args[i], \"--count\", \"-c\", \"-n\"):\n\t\t\tDebugf(\"Count option found: [%s], args left: %q.\", args[i], args[i:])\n\t\t\tvar extraI int\n\t\t\trv.Count, extraI, err = ParseFlagInt(args[i:])\n\t\t\ti += extraI\n\t\t\trv.AppendError(err)\n\t\tcase HasOneOfPrefixesFold(args[i], \"--points\", \"-p\"):\n\t\t\tDebugf(\"Points option found: [%s], args left: %q.\", args[i], args[i:])\n\t\t\tvar extraI int\n\t\t\trv.Points, extraI, err = ParseFlagString(args[i:])\n\t\t\ti += extraI\n\t\t\trv.AppendError(err)\n\n\t\t// Positional args go last in the order they're expected.\n\t\tcase len(rv.InputFile) == 0:\n\t\t\tDebugf(\"Input File argument: [%s].\", args[i])\n\t\t\trv.InputFile = args[i]\n\t\tdefault:\n\t\t\tDebugf(\"Unknown argument found: [%s], args left: %q.\", args[i], args[i:])\n\t\t\trv.AppendError(fmt.Errorf(\"unknown argument %d: [%s]\", i+1, args[i]))\n\t\t}\n\t}\n\trv.Debug = debug\n\tif len(rv.InputFile) == 0 {\n\t\trv.InputFile = default_input_file\n\t}\n\treturn rv\n}", "func (o *Options) InitFlags(fs *flag.FlagSet) {\n\tif fs == nil {\n\t\tfs = flag.CommandLine\n\t}\n\n\tflag.StringVar(\n\t\t&o.MetricsAddr,\n\t\t\"metrics-addr\",\n\t\t\":8080\",\n\t\t\"The address the metric endpoint binds to.\")\n\tflag.BoolVar(\n\t\t&o.LeaderElectionEnabled,\n\t\t\"enable-leader-election\",\n\t\ttrue,\n\t\t\"Enable leader election for controller manager. Enabling this will ensure there is only one active controller manager.\")\n\tflag.StringVar(\n\t\t&o.LeaderElectionID,\n\t\t\"leader-election-id\",\n\t\t\"\",\n\t\t\"Name of the config map to use as the locking resource when configuring leader election.\")\n\tflag.StringVar(\n\t\t&o.LeaderElectionNamespace,\n\t\t\"leader-election-namespace\",\n\t\t\"\",\n\t\t\"Name of the namespace to use for the configmap locking resource when configuring leader election.\")\n\tflag.StringVar(\n\t\t&o.WatchNamespace,\n\t\t\"namespace\",\n\t\t\"\",\n\t\t\"Namespace that the controller watches to reconcile cluster-api objects. If unspecified, the controller watches for cluster-api objects across all namespaces.\")\n\tflag.DurationVar(\n\t\t&o.SyncPeriod,\n\t\t\"sync-period\",\n\t\tDefaultSyncPeriod,\n\t\t\"The interval at which cluster-api objects are synchronized\")\n\tflag.IntVar(\n\t\t&o.MaxConcurrentReconciles,\n\t\t\"max-concurrent-reconciles\",\n\t\t10,\n\t\t\"The maximum number of allowed, concurrent reconciles.\")\n\tflag.StringVar(\n\t\t&o.PodNameSuffix,\n\t\t\"pod-name-suffix\",\n\t\t\"controller-manager\",\n\t\t\"The suffix name of the pod running the controller manager.\")\n\tflag.StringVar(\n\t\t&o.PodNamespaceSuffix,\n\t\t\"pod-namespace-suffix\",\n\t\t\"controller-manager\",\n\t\t\"The suffix name of the pod namespace running the controller manager.\")\n\tflag.IntVar(\n\t\t&o.WebhookPort,\n\t\t\"webhook-port\",\n\t\tDefaultWebhookServiceContainerPort,\n\t\t\"Webhook Server port (set to 0 to disable)\")\n\tflag.StringVar(\n\t\t&o.HealthAddr,\n\t\t\"health-addr\",\n\t\t\":9440\",\n\t\t\"The address the health endpoint binds to.\",\n\t)\n}", "func InitCommand() cli.Command {\n\treturn cli.Command{\n\t\tName: \"init\",\n\t\tAliases: []string{\"i\"},\n\t\tUsage: \"Initialize new project in current utils, if you give no project name, it will make a slug of utils name.\",\n\t\tArgsUsage: \"[project]\",\n\t\tAction: makeInitAction,\n\t}\n}", "func parseCmdLine() []string{\n\t// Anything that wasn't command, argument, or option will be returned\n\t// as a filename.\n\t// Upon return:\n\t// if a command like init was encountered,\n\tvar filenames []string\n\tvar parsingArgument bool\n\tfor pos, nextArg := range os.Args {\n\t\t//fmt.Printf(\"\\n\\nTop of loop. os.Args[%v]: %v. parsingArgument: %v\\n\", pos, nextArg,parsingArgument)\n\t\tswitch nextArg {\n\t\tcase \"init\":\n\t\t\t// initCmd.Parsed() is now true\n\t\t\tinitCmd.Parse(os.Args[pos+1:])\n\t\t\tif *initSiteName != \"\" {\n\t\t\t\t// *initSitename now points to the string value.\n\t\t\t\t// It's empty if -sitename wasn't -sitename specified\n\t\t\t\tparsingArgument = true\n\t\t\t}\n\t\tcase \"build\":\n\t\t\tbuildCmd.Parse(os.Args[pos+1:])\n\t\t\tif *buildOutputDir != \"\" {\n\t\t\t\tparsingArgument = true\n\t\t\t}\n\t\t\tif *buildBaseURL != \"\" {\n\t\t\t\tparsingArgument = true\n\t\t\t}\n\t\tdefault:\n\t\t\t// If not in the middle of parsing a command-like subargument,\n\t\t\t// like the -sitename=test in this command line:\n\t\t\t// foo init -sitename=test\n\t\t\t// Where foo is the name of the program, and -sitename is\n\t\t\t// an optional subcommand to init,\n\t\t\t//\n\t\t\t// os.Args[0] falls through so exclude it, since it's\n\t\t\t// the name of the invoking program.\n\t\t\tif !parsingArgument && pos > 0{\n\t\t\t\tfilenames = append(filenames, nextArg)\n\t\t\t} else {\n\t\t\t\tparsingArgument = false\n\t\t\t}\n\n\t\t}\n\t}\n\treturn filenames\n}", "func initConfig(cmd *cobra.Command) error {\n\tv := viper.New()\n\n\tv.SetConfigName(\"pbnj\")\n\tv.AddConfigPath(\".\")\n\tif err := v.ReadInConfig(); err != nil {\n\t\t// It's okay if there isn't a config file\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); !ok {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tv.SetEnvPrefix(prefix)\n\tv.AutomaticEnv()\n\tbindFlags(cmd, v)\n\treturn nil\n}", "func init() {\n\tcobra.OnInitialize(configInit)\n\n\trootCmd.PersistentFlags().StringP(\n\t\t\"format\",\n\t\t\"f\",\n\t\t\"{{padlen .NameValue 20}}\\t{{.NotBefore}}\\t{{.NotAfter}}\",\n\t\t\"Output formatting (go template).\\n Possible items are IssuerCaID, IssuerName, \"+\n\t\t\t\"NameValue, MinCertID, MinEntryTimestamp, NotBefore, NotAfter.\\n\",\n\t)\n\trootCmd.PersistentFlags().BoolP(\"debug\", \"d\", false, \"Debug output. \")\n\trootCmd.PersistentFlags().DurationP(\"timeout\", \"t\", 50*time.Second, \"Request timeout.\")\n\trootCmd.PersistentFlags().Bool(\"only-valid\", false, \"Only display still (date) valid certificates.\")\n\n\terr := multierr.Combine(\n\t\tviper.BindPFlag(\"format\", rootCmd.PersistentFlags().Lookup(\"format\")),\n\t\tviper.BindEnv(\"format\", \"FORMAT\"),\n\t\tviper.BindPFlag(\"timeout\", rootCmd.PersistentFlags().Lookup(\"timeout\")),\n\t\tviper.BindEnv(\"timeout\", \"TIMEOUT\"),\n\t\tviper.BindPFlag(\"debug\", rootCmd.PersistentFlags().Lookup(\"debug\")),\n\t\tviper.BindEnv(\"debug\", \"DEBUG\"),\n\t\tviper.BindPFlag(\"only-valid\", rootCmd.PersistentFlags().Lookup(\"only-valid\")),\n\t\tviper.BindEnv(\"only-valid\", \"ONLY_VALID\"),\n\t)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n}" ]
[ "0.62399775", "0.61309266", "0.6130822", "0.6126474", "0.6115499", "0.59982336", "0.5931803", "0.5896063", "0.58915246", "0.5883573", "0.58612067", "0.5859795", "0.58194065", "0.57860136", "0.5749652", "0.5728792", "0.5710102", "0.5669376", "0.5669293", "0.566864", "0.5646723", "0.5644428", "0.5638034", "0.56332254", "0.5608995", "0.5580463", "0.5570934", "0.5566669", "0.55548143", "0.55360043", "0.5535653", "0.5522777", "0.5503815", "0.5493531", "0.54910696", "0.54896986", "0.54812765", "0.5478679", "0.547443", "0.54730237", "0.5471067", "0.54646057", "0.54646057", "0.54644203", "0.5456175", "0.54518294", "0.5451427", "0.5451217", "0.5449176", "0.54457784", "0.54456794", "0.5444177", "0.5441952", "0.5432669", "0.54180413", "0.54126334", "0.54053646", "0.53999704", "0.53921914", "0.53918314", "0.5382371", "0.53672415", "0.53580713", "0.53574634", "0.53489214", "0.5347959", "0.53464246", "0.5344891", "0.5325545", "0.5324152", "0.53048974", "0.529214", "0.52897274", "0.52886575", "0.5282162", "0.52803344", "0.5277354", "0.52706164", "0.5254543", "0.52351314", "0.5231535", "0.52167237", "0.5216605", "0.5216468", "0.52163", "0.5212913", "0.52118534", "0.5196024", "0.51942176", "0.5193372", "0.51804525", "0.5179837", "0.51788294", "0.5170496", "0.5168362", "0.51672703", "0.51652455", "0.5163942", "0.51590675", "0.5158506" ]
0.70132834
0
Problem 9. Palindrome Number URL:
func isPalindrome(x int) bool { y, z := 0, x // the reverse integer if x < 0 { return false } for z > 0 { y = y*10 + z%10 z /= 10 } return x == y }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func isPalindrome(num int) bool {\n numStr := strconv.Itoa(num)\n strLen := len(numStr)\n if strLen % 2 != 0 {\n return false\n }\n for i := 0; i < strLen/2; i++ {\n if numStr[strLen/2+i] != numStr[strLen/2-i-1]{\n return false\n }\n }\n return true\n}", "func main() {\n\tfmt.Println(isPalindrome(12321))\n}", "func isPalindrome(s string) bool{\n //reverse the string number\n r := make([]byte, len(s))\n for i := 0; i < len(s); i++ {\n r[i] = s[len(s)-1-i]\n }\n revString := string(r) //reverse is intially a string\n revInt, _ := strconv.Atoi(revString) //convert string to int\n origInt, _ := strconv.Atoi(s) //convert string to integer\n\n fmt.Println(origInt, revInt)\n return origInt == revInt //check if the reverse integer is equal to original\n}", "func IsPalindrome(num int) bool {\n\tstr := strconv.Itoa(num)\n\tlast := len(str) - 1\n\tfor i := 0; i < len(str)/2; i++ {\n\t\tif str[i] != str[last-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isPalindromeWithoutConcernOverflow(x int) bool {\n\tif x < 0 {\n\t\treturn false\n\t}\n\tif x == 0 {\n\t\treturn true\n\t}\n\tif x%10 == 0 {\n\t\treturn false\n\t}\n\ty := x\n\tvar rev int\n\tfor y > 0 {\n\t\trev = rev*10 + y%10\n\t\ty /= 10\n\t}\n\treturn x == rev\n}", "func isPalindrome(n int) bool {\n\ts := strconv.Itoa(n)\n\n\tfor i := 0; i < len(s)/2; i++ {\n\t\tif s[i] != s[len(s)-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func isPalindrome(x int) bool {\n\tstr := strconv.Itoa(x)\n\tr := strings.Split(str, \"\")\n\tfor i := 0; i < len(r)/2; i++ {\n\t\tif r[i] != r[len(r)-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func testLychrel(x int) bool {\n\tn := big.NewInt(int64(x))\n\tfor tries := 1; tries <= maxTries; tries++ {\n\t\tnReverse := reverse(n)\n\t\tsum := big.NewInt(0).Add(n, nReverse)\n\t\tif isPalindrome := isPalindrome(sum.String()); isPalindrome {\n\t\t\treturn false\n\t\t}\n\t\tn = sum\n\t}\n\treturn true\n}", "func isPalindrome(x int) bool {\n\n\ts := strconv.Itoa(x)\n\trunes := make([]rune, 0)\n\n\tif x < 0 {\n\t\ts = s[1:]\n\t\trunes = []rune(s)\n\t} else {\n\t\trunes = []rune(s)\n\t}\n\tfor i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {\n\t\trunes[i], runes[j] = runes[j], runes[i]\n\t}\n\n\tresult := string(runes)\n\n\tresultNum, _ := strconv.Atoi(result)\n\tif x < 0 {\n\t\tresultNum = resultNum * -1\n\t}\n\tif float64(resultNum) < math.Pow(-2, 31) || float64(resultNum) > math.Pow(2, 31) {\n\t\treturn false\n\t}\n\n\tif x < 0 {\n\t\tresult = fmt.Sprintf(\"%v%v\", result, \"-\")\n\t}\n\n\treturn result == s\n}", "func palindromable(s string) bool {\n\tbs := []byte(s)\n\tm := make(map[byte]int)\n\tfor _, b := range bs {\n\t\tm[b]++\n\t}\n\tcenter := len(bs) % 2\n\tfor _, v := range m {\n\t\tif v%2 != 0 {\n\t\t\tif center == 0 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tcenter--\n\t\t}\n\t}\n\treturn true\n}", "func isPalindrome(x int) bool {\n\tvar (\n\t\ty int\n\t\tz = x\n\t)\n\n\tfor x > 0 {\n\t\ty = y*10 + x%10\n\t\tx /= 10\n\t}\n\treturn y == z\n}", "func isPalindrome1(x int) bool {\n\tif x < 0 {\n\t\treturn false\n\t}\n\n\tvar rev int\n\tdividedx := x\n\n\tfor dividedx != 0 {\n\t\t//pop\n\t\tpop := dividedx % 10\n\t\tdividedx /= 10\n\t\t//push\n\t\trev = rev * 10 + pop\n\t}\n\n\treturn x == rev\n}", "func isP(s string) string {\n mid := len(s) / 2\n last := len(s) - 1\n for i := 0; i < mid; i++ {\n if s[i] != s[last-i] {\n return \"No this is not a Palimdrome.\"\n }\n }\n return \"Yes this is a Palindrome\"\n}", "func isPalindrome2(x int) bool {\n\tif x < 0 || (x % 10 == 0 && x != 0) {\n\t\treturn false\n\t}\n\tvar rev int\n\tfor x > rev {\n\t\t//pop and push\n\t\trev = rev * 10 + x % 10\n\t\tx /= 10\n\t}\n\t// Considering about both odd and even cases.\n\treturn x == rev || x == rev / 10\n}", "func chopPalindrome(n int) int {\n numberString := strconv.Itoa(n)\n newString := \"\"\n for i := 1; i < len(numberString) - 1; i++ {\n newString += string(numberString[i])\n }\n newPalindrome, _ := strconv.Atoi(newString)\n return newPalindrome\n}", "func isPalindrome(x int) bool {\n\tcopy_x := x\n\n\tif x < 0 {\n\t\treturn false\n\t}\n\n\trev := 0\n\n\tfor x > 0 {\n\t\trev = rev*10 + x%10\n\t\tx = x / 10\n\t}\n\n\tif rev == copy_x {\n\t\treturn true\n\t}\n\treturn false\n}", "func Palindrome(value string) bool {\n\tvar temp = \"\"\n\n\tfor i := len(value) -1; i >= 0; i-- {\n\t\ttemp = temp + string(value[i])\n\t}\n\tfmt.Println(temp)\n\tresult := temp == value\n\treturn result\n}", "func palindrome(input string) bool {\n\t//hasil akhir yg diharapkan (true/false) defaultnya false\n\tvar kembalian bool\n\n\t//menampung jumlah karakter yang sama\n\tvar nilai int\n\n\t//panjang dari inputan ( jumlah karakternya )\n\tvar karakter int = len(input)\n\n\tfor i := 0; i < karakter; i++ {\n\t\t//misalkan karakter pertama dan terakhir sama, maka variabel nilai bertambah\n\t\tif input[i] == input[karakter-(i+1)] {\n\t\t\tnilai++\n\t\t}\n\t}\n\t//jika jumlah karakter input dan jumlah karakter yg sama sesuai maka true\n\tif nilai == karakter {\n\t\tkembalian = true\n\t}\n\treturn kembalian\n}", "func AnswerABC198Bその1(N int) string {\n\tfor i := 0; i <= 9; i++ {\n\t\tzeros := \"\"\n\t\tfor j := 0; j < i; j++ {\n\t\t\tzeros += \"0\"\n\t\t}\n\n\t\tif lib.IsPalindrome(zeros + strconv.Itoa(N)) {\n\t\t\treturn \"Yes\"\n\t\t}\n\t}\n\n\treturn \"No\"\n}", "func isPalindrome(x int) bool {\n\tif x < 0 || (x != 0 && x%10 == 0) {\n\t\treturn false\n\t}\n\treverse := 0\n\tfor x > reverse {\n\t\treverse = reverse*10 + x%10\n\t\tx /= 10\n\t}\n\n\treturn x == reverse || x == reverse/10\n}", "func isPalindrome(num int) bool {\n\tif num < 0 {\n\t\treturn false\n\t}\n\treturn num == reverseInt(num)\n}", "func reducePalindrome(n int) int {\n numberString := strconv.Itoa(n)\n length := len(numberString)\n midlen := length / 2\n reduceValueString := \"\"\n\n if length % 2 == 1 {\n reduceValueString += \"1\"\n for i := midlen + 1; i < length; i++ {\n reduceValueString += \"0\"\n }\n } else {\n reduceValueString += \"11\"\n for i := midlen + 1; i < length; i++ {\n reduceValueString += \"0\"\n }\n }\n reduceValue, _ := strconv.Atoi(reduceValueString)\n\n // if length % 2 == 1 {\n // carryString := \"\"\n // if string(numberString[midlen]) == \"0\" {\n // string(numberString[midlen]) = \"9\"\n // }\n // } else {\n\n // }\n\n return reduceValue\n}", "func isPalindrome(x string) bool {\n\trunes := []rune(x)\n\truneCount := len(runes)\n\tfor i := 0; i < runeCount/2; i++ {\n\t\tif runes[i] != runes[runeCount-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isPalindrome(s string) bool {\n\tn := len(s)\n\tfor i := 0; i < (n / 2); i++ {\n\t\tif s[i] != s[n-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func isPalindrome(input string) bool {\n\n\tletters := splitInput(input)\n\n\tleftPointer := 0\n\trightPointer := len(letters) - 1\n\tres := true\n\tfor true {\n\t\tif leftPointer >= rightPointer {\n\t\t\tbreak\n\t\t}\n\n\t\tif letters[leftPointer] == letters[rightPointer] {\n\t\t\tleftPointer++\n\t\t\trightPointer--\n\t\t} else {\n\t\t\tres = false\n\t\t\tbreak\n\t\t}\n\n\t}\n\treturn res\n}", "func IsPalindrome(x int) bool {\n\tif x < 0 {\n\t\treturn false\n\t}\n\tints := make([]int, 0)\n\tfor x != 0 {\n\t\tints = append(ints, x%10)\n\t\tx = x / 10\n\t}\n\tlength := len(ints)\n\tfor i := 0; i < length/2; i++ {\n\t\t//fmt.Printf(\"v1: %v v2: %v\\n\", ints[i], ints[length-i-1])\n\t\tif ints[i] != ints[length-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func PalindromesNaive(text string) (int, int) {\n\tllen, tlen := 0, len(text)\n\tif tlen > 1 {\n\t\tllen = 2*tlen + 1\n\t}\n\tlengths := make([]int, llen)\n\tfor i := 0; i < llen; i++ {\n\t\tstart := i / 2\n\t\tend := start + i%2\n\t\tfor start > 0 && end < tlen && text[start-1] == text[end] {\n\t\t\tstart -= 1\n\t\t\tend += 1\n\t\t\tlengths[i] = end - start\n\t\t}\n\t\tlengths[i] = end - start\n\t}\n\treturn LargestStartEnd(lengths)\n}", "func palindrome(str string) bool {\n\treturn false\n}", "func palindrome(n int) int {\n\tst := int(math.Pow10(n)) - 1\n\tmx := 0\n\tfor i := st; i > 0; i-- {\n\t\tif i*st <= mx {\n\t\t\tbreak\n\t\t}\n\t\tfor j := st; j > 0; j-- {\n\t\t\tpd := i * j\n\t\t\tif pd < mx {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif pd > mx && isPalindrome(pd) {\n\t\t\t\tmx = pd\n\t\t\t}\n\t\t}\n\t}\n\treturn mx\n}", "func isPalindrome(s string) bool {\n\t// defer timeTrack(time.Now(), \"isPalindrome()\")\n\n\tfor i := 0; i < len(s)/2; i++ {\n\t\tif s[i] != s[len(s)-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isPalindrome(s string) bool {\n\t// defer timeTrack(time.Now(), \"isPalindrome()\")\n\n\tfor i := 0; i < len(s)/2; i++ {\n\t\tif s[i] != s[len(s)-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func IsPalindrome(x int) bool {\n\tif x < 0 {\n\t\treturn false\n\t}\n\n\t// x should be in range of -2^31 to 2^31 - 1\n\tif x > 2147483647 { //|| x < -2147483648 {\n\t\treturn false\n\t}\n\n\tif x >= 0 && x <= 9 {\n\t\treturn true\n\t}\n\n\tvar reverse int = 0\n\ttemp := x\n\t// reverse digit\n\tfor x > 0 {\n\t\tfloat := x % 10 // use last digit\n\t\treverse *= 10 // move digit\n\t\treverse += float // assign new value to that digit\n\t\tx /= 10 // cut last digit to calculate next\n\t}\n\n\tif temp == reverse {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func isP(s string) string {\n\tmid := len(s) / 2\n\tlast := len(s) - 1\n \n\tfor i := 0; i < mid; i++ {\n\t\tif s[i] != s[last-i] {\n\t\t\treturn \"NO. It's not a Palindrome.\"\n\t\t}\n\t}\n\t\n\treturn \"YES! You've entered a Palindrome\"\n}", "func CheckPalindrome(str string) bool {\n\ti := 0\n\tj := len(str) - 1\n\tfor i < j && str[i] == str[j] {\n\t\ti++\n\t\tj--\n\t}\n\tif i < j {\n\t\treturn false\n\t}\n\treturn true\n}", "func isPalindrome(x int) bool {\n\tif x == 0 {\n\t\treturn true\n\t}\n\tif x < 0 {\n\t\treturn false\n\t}\n\tl := []int{}\n\tfor {\n\t\tbalance := x % 10\n\t\tl = append(l, balance)\n\t\tx = (x - balance) / 10\n\t\tif x == 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tr := make([]int, len(l))\n\tj := 0\n\tfor i := len(l) - 1; i >= 0; i-- {\n\t\tr[i] = l[j]\n\t\tj++\n\t}\n\n\tfor i, v := range l {\n\t\tif r[i] != v {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isP(s string) string {\n\tmid := len(s) / 2\n\tlast := len(s) - 1\n\n\tfor i := 0; i < mid; i++ {\n\t\n\t//printed if string is not a palindrome\n\tif s[i] != s[last-i] {\n\t\treturn \"NO. It's not a Palimdrome.\"\n \t}\n}\n //printed if string is a paindrome\n return \"YES! You've entered a Palindrome\"\n}", "func IsPalindrome(x int) bool {\n\tif x < 0 {\n\t\treturn false\n\t}\n\tif x < 10 {\n\t\treturn true\n\t}\n\t// 先求出总共有多少位\n\tn := 2\n\tfor {\n\t\tif x/int(math.Pow10(n)) < 1 {\n\t\t\tbreak\n\t\t}\n\t\tn++\n\t}\n\t// 比较对称位上的值是否相等\n\tfor i, j := 1, n; i <= n/2; i, j = i+1, n+1-i {\n\t\tr := (x % int(math.Pow10(i))) / int(math.Pow10(i-1))\n\t\tl := (x % int(math.Pow10(j))) / int(math.Pow10(j-1))\n\n\t\tif r != l {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func IsPalindrome(value string) bool {\n\n\tlength := len(value)\n\n\tfor i := 0; i < length/2; i++ {\n\t\tif value[i] != value[length-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}", "func validPalindrome(s string) bool {\n return validPalindromeDeleted(s, false)\n}", "func isPalindrome(s string) bool {\n\ts = cleanString(s)\n\n\ti := 0\n\tj := len(s) - 1\n\tfor i < j {\n\t\tif s[i] != s[j] {\n\t\t\treturn false\n\t\t}\n\t\ti += 1\n\t\tj -= 1\n\t}\n\n\treturn true\n}", "func Palindrome(str string) bool {\n\tj := len(str) - 1\n\n\tfor i := 0; i != j; i++ {\n\t\tif str[i] != str[j] {\n\t\t\treturn false\n\t\t}\n\t\tj--\n\t}\n\n\treturn true\n}", "func URLifyn(s string, n int) string {\n\tspaces := 0\n\tfor _, c := range s {\n\t\tif c == ' ' {\n\t\t\tspaces++\n\t\t}\n\t}\n\n\tindex := n + spaces*2\n\trunes := make([]rune, n+spaces*2)\n\n\tfor i := n - 1; i >= 0; i-- {\n\t\tif s[i] == ' ' {\n\t\t\trunes[index-1] = '0'\n\t\t\trunes[index-2] = '2'\n\t\t\trunes[index-3] = '%'\n\t\t\tindex = index - 3\n\t\t} else {\n\t\t\trunes[index-1] = rune(s[i])\n\t\t\tindex--\n\t\t}\n\t}\n\n\treturn string(runes)\n}", "func isPalindrome(listOfNumbers [6]int,numberDigits int ) bool {\n\n\tisValid := true \t\t // initiate return value\n\n\tfor i := 0 ; i < numberDigits ; i++ { // loop through array size\n\n\t\tif listOfNumbers[i] != listOfNumbers[(numberDigits - 1)-i] { \t // compare first element of array with its mirrored index value\n\n\t\t\tisValid = false \t // if not the same then it is not a palindrome\n\t\t}\n\t}\n\treturn isValid\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t // return if is palindrome\n}", "func isP(s string) string {\n mid := len(s) / 2 //calculates the midpoint of the slice\n last := len(s) - 1 //calculates the end of the slice like an array (arrays begin at 0 not 1)\n for i := 0; i < mid; i++ {//if a letter greater <blank> \n if s[i] != s[last-i] { //compares the slices\n return \"NO. It's not a Palimdrome.\" //displays if false\n }\n }\n return \"YES! You've entered a Palindrome\" //displays if true\n\n}", "func isPalindrome(s string) bool {\n\ts = strings.ToLower(s)\n\tvar str []rune\n\tfor _, ch := range s {\n\t\tif unicode.IsLetter(ch) || unicode.IsDigit(ch) {\n\t\t\tstr = append(str, ch)\n\t\t}\n\t}\n\n\tfor i := 0; i < len(str)/2; i++ {\n\t\tif str[i] != str[len(str)-i-1] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isP(s string) string {\n\tmid := len(s) / 2\n\tlast := len(s) - 1\n\tfor i := 0; i < mid; i++ { //checks if the last letter and the first letter are the same\n\t\tif s[i] != s[last-i] { // then moves on and check2nd letter and 2nd last letter and ect...\n\t\t\treturn \"NO. It's not a Palimdrome.\"\n\t\t}\n\t}\n\treturn \"YES! You've entered a Palindrome\"\n}", "func CheckPlindromePermutation(s string) bool {\n\ttable := [128]int{} // Assumption\n\toddCount := 0\n\n\tfor _, c := range s {\n\t\tif c == ' ' {\n\t\t\tcontinue\n\t\t}\n\n\t\ttable[c]++\n\t\tif table[c]%2 == 0 {\n\t\t\toddCount--\n\t\t} else {\n\t\t\toddCount++\n\t\t}\n\t}\n\n\tif oddCount > 1 {\n\t\treturn false\n\t}\n\treturn true\n}", "func Palindrome(input string) bool {\n\tinputIsPalindrome := true\n\tlength := len(input)\n\n\tfor i := 0; i < length; i++ {\n\t\tif input[i] != input[length-i-1] {\n\t\t\tinputIsPalindrome = false\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn inputIsPalindrome\n}", "func isPalindrome(s string) bool {\n\treturn helper([]rune(s))\n}", "func isPalindrome(s string, i, j int) bool {\n\tfor ; i < j; i, j = i+1, j-1 {\n\t\tif s[i] != s[j] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func palindromeSummer(n int) int {\n\tvar sum int\n\tvar listNum []int\n\t// Outer loop, every time the inner loop will have one fewer number to sum over\n\tfor i := 1; float64(i) < math.Sqrt(float64(n)); i++ {\n\t\tvar numToTest int\n\t\tnumToTest += i * i\n\t\tfor j := i + 1; float64(j) < math.Sqrt(float64(n)); j++ {\n\t\t\tnumToTest += j * j\n\t\t\t// Exit loop if numToTest is larger than n\n\t\t\tif numToTest > n {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// Convert the number to be tested into a string\n\t\t\tstr := fmt.Sprint(numToTest)\n\t\t\t// Create a flag to test if str is a palindrome\n\t\t\tpalindromeFlag := true\n\t\t\tif len(str) > 1 { // palindromeFlag is automatically true if numToTest is a single digit (1^2 + 2^2)\n\t\t\t\tfor k := 0; k <= len(str)/2-1; k++ {\n\t\t\t\t\tif str[len(str)-k-1] != str[k] {\n\t\t\t\t\t\tpalindromeFlag = false\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If palindromeFlag is true and we don't already have that number in our list, we add numToTest to sum\n\t\t\tlistFlag := true\n\t\t\tfor _, listElement := range listNum {\n\t\t\t\tif numToTest == listElement {\n\t\t\t\t\tlistFlag = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\tif palindromeFlag && listFlag {\n\t\t\t\tsum += numToTest\n\t\t\t\tlistNum = append(listNum, numToTest)\n\t\t\t}\n\t\t}\n\t}\n\treturn sum\n}", "func palindrome(s string) bool {\n\tleft := 0\n\tright := len(s) - 1\n\n\tfor left < right {\n\t\tif s[left] != s[right] {\n\t\t\treturn false\n\t\t}\n\t\tleft++\n\t\tright--\n\t}\n\treturn true\n}", "func IsPalindrome(s string) string {\t\n\n\tletters := []string{} //get only lowercase letters\n\n\tfor _, char := range s {\n\t\tif unicode.IsLetter(rune(char)){\n\t\t\tletters = append(letters, string(unicode.ToLower(char)))\n\t\t}\n\t}\n\tfor i := 0; i < len(letters); i++ {\n\t\tif letters[i] != letters[len(letters)-i-1] {\n\t\t\treturn \"false\"\n\t\t}\n\t}\n\treturn \"true\"\t\n}", "func breakPalindrome(s string) string {\n\tn := len(s)\n\tmodable := n / 2\n\tif modable == 0 {\n\t\treturn \"\"\n\t}\n\n\tvar sb strings.Builder\n\ti := 0\n\tfor ; i < modable && s[i] == 'a'; i++ {\n\t\tsb.WriteByte('a')\n\t}\n\n\tif i == modable {\n\t\tif n%2 == 1 {\n\t\t\tsb.WriteByte(s[modable])\n\t\t}\n\n\t\tif modable+1 < n-1 {\n\t\t\tsb.WriteString(s[modable+1:n-1])\n\t\t}\n\n\t\tsb.WriteByte('b')\n\t} else {\n\t\tsb.WriteByte('a')\n\t\tsb.WriteString(s[i+1:])\n\t}\n\n\treturn sb.String()\n}", "func IsPalindrome(s string) bool {\n\tfor i := range s {\n\t\tif s[i] != s[len(s)-1-i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func Soal2(sentence string) {\n\tresult := isPalindrome(sentence)\n\tfmt.Print(\"Problem 2 \")\n\tprinted := fmt.Sprintf(\"input: '%v', return: %v\", sentence, result)\n\tfmt.Println(printed)\n}", "func main() {\n\tk := 3\n\ts := \"aabbaa\"\n\tres := kpalindromes.Kpalindromes(k, s)\n\tfmt.Println(res)\n}", "func palindromeSol1(str string) bool {\n\trightPtr := len(str) - 1\n\tleftPtr := 0\n\tspace := rune(' ')\n\tfor rightPtr < len(str)/2 {\n\t\tright := rune(str[rightPtr])\n\t\tleft := rune(str[leftPtr])\n\t\t// Handle white space\n\t\tif right == space {\n\t\t\trightPtr++\n\t\t\tcontinue\n\t\t}\n\t\tif left == space {\n\t\t\tleftPtr--\n\t\t\tcontinue\n\t\t}\n\t\tif right != left {\n\t\t\treturn false\n\t\t}\n\t\tleftPtr--\n\t\trightPtr++\n\t}\n\treturn true\n}", "func checkPalindromePermutation(str string) bool {\n\tchars := strings.Split(str, \"\")\n\tcharMap := make(map[string]int)\n\tfor _, char := range chars {\n\t\tcharMap[char] += 1\n\t}\n\tnonUniqueChars := 0\n\tfor _, value := range charMap {\n\t\tif value%2 == 1 {\n\t\t\tnonUniqueChars++\n\t\t}\n\t}\n\treturn nonUniqueChars <= 2\n}", "func palindromeIndex(s string) int {\n\tn := len(s)\n\tfor i := 0; i < n/2; i++ {\n\t\t// problem, find which index\n\t\t// is at fault.\n\t\tif s[i] != s[n-i-1] {\n\t\t\tif palindrome(s[:i] + s[i+1:]) {\n\t\t\t\treturn i\n\t\t\t} else {\n\t\t\t\treturn n - i - 1\n\t\t\t}\n\t\t}\n\t}\n\treturn -1\n}", "func isPalindrome(str string) bool {\n\tvar reverse string\n\tfor _, char := range str {\n\t\treverse = string(char) + reverse\n\t}\n\treturn reverse == str\n}", "func isPalindromeRecursive(value string, i int) bool {\n\tif i < len(value) /2 {\n\t\tvar firstIndex = i\n\t\tvar lastIndex = len(value) - i -1\n\t\t//compare per index\n\t\tfmt.Println(string(value[firstIndex]) , \" : \" , string(value[lastIndex]))\n\n\t\tif string(value[firstIndex]) != string(value[lastIndex]) {\n\t\t\tfmt.Println(\"Palindrome recursive false\")\n\t\t\treturn false\n\t\t} else {\n\t\t\t//if true call again the recursive, and add 1 for i var\n\t\t\treturn isPalindromeRecursive(value, i+1)\n\t\t}\n\t} else {\n\t\tfmt.Println(\"Palindrome recursive true\")\n\t\treturn true\n\t}\n}", "func isPalindrome125(s string) bool {\n\tn := len(s)\n\tif s == \"\" {\n\t\treturn true\n\t}\n\tl, r := 0, n-1\n\tfor l < r {\n\t\tlv, rv := rune(s[l]), rune(s[r])\n\t\tif !unicode.IsNumber(lv) && !unicode.IsLetter(lv) {\n\t\t\tl++\n\t\t\tcontinue\n\t\t}\n\t\tif !unicode.IsNumber(rv) && !unicode.IsLetter(rv) {\n\t\t\tr--\n\t\t\tcontinue\n\t\t}\n\t\tif unicode.ToLower(lv) != unicode.ToLower(rv) {\n\t\t\treturn false\n\t\t}\n\t\tl++\n\t\tr--\n\t}\n\treturn true\n}", "func IsPalindromePermutation1(str string) bool {\n\tvar charMap [256]int\n\tfor _, c := range str {\n\t\tcharMap[int(c)]++\n\t}\n\n\tfoundOneOdd := false\n\tfor _, i := range charMap {\n\t\tif i%2 != 0 {\n\t\t\tif !foundOneOdd {\n\t\t\t\tfoundOneOdd = true\n\t\t\t} else {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\treturn true\n}", "func palindrome(str string) bool {\n\tsplitStr := strings.Split(str, \"\")\n\tfor i, j := 0, len(splitStr) - 1; i < j; i, j = i + 1, j - 1 {\n\t\tif splitStr[i] != splitStr[j] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true \n}", "func IsPalindrome(s sort.Interface) bool {\n\t// TODO\n\treturn false\n}", "func longestPalindrome(s string) string {\n\n}", "func IterIsPalyn(s string) bool {\r\n n := len(s)\r\n for i := 0;i < n / 2;i++ {\r\n if s[i] != s[n - i - 1] {\r\n return false\r\n }\r\n }\r\n return true\r\n}", "func IsPalindromePermutation2(str string) bool {\n\tvar charMap [256]int\n\tcountOdd := 0\n\tfor _, c := range str {\n\t\tcharMap[int(c)]++\n\t\tif charMap[int(c)]%2 != 0 {\n\t\t\tcountOdd++\n\t\t} else {\n\t\t\tcountOdd--\n\t\t}\n\t}\n\treturn countOdd <= 1\n}", "func hashLink(url string) (res string) {\n\tres = strconv.FormatInt(int64((crc64.Checksum([]byte(url+\"321_SeCReT_KeyFoR_SaLT_123\"), crc64.MakeTable(crc64.ISO)))), 36)\n\tif matched, _ := regexp.Match(\"-[1-9].*\", []byte(res)); matched {\n\t\ttransform, _ := strconv.Atoi(string(res[1]))\n\t\tres = string(byte(65+transform)) + res[2:]\n\t}\n\treturn\n}", "func Problem0004() int {\n\tlargest := 0\n\tfor a := 999; a >= 100; a-- {\n\t\tfor b := 999; b >= a; b-- {\n\t\t\tnum := a * b\n\t\t\tif num > largest && isPalindrome(num) {\n\t\t\t\tlargest = num\n\t\t\t}\n\t\t}\n\t}\n\treturn largest\n}", "func CheckPlindromePermutation2(s string) bool {\n\tvar table int64\n\tfor _, c := range s {\n\t\tif c == ' ' {\n\t\t\tcontinue\n\t\t}\n\n\t\tmask := int64(1 << uint(c-'A'))\n\t\tif table&mask == 0 {\n\t\t\ttable |= mask\n\t\t} else {\n\t\t\ttable ^= mask\n\t\t}\n\t}\n\n\tif table == 0 || (table-1)&table == 0 {\n\t\treturn true\n\t}\n\n\treturn false\n}", "func main() {\n\tfmt.Println(longestPalindrome(\"babad\"))\n}", "func Problem36() uint64 {\n\tvar i uint64 = 2\n\tvar sum uint64 = 0\n\tfor i < 1000000 {\n\t\tif IsNumberPalindrome(i) && IsBinaryNumberPalindrome(i) {\n\t\t\tsum += i\n\t\t}\n\t\ti++\n\t}\n\treturn sum\n}", "func buildPalindrome(s string, left int, right int) string {\n\tfor right < len(s) && left >= 0 && s[left] == s[right] {\n\t\tleft--\n\t\tright++\n\t}\n\n\treturn string(s[left+1 : right])\n}", "func palindromeIndex(s string) int32 {\n\tl := len(s) - 1\n\tfor i := 0; i <= l; i, l = i+1, l-1 {\n\t\tif s[i] == s[l] {\n\t\t\tcontinue\n\t\t}\n\t\tif palindrome(s[i+1 : l+1]) {\n\t\t\treturn int32(i)\n\t\t}\n\t\tif palindrome(s[i:l]) {\n\t\t\treturn int32(l)\n\t\t}\n\t\treturn -1\n\t}\n\treturn -1\n}", "func findSumOfDualPalindromes(lim int) int {\n\tdefer timeTrack(time.Now(), \"findSumOfDualPalindromes()\")\n\n\tsum := 0\n\tfor i := 1; i < lim; i++ {\n\t\tbase10 := strconv.FormatInt(int64(i), 10)\n\t\tif isPalindrome(base10) == false {\n\t\t\tcontinue\n\t\t}\n\t\tbase2 := strconv.FormatInt(int64(i), 2)\n\t\tif isPalindrome(base2) == false {\n\t\t\tcontinue\n\t\t}\n\t\t// p(base10, \" : \", base2)\n\t\tsum += i\n\t}\n\treturn sum\n}", "func LongestPalindrome(str string) string {\n l := len(str)\n odd := make([]bool, l)\n even := make([]bool, l)\n var oddRadius, evenRadius, oddCenter, evenCenter int\n for radius := 0; radius <= l/2; radius++ {\n for c := 0; c < l; c++ {\n if radius == 0 {\n odd[c] = true\n even[c] = true\n } else {\n if c-radius >= 0 && c+radius < l {\n odd[c] = odd[c] && (str[c-radius] == str[c+radius])\n } else {\n odd[c] = false\n }\n if c-radius+1 >= 0 && c+radius < l {\n even[c] = even[c] && (str[c-radius+1] == str[c+radius])\n } else {\n even[c] = false\n }\n }\n if odd[c] && radius > oddRadius {\n oddRadius = radius\n oddCenter = c\n }\n if even[c] && radius > evenRadius {\n evenRadius = radius\n evenCenter = c\n }\n }\n }\n if oddRadius >= evenRadius {\n return str[oddCenter-oddRadius: oddCenter+oddRadius+1]\n } else {\n return str[evenCenter-evenRadius+1: evenCenter+evenRadius+1]\n }\n}", "func PalindromeComparePerChar(value string) bool {\n\tfor i := 0; i < len(value) / 2; i++ {\n\t\tvar firstIndex = i\n\t\tvar lastIndex = len(value) - i -1\n\t\t//compare per index\n\t\tfmt.Println(string(value[firstIndex]) , \" : \" , string(value[lastIndex]))\n\n\t\tif string(value[firstIndex]) != string(value[lastIndex]) {\n\t\t\tfmt.Println(\"Palindrome false\")\n\t\t\treturn false\n\t\t}\n\t}\n\tfmt.Println(\"Palindrome true\")\n\treturn true\n}", "func UTF8Palindrome(s string) bool {\n\tfor utf8.RuneCountInString(s) > 1 {\n\t\tfirstRune, firstSize := utf8.DecodeRuneInString(s)\n\t\tlastRune, lastSize := utf8.DecodeLastRuneInString(s)\n\n\t\tif unicode.ToLower(firstRune) != unicode.ToLower(lastRune) {\n\t\t\treturn false\n\t\t}\n\n\t\ts = s[firstSize : len(s)-lastSize]\n\t}\n\treturn true\n}", "func ASCIIPalindrome(s string) bool {\n\ti := 0\n\tj := len(s) - 1\n\n\tfor i < j {\n\t\tfor !(unicode.IsDigit(rune(s[i])) || unicode.IsLetter(rune(s[i]))) {\n\t\t\ti++\n\t\t}\n\t\tfor !(unicode.IsDigit(rune(s[j])) || unicode.IsLetter(rune(s[j]))) {\n\t\t\tj--\n\t\t}\n\n\t\tletterI := unicode.ToLower(rune(s[i]))\n\t\tletterJ := unicode.ToLower(rune(s[j]))\n\t\tif letterI != letterJ {\n\t\t\treturn false\n\t\t}\n\n\t\ti++\n\t\tj--\n\t}\n\treturn true\n}", "func Test_S9(t *testing.T) {\n\ttests := []struct {\n\t\tArgsX int\n\t\tResult bool\n\t}{\n\t\t{\n\t\t\tArgsX: 121,\n\t\t\tResult: true,\n\t\t}, {\n\t\t\tArgsX: -121,\n\t\t\tResult: false,\n\t\t}, {\n\t\t\tArgsX: 10,\n\t\t\tResult: false,\n\t\t}, {\n\t\t\tArgsX: -101,\n\t\t\tResult: false,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(\"Test_S9\", func(t *testing.T) {\n\t\t\tresult := isPalindrome(test.ArgsX)\n\t\t\tt.Logf(\"x: %d, expected expectedResult: %v, run expectedResult: %v\", test.ArgsX, test.Result, result)\n\t\t\tif result != test.Result {\n\t\t\t\tt.Fatalf(\"Failed\")\n\t\t\t}\n\t\t})\n\t}\n}", "func Utama(x string) int {\n\tinputNum := strings.Split(x, \" \") // The string input value will be convert to Array\n\tarrayInput := make([]int, len(inputNum))\n\n\tfor i := range arrayInput {\n\t\tarrayInput[i], _ = strconv.Atoi(inputNum[i]) // The conversion from String to Integer will be done here\n\t}\n\tcount := 0\n\n\tfor i := arrayInput[0]; i <= arrayInput[1]; i++ {\n\t\tstartingPoint := i\n\t\tresult := reverse(i) // This line refers to \"func reverse\" on bellow\n\n\t\tif startingPoint == result {\n\t\t\tcount += 1 // Everytime startingPoint value matched with the Result, it will increase the Count value by 1\n\t\t}\n\t}\n\treturn count // The result of Counted Palindrome\n}", "func IsPalindromePermutation(s string) bool {\n\tinput := make([]rune, 0, len(s))\n\tfor _, r := range strings.ToLower(s) {\n\t\tif unicode.IsLetter(r) {\n\t\t\tinput = append(input, r)\n\t\t}\n\t}\n\n\tcounts := make(map[rune]int)\n\tfor _, r := range input {\n\t\tcounts[r]++\n\t}\n\n\tfoundOddCount := false\n\tfor _, c := range counts {\n\t\tif c%2 == 1 {\n\t\t\tif foundOddCount {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfoundOddCount = true\n\t\t}\n\t}\n\treturn true\n}", "func main() {\n\ts := \"abccccdd\"\n\tfmt.Println(longestPalindrome(s))\n}", "func palindromePermutation(s string) bool {\n\t// for all permutations\n\tccount := make(map[rune]int)\n\tfor _, c := range s {\n\t\tif c != ' ' {\n\t\t\tccount[c]++\n\t\t}\n\t}\n\n\t// more than 1 odd char means this cannot be a palindrome\n\todd := 0\n\tfor _, v := range ccount {\n\t\tif v%2 != 0 {\n\t\t\todd++\n\t\t\tif odd > 1 {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}", "func PalindromesFast(text string) (int, int) {\n\tlengths := make([]int, 2*len(text)+1)\n\ti, j, d, s, e, plen, k := 0, 0, 0, 0, 0, 0, 0\n\tfor i < len(text) {\n\t\t// is the string so far a palindrome ?\n\t\tif i > plen && text[i-plen-1] == text[i] {\n\t\t\t// yes, so we extend the current found palindrome length\n\t\t\t// and keep checking forward else ...\n\t\t\tplen += 2\n\t\t\ti++\n\t\t\tcontinue\n\t\t}\n\t\t// ... we have reached the end of the current found palindrome\n\t\t// so we set the current palindrome length etc. ...\n\t\tlengths[k] = plen\n\t\tk++\n\t\ts = k - 2\n\t\te = s - plen\n\t\t// ... then backtrack over the last found palindrome to see ...\n\t\tb := true\n\t\tfor j = s; j > e; j-- {\n\t\t\td = j - e - 1\n\t\t\t// ... if we have a reflection of the same length ...\n\t\t\tif lengths[j] == d {\n\t\t\t\t// ... yes, so we set new palindrome length ...\n\t\t\t\tplen = d\n\t\t\t\t// ... and stop backtracking.\n\t\t\t\tb = false\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// ... no, so we take the smaller length,\n\t\t\t// update the lengths and continue backtracking.\n\t\t\tlengths[k] = MinInt(d, lengths[j])\n\t\t\tk++\n\t\t}\n\t\t// if we we're backtracking then reset palindrome length\n\t\t// and move on.\n\t\tif b {\n\t\t\tplen = 1\n\t\t\ti++\n\t\t}\n\t}\n\t// we're done scanning the text so we perform\n\t// one last backtrack.\n\tlengths[k] = plen\n\tk++\n\ts = k - 2\n\te = s - (2*len(text) + 1 - k)\n\tfor i := s; i > e; i-- {\n\t\td = i - e - 1\n\t\tlengths[k] = MinInt(d, lengths[i])\n\t\tk++\n\t}\n\treturn LargestStartEnd(lengths)\n}", "func P004Solve() int {\n\tresult := 0\n\tconst finish = 999\n\tconst start = 99\n\ti := finish\n\n\tfor ; i > start; i-- {\n\n\t\tfor j := finish; j > start; j-- {\n\n\t\t\tnumber := i * j\n\t\t\tif (number > result) && isPalindromic(number) {\n\t\t\t\tresult = number\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result\n}", "func Valid(s string) bool {\n\tn := removeSpace(s)\n\tl := make([]byte, len(n))\n\t// fmt.Printf(\"%s --> %s, len: %d\", string(l), n, len(l))\n\todd := len(n) & 1\n\tif len(l) <= 1 {\n\t\treturn false\n\t}\n\tp := 0\n\tresult := 0\n\tfor x := 0; x < len(n); x++ {\n\t\tnumber := rune(n[x])\n\t\ti, err := strconv.Atoi(string(number))\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\n\t\tif err == nil {\n\t\t\tif (p+odd)%2 == 0 {\n\t\t\t\ti = i * 2\n\t\t\t\tif i > 9 {\n\t\t\t\t\ti = i - 9\n\t\t\t\t}\n\t\t\t}\n\t\t\td := strconv.Itoa(i)\n\t\t\tl[p] = d[0]\n\t\t\tp++\n\t\t}\n\t\tresult += i\n\t}\n\tl = l[:p]\n\n\treturn result%2 == 0\n\n}", "func isPalindrome(head *ListNode) bool {\n\tif head == nil {\n\t\treturn true\n\t}\n\tslow, fast := head, head\n\tfor fast.Next != nil && fast.Next.Next != nil {\n\t\tslow = slow.Next\n\t\tfast = fast.Next.Next\n\t}\n\treverse(slow)\n\tfor head != nil && slow != nil {\n\t\tif head.Val == slow.Val {\n\t\t\thead = head.Next\n\t\t\tslow = slow.Next\n\t\t} else {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}", "func isPalindrome(head *ListNode) bool {\n\tvar length int\n\t// cal linked length\n\tp := head\n\tfor p != nil {\n\t\tlength++\n\t\tp = p.Next\n\t}\n\treturn recursionLinked2(head, head, 1, length)\n}", "func exercise8() {\n input := utils.GetDefaultInput()\n reverse := Reverse(input)\n fmt.Println(\"The reverse is\", reverse)\n}", "func IsPalindrome(s sort.Interface) bool {\n\tif s.Len() == 0 {\n\t\treturn false\n\t}\n\tleft := 0\n\tright := s.Len() - 1\n\tfor left < right {\n\t\tif s.Less(left, right) || s.Less(right, left) {\n\t\t\treturn false\n\t\t}\n\t\tleft++\n\t\tright--\n\t}\n\treturn true\n}", "func test() {\n\to := decode(\"101\")\n\tfmt.Println(o, \"== 1\")\n\to = decode(\"111\")\n\tfmt.Println(o, \"== 3\")\n\to = decode(\"12\")\n\tfmt.Println(o, \"== 2\")\n\to = decode(\"27\")\n\tfmt.Println(o, \"== 1\")\n}", "func minPalindrome(s string) string {\n\ttype key struct {\n\t\ta string // current string\n\t\tr string // prefix+suffix\n\t\tx int // moves required\n\t}\n\tvar cache = make(map[key]result)\n\tvar rec func(a string, r string, x int) result\n\trec = func(a string, r string, x int) result {\n\t\t// Termination condition.\n\t\tn := len(a)\n\t\tif n <= 1 {\n\t\t\treturn result{r + a + r, x}\n\t\t}\n\t\t// Check the cache.\n\t\tk := key{a, r, x}\n\t\tif result, ok := cache[k]; ok {\n\t\t\treturn result\n\t\t}\n\t\t// Compare a[i+1...j], a[i...j-1], and a[i+1...j+1].\n\t\tbest := rec(a[1:], a[:1], 1)\n\t\t{\n\t\t\tother := rec(a[:n-1], a[n-1:], 1)\n\t\t\tif other.beats(best) {\n\t\t\t\tbest = other\n\t\t\t}\n\t\t}\n\t\tif a[0] == a[n-1] {\n\t\t\tother := rec(a[1:n-1], a[:1], 0)\n\t\t\tif other.beats(best) {\n\t\t\t\tbest = other\n\t\t\t}\n\t\t}\n\t\t// Memoize the answer and return.\n\t\tanswer := result{r + best.s + r, best.n + x}\n\t\tcache[k] = answer\n\t\treturn answer\n\t}\n\treturn rec(s, \"\", 0).s\n}", "func (l *LinkedList) isPalindrome() bool {\n\thalfPoint := int(l.length / 2)\n\tcurrent := l.head\n\tstart := l.head\n\tfor i := halfPoint + 1; i < 0; i-- {\n\t\tcurrent = current.next\n\t}\n\t// now current points to the first element of the second half\n\t// we can reverse a new linked list with root current\n\tsecondHalf := LinkedList{head: current}\n\tsecondHalf.reverse()\n\tsecondHalfElement := secondHalf.head\n\tfor i := halfPoint + 1; i < 0; i-- {\n\t\tif start != secondHalfElement {\n\t\t\treturn false\n\t\t}\n\t\tstart = start.next\n\t\tsecondHalfElement = secondHalfElement.next\n\t}\n\treturn true\n}", "func longestPalindrome(s string) string {\n\tl := len(s)\n\tsubs := \"\"\n\tcount := 0\n\tfor i := 0; i < l; i++ {\n\t\todd := getSame(s[0:i], s[i:l])\n\t\tsingle := getSame(s[0:i], s[i+1:l])\n\n\t\tif count < odd * 2 {\n\t\t\tcount = odd *2\n\t\t\tsubs = s[i-odd:i+odd]\n\t\t}\n\n\t\tif count < single * 2 + 1 {\n\t\t\tcount = single * 2 + 1\n\t\t\tsubs = s[i-single:i+1+single]\n\t\t}\n\t}\n\treturn subs\n}", "func TestIsChinesePalindrome(t *testing.T) {\n\t// should not be\n\tss := []string{\"中\", \"ab中哈中ba\",}\n\tfor _, s := range ss {\n\t\tif !word.IsPalindrome(s) {\n\t\t\tt.Errorf(\"should be true %s \\n\", s)\n\t\t}\n\t}\n}", "func IsIntegerPalindromeFaster(i int) bool {\n\tdivisor := 1\n\tfor temp := i; temp/divisor > 10; divisor *= 10 {\n\t}\n\tfor i >= 10 {\n\t\thighest := i / divisor\n\t\tlowest := i % 10\n\t\tif highest != lowest {\n\t\t\treturn false\n\t\t}\n\t\ti %= divisor\n\t\ti /= 10\n\t\tdivisor /= 100\n\t}\n\treturn true\n}", "func GenerateInvalidURL() string {\n\tvar rawURL string\n\n\th := \"ghijklmnopqrstuvwxyz\"\n\trands := [8]byte{}\n\t_, _ = rand.Read(rands[:])\n\tfor i := 0; i < 4; i++ {\n\t\th1 := string(h[int(rands[i*2])%len(h)])\n\t\th2 := string(h[int(rands[i*2+1])%len(h)])\n\t\trawURL += \"%\" + h1 + h2\n\t}\n\n\treturn rawURL\n}" ]
[ "0.6960099", "0.6884035", "0.6664014", "0.64277637", "0.64114386", "0.63674486", "0.6257939", "0.621066", "0.61366796", "0.61073196", "0.60962695", "0.60846704", "0.60810184", "0.6079801", "0.6075255", "0.6025481", "0.59907854", "0.59879917", "0.5982325", "0.5909691", "0.59094584", "0.5897111", "0.58885294", "0.58309835", "0.58293664", "0.58081883", "0.57539123", "0.57432914", "0.57290447", "0.5709577", "0.5709577", "0.5707582", "0.56953394", "0.56902546", "0.56844455", "0.5682767", "0.56764865", "0.56692904", "0.5668545", "0.56634456", "0.5648236", "0.5644446", "0.56078804", "0.5592996", "0.55880153", "0.5535368", "0.55148304", "0.55144906", "0.5508194", "0.55009276", "0.5493957", "0.548423", "0.54731125", "0.54725516", "0.54697156", "0.54508966", "0.5436203", "0.54185414", "0.5368683", "0.536775", "0.53600615", "0.5358666", "0.5353651", "0.53481674", "0.53401375", "0.53400904", "0.5337961", "0.53355145", "0.5334036", "0.53104943", "0.53051275", "0.5297337", "0.5286375", "0.5278008", "0.5263626", "0.52590615", "0.52537423", "0.524846", "0.5234757", "0.5226222", "0.52119315", "0.52072704", "0.51931536", "0.51853603", "0.518454", "0.5162868", "0.51582503", "0.5151702", "0.5144467", "0.5131627", "0.5128115", "0.51196843", "0.50915325", "0.5079634", "0.5058377", "0.50539875", "0.5045342", "0.50439346", "0.5042642", "0.50387365" ]
0.6066814
15
NewNullHandler returns a new NullHandler.
func NewNullHandler() Handler { return &NullHandler{} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewNullHandler() *NullHandler {\n\treturn &NullHandler{}\n}", "func NewHandler(sessionHandler SessionHandler, network, address string) Handler {\n\treturn &defaultHandler{\n\t\tsessionHandler: sessionHandler,\n\t\tnetwork: network,\n\t\taddress: address,\n\t}\n}", "func NewHandler() Handler {\n\treturn Handler{}\n}", "func New() *Handler {\n\th := Handler{}\n\th.init()\n\treturn &h\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func New() *Handler {\n\treturn &Handler{\n\t\tEntries: make([]log.Entry, 0),\n\t}\n}", "func NewEmptyHandler(logger *zap.Logger) (*Handler, error) {\n\th, err := multichannelfanout.NewHandler(logger, multichannelfanout.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn NewHandler(h, logger), nil\n}", "func NewHandler() (*SimpleHandler, error) {\n\treturn &SimpleHandler{}, nil\n}", "func NewHandler(defaultTo string, defaultCode Code) *Handler {\n\treturn &Handler{\n\t\tRedirects: make(map[string]redirect),\n\t\tDefault: redirect{\n\t\t\tURL: defaultTo,\n\t\t\tCode: defaultCode,\n\t\t},\n\t}\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tentry: newEntries(),\n\t}\n}", "func NewHandler(t mockConstructorTestingTNewHandler) *Handler {\n\tmock := &Handler{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewNull() *Null {\n\treturn &Null{}\n}", "func NewNull() *Null {\n\treturn &Null{}\n}", "func New(notifier *gobrake.Notifier) *Handler {\n\th := Handler{notifier}\n\treturn &h\n}", "func New(h []IHandler) *Handler {\n\treturn &Handler{handler: h}\n}", "func NewHandler(service service.Interface) *Handler {\n\treturn &Handler{service: service}\n}", "func (h *NullHandler) Handle(err error) {\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\ttemplateStore: defaultTemplateStore,\n\t\tactions: make([]HandlerAction, 0),\n\t}\n}", "func NewHandler(hdlr interface{}) Handler {\n\treturn DefaultServer.NewHandler(hdlr)\n}", "func New(c Cache) *Handler {\n\treturn &Handler{\n\t\tcache: c,\n\t}\n}", "func NewHandler(service *Service) *Handler {\n\treturn &Handler{\n\t\tservice: service,\n\t}\n}", "func NewNullLog() *null {\n\treturn &null{}\n}", "func New(eh *exit.Handler, lgr logger.OutputIface) *Handler {\n\treturn &Handler{\n\t\tex: eh,\n\t\tLogger: lgr,\n\t\tmu: &sync.Mutex{},\n\t}\n}", "func NewHandler() sdk.Handler {\n\treturn &Handler{}\n}", "func NewHandler(service Service) Handler {\n\treturn Handler{service: service}\n}", "func New(reader Reader, ctx context.Context) *Handler {\n\treturn &Handler{\n\t\treader: reader,\n\t}\n}", "func NewHandler(newEventStream NewEventStreamHandler) *Handler {\n\treturn NewHandlerBuffered(newEventStream, 0)\n}", "func NewHandler(repository Repository) *Handler {\n\treturn &Handler{repository: repository}\n}", "func NewHandler(family *Family) *Handler {\n\treturn &Handler{\n\t\tfamily,\n\t\tmake(map[int32]HandlerFunc),\n\t\tos.Getenv(\"TP_DEBUG\") == \"true\",\n\t}\n}", "func NewHandler(storage Storage) (*handler, error) {\n\tif storage == nil {\n\t\treturn nil, ErrNilStorage\n\t}\n\treturn &handler{storage: storage}, nil\n}", "func New(betRepository BetRepository) *Handler {\n\treturn &Handler{\n\t\tbetRepository: betRepository,\n\t}\n}", "func New(logger logger.Logger) *Handler {\n\treturn &Handler{\n\t\tlogger: logger,\n\t}\n}", "func NewNull() *nullCache {\n\treturn &nullCache{}\n}", "func (t *Trigger) NewHandler(settings map[string]interface{}) *Handler {\n\n\tnewHandler := &Handler{settings: settings}\n\tt.handlers = append(t.handlers, newHandler)\n\n\treturn newHandler\n}", "func NewHandler(repository *services.CommentRepository) *Handler {\n\treturn &Handler{\n\t\tRepository: repository,\n\t}\n}", "func NewHandler(store *datastore.Datastore, running *lifecycle.Running) *Handler {\n\treturn &Handler{\n\t\tStore: *store,\n\t\tRunning: running,\n\t}\n}", "func NewHandler(clusterID string, dataType string, act Action) *Handler {\n\th := &Handler{\n\t\tdataType: dataType,\n\t\tqueue: make(chan *action.SyncData, defaultHandlerQueueSize),\n\t\tact: act,\n\t\tclusterID: clusterID,\n\t}\n\treturn h\n}", "func NewHandler(manager Manager) *Handler{\n\treturn &Handler{manager}\n}", "func NewHandler(service *comment.Service) *Handler {\n\treturn &Handler{\n\t\tService: service,\n\t}\n}", "func New(ctrl *storagecluster.Controller) *Handler {\n\treturn &Handler{\n\t\tctrl: ctrl,\n\t\tclient: ctrl.GetKubernetesClient(),\n\t\tdriver: ctrl.Driver,\n\t}\n}", "func NewHandler(folderName string) *Handler {\n\treturn &Handler{BaseDir: folderName, SplitCache: make(map[[16]byte]CacheEntry, 0)}\n}", "func NewHandler(next http.Handler) Handler {\n\treturn Handler{\n\t\tNext: next,\n\t\tLogger: JSONLogger,\n\t\tSkip: SkipHealthEndpoint,\n\t}\n}", "func NewHandler(manager Manager) *Handler {\n\treturn &Handler{manager}\n}", "func NewHandler(manager Manager) *Handler {\n\treturn &Handler{manager}\n}", "func NewHandler(manager Manager) *Handler {\n\treturn &Handler{manager}\n}", "func NewHandler(manager Manager) *Handler {\n\treturn &Handler{manager}\n}", "func NewHandler(fp string, fs http.FileSystem, fc FragmentCache) http.Handler {\n\treturn &Handler{fs, fc, fp}\n}", "func New() *Handler {\n\tp := &Handler{}\n\tp.reverseProxy = &httputil.ReverseProxy{\n\t\tTransport: &http.Transport{\n\t\t\tDial: func(network, address string) (net.Conn, error) {\n\t\t\t\treturn p.dial(context.TODO(), address)\n\t\t\t},\n\t\t},\n\t\tDirector: func(*http.Request) {\n\t\t\t// Do nothing, the request is self-sufficient\n\t\t},\n\t}\n\treturn p\n}", "func newNullEventSpool() *NullEventSpool {\n\treturn &NullEventSpool{}\n}", "func newSignalHandler() *signalHandler {\n\treturn &signalHandler{\n\t\tsignals: make(map[uint64]signalUser),\n\t\ttracer: nil,\n\t}\n}", "func NewHandler(intfs *Interfaces) infra.Handler {\n\tf := func(r *infra.Request) *infra.HandlerResult {\n\t\thandler := &handler{\n\t\t\tintfs: intfs,\n\t\t\trequest: r,\n\t\t}\n\t\treturn handler.Handle()\n\t}\n\treturn infra.HandlerFunc(f)\n}", "func NewHandler(db dal.MessageDB) *Handler {\n\treturn &Handler{\n\t\tdb: db,\n\t}\n}", "func NewHandler(h http.Handler) http.Handler {\n\treturn handler{Handler: h}\n}", "func NewMyHandler() MyHandler {\n\treturn &myHandler{}\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tdocs: map[string]*doc{},\n\t\tpkgs: &pkg{},\n\t\tbuiltins: map[string]builtin{},\n\t}\n}", "func NewHandler(handler HandlerFunc) *Handler {\n\tph := &Handler{panicChan: make(chan Info), handle: handler, mu: &sync.Mutex{}, quit: make(chan struct{})}\n\tgo ph.listen()\n\treturn ph\n}", "func NewHandler(clusterService agent.ClusterService, agentTags *agent.InfoTags, notaryService *security.NotaryService) *Handler {\n\th := &Handler{\n\t\tRouter: mux.NewRouter(),\n\t\tconnectionUpgrader: websocket.Upgrader{},\n\t\tclusterService: clusterService,\n\t\tagentTags: agentTags,\n\t}\n\n\th.Handle(\"/websocket/attach\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketAttach)))\n\th.Handle(\"/websocket/exec\", notaryService.DigitalSignatureVerification(httperror.LoggerHandler(h.websocketExec)))\n\treturn h\n}", "func NewHandler(log zerolog.Logger) func(httpserver.Handler) httpserver.Handler {\n\treturn func(next httpserver.Handler) httpserver.Handler {\n\t\treturn httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {\n\t\t\t// Create a copy of the logger (including internal context slice)\n\t\t\t// to prevent data race when using UpdateContext.\n\t\t\tl := log.With().Logger()\n\t\t\tr = r.WithContext(l.WithContext(r.Context()))\n\t\t\treturn next.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func NewHandler(srv *apix.Server) *Handler {\n\treturn &Handler{\n\t\tsrv: *srv,\n\t}\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tDeliverers: []Deliverer{},\n\t}\n}", "func (app AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(app.msKeeper, app.poaKeeper)\n}", "func NewHandler(ctx context.Context, cluster Cluster, contextDecoupler ContextDecoupler, devAddrPrefixes []types.DevAddrPrefix) *Handler {\n\treturn &Handler{\n\t\tctx: ctx,\n\t\tcluster: cluster,\n\t\tcontextDecoupler: contextDecoupler,\n\t\tdevAddrPrefixes: devAddrPrefixes,\n\t}\n}", "func New(r *mux.Router, db *sql.DB) *Handler {\n\treturn &Handler{r, db}\n}", "func NewHandler(hookURI string) *Handler {\r\n\treturn &Handler{hookURI: hookURI}\r\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tevents: []*event.Event{},\n\t}\n}", "func NewHandler() *Handler {\n\th := &Handler{\n\t\tHandler: &http.Handler{},\n\t\tProductHandler: NewProductHandler(),\n\t}\n\th.Handler.ProductHandler = h.ProductHandler.ProductHandler\n\treturn h\n}", "func newSignalHandler() *signalHandler {\n\treturn &signalHandler{\n\t\tsignals: make([]signalUser, 0, 10),\n\t\ttracer: nil,\n\t}\n}", "func NewHandler(manager Manager) *Handler {\n\treturn &Handler{Manager:manager}\n}", "func NewHandler(logger *zap.Logger, destination string) *Handler {\n\t handler := &Handler{\n\t\t logger: logger,\n\t\t dispatcher: provisioners.NewMessageDispatcher(logger.Sugar()),\n\t\t destination: destination,\n\t }\n\t // The receiver function needs to point back at the handler itself, so set it up after\n\t // initialization.\n\t handler.receiver = provisioners.NewMessageReceiver(createReceiverFunction(handler), logger.Sugar())\n \n\t return handler\n }", "func NewHandler(logger abstractlogger.Logger, client Client, executorPool ExecutorPool) (*Handler, error) {\n\treturn NewHandlerWithInitFunc(logger, client, executorPool, nil)\n}", "func NewRootHandler(dsh *DatasetHandlers, ph *PeerHandlers) *RootHandler {\n return &RootHandler{dsh, ph}\n}", "func New(lc Checker, lw Writer) *Handler {\n\treturn &Handler{\n\t\tlc: lc,\n\t\tlw: lw,\n\t}\n}", "func NewHandler() (*Handler, error) {\n\trdCloser, err := NewReaderCloser()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Handler{\n\t\treaderCloser: rdCloser,\n\t\tbufioReader: bufio.NewReader(rdCloser),\n\t}, nil\n}", "func NewHandler(logger *log.Logger, db *sql.DB) Handler {\n\treturn Handler{\n\t\tlogger: logger,\n\t\tdb: db,\n\t}\n}", "func NewHandler(service shortener.RedirectService) RedirectHandler {\n\th := &handler{\n\t\tredirectService: service,\n\t\techo: echo.New(),\n\t}\n\th.setHandlers()\n\treturn h\n}", "func Newhandler(service *comment.Service) *Handler {\n\treturn &Handler{\n\t\tService: service,\n\t}\n}", "func NewHandler(db *db.Client) *Handler {\n\treturn &Handler{db}\n}", "func NewHandler(ctx context.Context, store *sessions.CookieStore, urls map[string]string) *Handler {\n\treturn &Handler{\n\t\tctx: ctx,\n\t\tstore: store,\n\t\turls: urls,\n\t\tdb: orgodb.NewDB(\"orgo.db\"),\n\t}\n}", "func NewNullLogger() *NullLogger {\n\treturn &NullLogger{}\n}", "func NewNone() *None {\n\treturn nil\n}", "func NewHandler(appContext *appcontext.AppContext, domain domain.AppDomain, v validation.AppValidation, util utils.AppUtil) *Handler {\n\treturn &Handler{appContext: appContext, domain: domain, validation: v, util: util}\n}", "func newHandler(chain *Chain, handler Handler) (ch *ChainHandler) {\n\tch = new(ChainHandler)\n\tch.chain = chain\n\tch.handler = handler\n\treturn\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func NewHandler(\n\tcustomerService objects.CustomerService,\n\tbookService objects.BookService,\n) *Handler {\n\th := &Handler{\n\t\tcustomerService: customerService,\n\t\tbookService: bookService,\n\t}\n\treturn h\n}", "func NewHandler(clusterId string, members []string) (*Handler, error) {\n\tproxyHandler, err := proxy.NewProxyHandler(clusterId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\th := &Handler{\n\t\tclusterId: clusterId,\n\t\tproxyHandler: proxyHandler,\n\t\tmembers: members,\n\t}\n\n\tif err := h.Register(clusterId, members); err != nil {\n\t\treturn nil, err\n\t}\n\treturn h, nil\n}", "func NewHandler(s Service, v *validator.Validate, c *cache.Cache) FundHandler {\n\treturn FundHandler{service: s, validate: v, cache: c}\n}", "func New() handler.Handler {\n\treturn &LocalSelectionHandler{}\n}", "func NewNullSlowHasher() nullSlowHasher {\n\treturn nullSlowHasher{}\n}", "func NewHandler(config *conf.DNSResolverConfig, cache c.Cache) *DNSHandler {\n\tvar (\n\t\tclientConfig *dns.ClientConfig\n\t\tresolver *Resolver\n\t)\n\n\tresolver = &Resolver{clientConfig}\n\n\thandler := &DNSHandler{\n\t\tresolver: resolver,\n\t\tcache: cache,\n\t\tconfig: config,\n\t}\n\n\tif config.Hosts.Enable {\n\t\thandler.hosts = h.NewHosts(&config.Hosts)\n\t}\n\n\treturn handler\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tclient: NewClient(secrets()),\n\t\tstore: NewStore(),\n\t\ttemplates: templates(),\n\t\tsecrets: secrets(),\n\t\tdomain: \"http://localhost:9000\",\n\t}\n}", "func NewHandler(logger *zap.Logger, destination string) *Handler {\n\thandler := &Handler{\n\t\tlogger: logger,\n\t\tdispatcher: provisioners.NewMessageDispatcher(logger.Sugar()),\n\t\tdestination: fmt.Sprintf(\"http://%s\", destination),\n\t}\n\t// The receiver function needs to point back at the handler itself, so set it up after\n\t// initialization.\n\thandler.receiver = provisioners.NewMessageReceiver(createReceiverFunction(handler), logger.Sugar())\n\n\treturn handler\n}", "func NewNull() *Value {\n\treturn &Value{nil, Null}\n}", "func NewHandler(opts ...Option) *Handler {\n\th := &Handler{\n\t\thc: func() *hoarding.Hoard {\n\t\t\treturn hoarding.NewHoarder(nil, func() bool {\n\t\t\t\treturn true\n\t\t\t})\n\t\t},\n\t}\n\n\tfor _, o := range opts {\n\t\th = o(h)\n\t}\n\n\treturn h\n}", "func New(u IUserSvc, s IShopSvc) *Handler {\n\treturn &Handler{\n\t\tusrSvc: u,\n\t\tshopSvc: s,\n\t}\n}", "func New(c config.Handler, l logger.Handler) Handler {\n\treturn &handler{\n\t\tconfig: c,\n\t\tlog: l,\n\t}\n}", "func NewNullFunc(key Key, value bool) (Function, error) {\n\treturn &nullFunc{key, value}, nil\n}" ]
[ "0.86609536", "0.66271216", "0.64403784", "0.6337641", "0.6284098", "0.6284098", "0.6284098", "0.62595236", "0.6242817", "0.6185654", "0.6176326", "0.61568683", "0.61459947", "0.61377853", "0.61377853", "0.6133968", "0.61186665", "0.6111735", "0.6074967", "0.60670245", "0.6026621", "0.6019724", "0.6007954", "0.6006493", "0.59974533", "0.59931916", "0.5990903", "0.5978473", "0.5960945", "0.59364223", "0.5922357", "0.59217656", "0.59062713", "0.5900372", "0.589319", "0.58682644", "0.5865824", "0.58641607", "0.58634776", "0.5863005", "0.58581966", "0.5843502", "0.5842181", "0.582692", "0.58256257", "0.58256257", "0.58256257", "0.58256257", "0.58214307", "0.5814036", "0.5813015", "0.58125407", "0.5789946", "0.5788717", "0.57878685", "0.5785906", "0.5783991", "0.57758266", "0.5765407", "0.5763134", "0.5756168", "0.5755184", "0.5747588", "0.57434624", "0.5741963", "0.57364297", "0.5730908", "0.57164484", "0.57160836", "0.5715138", "0.5710538", "0.569467", "0.56932503", "0.5687721", "0.56821126", "0.56708", "0.5662901", "0.5660813", "0.5656124", "0.5653737", "0.56517315", "0.5640785", "0.5638905", "0.5622426", "0.55802417", "0.55802417", "0.55802417", "0.5578969", "0.55769527", "0.5570695", "0.5570172", "0.556741", "0.55629104", "0.55611277", "0.5556129", "0.55551225", "0.55541587", "0.55537724", "0.55482113", "0.5546079" ]
0.84745127
1
Handle does the actual throwing away.
func (h *NullHandler) Handle(err error) { }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func HandleCleanup(w http.ResponseWriter, r *http.Request) {\n\thc := NewHTTPContext(r, w) // HTTPContext\n\tc := gae.NewContext(hc) //GAE Context\n\tstamp := int64(time.Now().UnixNano() / Msec)\n\tq := datastore.NewQuery(\"Share\").Filter(\"expires >\", stamp)\n\n\tvar shares []Share\n\tkeys, err := q.GetAll(c, &shares)\n\tif err != nil {\n\t\tlog.Printf(\"Error during cleanip: %s\", err)\n\t\treturn\n\t}\n\n\tif len(keys) > 0 {\n\t\tlog.Printf(\"Found %d expired shares\", len(shares))\n\t\tfor i, key := range keys {\n\t\t\tshares[i].DSK = key\n\t\t\tshares[i].Delete(c)\n\t\t\tlog.Printf(\"Share '%s' deleted\", shares[i].Key)\n\t\t}\n\t}\n}", "func Unhandle(context *gorouter.RouteContext) {\n\n\tfmt.Println(\"cannot handle:\", context.Path)\n\tresponseData := response.Data{Success: false,\n\t\tErrorCode: 0,\n\t\tMessage: \"Route to nowhere\",\n\t\tData: nil}\n\n\tif data, err := json.Marshal(responseData); err == nil {\n\n\t\tcontext.W.Write(data)\n\t}\n\tcontext.Handled = true\n}", "func (ctx *Context) handle() {\n\thandlers := append(ctx.g.handlers, ctx.g.defaultHandler)\n\tfor _, h := range handlers {\n\t\tvals, err := ctx.Call(h, ctx.g.Injector)\n\n\t\t// If a Handler returns values, and if the first value is a glue.AfterHandler\n\t\t// defer it to allow post-request logic\n\t\tif len(vals) > 0 {\n\t\t\tif vals[0].Type() == reflect.TypeOf(AfterHandler(nil)) {\n\t\t\t\tafterFn := vals[0].Interface().(AfterHandler)\n\t\t\t\tdefer afterFn(*ctx)\n\t\t\t} else if len(vals) == 1 {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It is instead of type: %+v\\n\", AfterHandler(nil), vals[0].Type())\n\t\t\t} else {\n\t\t\t\tlog.Printf(\"glue: middleware didn't return a %T. It instead returned %d values: %+v\", AfterHandler(nil), len(vals), vals)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tif ctx.rw.WroteHeader() {\n\t\t\tbreak\n\t\t}\n\t}\n}", "func (e EmptyHandler) Handle(q midl.Request, s midl.Response) []byte {\n\treturn e.HandleFunc(q, s)\n}", "func (b *BaseHandler) Destroy() {}", "func (h Handler) Handle(c Container) {\n\th(c)\n}", "func Handle(ctx context.Context, rp interface{}) {\n\tpw, ok := rp.(*PanicWrap)\n\tif ok {\n\t\tlog.Ctx(ctx).Error().Msgf(\"Panic: %v\", pw.err)\n\t\trp = pw.err // unwrap error\n\t} else {\n\t\tlog.Ctx(ctx).Error().Msgf(\"Error: %v\", rp)\n\t}\n\tlog.Stack(ctx)\n\n\tsentryEvent{ctx, nil, rp, \"\"}.Send()\n}", "func Handle(err error) {\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func Handle(err error) {\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func (c *Command) Handle() {\n\tfmt.Println(\"Handle Method Should Be Rewrite\")\n\tos.Exit(0)\n}", "func (h *Handler) handle() {\n\t// try to keep reading from queue until there is no more data every period.\n\tfor {\n\t\tselect {\n\t\tcase data := <-h.queue:\n\t\t\tmetrics.ReportK8sWatchHandlerQueueLengthDec(h.clusterID, h.dataType)\n\t\t\tswitch data.Action {\n\t\t\tcase action.SyncDataActionAdd:\n\t\t\t\th.act.Add(data)\n\n\t\t\tcase action.SyncDataActionDelete:\n\t\t\t\th.act.Delete(data)\n\n\t\t\tcase action.SyncDataActionUpdate:\n\t\t\t\th.act.Update(data)\n\n\t\t\tdefault:\n\t\t\t\tglog.Errorf(\"can't handle metadata, unknown action type[%+v]\", data.Action)\n\t\t\t}\n\n\t\tcase <-time.After(defaultQueueTimeout):\n\t\t\t// no more data, break loop.\n\t\t\treturn\n\t\t}\n\t}\n}", "func (h Healthz) Handle(c echo.Context) error {\n\treturn c.NoContent(http.StatusNoContent)\n}", "func (Executor) Handle(w http.ResponseWriter, req *http.Request) {\n\tlogger.Logging(logger.DEBUG)\n\tdefer logger.Logging(logger.DEBUG, \"OUT\")\n\n\tswitch reqUrl := req.URL.Path; {\n\tcase strings.Contains(reqUrl, url.Unregister()):\n\t\tapiInnerExecutor.unregister(w, req)\n\t}\n}", "func (e *Periodical) handle(g Game, p interface{}) {\n\tswitch p.(type) {\n\tcase EventDead:\n\t\tg.DetachEffect(e)\n\tcase EventGameTick:\n\t\tif g.Clock().Before(e.expirationTime) {\n\t\t\treturn\n\t\t}\n\t\te.writeOutputUnitDetach(g)\n\t\tg.DetachEffect(e)\n\tcase EventPeriodicalTick:\n\t\te.routine()\n\t}\n}", "func (h *rawContainerHandler) Cleanup() {}", "func (h HandlerFunc) Handle(e Event) { h(e) }", "func Handle(handler Handler) {\n\tHandleContext(context.Background(), handler)\n}", "func (e WakeupEvent) Handle(c *Converger) {\n\t//do nothing\n}", "func handlePushEarlyReturnCancel(pushHandler PushHandler, pushedRequest *PushedRequest) {\n\thandleReturned := make(chan struct{})\n\tgo func() {\n\t\tdefer close(handleReturned)\n\t\tpushHandler.HandlePush(pushedRequest)\n\t}()\n\tselect {\n\tcase <-handleReturned:\n\t\tpushedRequest.Cancel()\n\tcase <-pushedRequest.pushedStream.done:\n\t}\n}", "func (app *App) handle(handler disgoHandler) *appHandler {\n\treturn &appHandler{handler, app, make([]middleware, 0)}\n}", "func (s *session) handleNOOP(args []string) error {\n\treturn s.respondOK(\"doing nothing\")\n}", "func (r *Route) handle(c *Context) {\n\tfor _, h := range r.handlers {\n\t\th(c)\n\t\tif c.Resp.Wrote() {\n\t\t\treturn\n\t\t}\n\t}\n}", "func handle(msg *queue.Message) {\n\tswitch msg.Action {\n\tcase RegenerateApprcAndStart:\n\t\tfallthrough\n\tcase regenerateApprc:\n\t\tif len(msg.Args) < 1 {\n\t\t\tlog.Printf(\"Error handling %q: this action requires at least 1 argument.\", msg.Action)\n\t\t\tmsg.Delete()\n\t\t\treturn\n\t\t}\n\t\tapp, err := ensureAppIsStarted(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\t\tapp.SerializeEnvVars()\n\t\tfallthrough\n\tcase startApp:\n\t\tif msg.Action == regenerateApprc {\n\t\t\tbreak\n\t\t}\n\t\tif len(msg.Args) < 1 {\n\t\t\tlog.Printf(\"Error handling %q: this action requires at least 1 argument.\", msg.Action)\n\t\t}\n\t\tapp, err := ensureAppIsStarted(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\terr = app.Restart(ioutil.Discard)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error handling %q. App failed to start:\\n%s.\", msg.Action, err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\tcase bindService:\n\t\terr := bindUnit(msg)\n\t\tif err != nil {\n\t\t\tlog.Print(err)\n\t\t\treturn\n\t\t}\n\t\tmsg.Delete()\n\tdefault:\n\t\tlog.Printf(\"Error handling %q: invalid action.\", msg.Action)\n\t\tmsg.Delete()\n\t}\n}", "func handle(handler func(evt interface{}, args ...interface{}), evt interface{}, args ...interface{}) {\n\tdefer util.HandlePanic()\n\thandler(evt, args...)\n}", "func (h *RepairingHandler) Handle(key serialization.Data, source, partition types.UUID, seq int64) error {\n\t// port of: com.hazelcast.internal.nearcache.impl.invalidation.RepairingHandler#handle(com.hazelcast.internal.serialization.Data, java.util.UUID, java.util.UUID, long)\n\t// Apply invalidation if it's not originated by local member/client.\n\t// Since local Near Caches are invalidated immediately there is no need to invalidate them twice.\n\tif h.localUUID != source {\n\t\tif key == nil {\n\t\t\th.nc.Clear()\n\t\t} else {\n\t\t\tk, err := h.toNearCacheKey(key)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\th.nc.Invalidate(k)\n\t\t}\n\t}\n\tpid, err := h.getPartitionIDOrDefault(key)\n\tif err != nil {\n\t\treturn err\n\t}\n\th.CheckOrRepairUUID(pid, partition)\n\th.CheckOrRepairSequence(pid, seq, false)\n\treturn nil\n}", "func Handle(err error) {\n\n\tlog.Error(err.Error())\n\tlog.Warn(\"Cauldron stopped\\n\")\n\n\tos.Exit(1)\n}", "func (j *Janitor) Handle(ctx context.Context) error {\n\tfns := []func(ctx context.Context){\n\t\tj.removeOldUploadFiles,\n\t\tj.removeOldUploadPartFiles,\n\t\tj.removeOldUploadingRecords,\n\t\tj.removeRecordsForDeletedRepositories,\n\t\tj.removeExpiredData,\n\t\tj.hardDeleteDeletedRecords,\n\t\tj.removeOrphanedData,\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(len(fns))\n\n\tfor _, f := range fns {\n\t\tgo func(f func(ctx context.Context)) {\n\t\t\tdefer wg.Done()\n\t\t\tf(ctx)\n\t\t}(f)\n\t}\n\n\twg.Wait()\n\treturn nil\n}", "func handleFailure(fhandler *flowHandler, context *faasflow.Context, err error) {\n\tvar data []byte\n\n\tcontext.State = faasflow.StateFailure\n\t// call failure handler if available\n\tif fhandler.getPipeline().FailureHandler != nil {\n\t\tfmt.Printf(\"[Request `%s`] Calling failure handler for error, %v\\n\",\n\t\t\tfhandler.id, err)\n\t\tdata, err = fhandler.getPipeline().FailureHandler(err)\n\t}\n\n\tfhandler.finished = true\n\n\t// call finally handler if available\n\tif fhandler.getPipeline().Finally != nil {\n\t\tfmt.Printf(\"[Request `%s`] Calling Finally handler with state: %s\\n\",\n\t\t\tfhandler.id, faasflow.StateFailure)\n\t\tfhandler.getPipeline().Finally(faasflow.StateFailure)\n\t}\n\tif data != nil {\n\t\tfmt.Printf(\"%s\", string(data))\n\t}\n\n\t// Cleanup data and state for failure\n\tif fhandler.stateStore != nil {\n\t\tfhandler.stateStore.Cleanup()\n\t}\n\tfhandler.dataStore.Cleanup()\n\n\t// stop req span if request has finished\n\tfhandler.tracer.stopReqSpan()\n\n\t// flash any pending trace item if tracing enabled\n\tfhandler.tracer.flushTracer()\n\n\tpanic(fmt.Sprintf(\"[Request `%s`] Failed, %v\\n\", fhandler.id, err))\n}", "func (recv *Receiver) handle(req Request, event cloudevents.Event) error {\n\n\terr := recv.s3ification(req.Description, event)\n\tif err != nil {\n\t\trecv.logger.Errorw(\"and error occured posting to s3 \", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (e *entityDeath) handle(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close()\n\n\tsc, err := getServerContext(r.Context())\n\n\tedLog := logWithRequest(r.RequestURI, sc)\n\n\tif err != nil {\n\t\tedLog.WithError(err).Info(\"Can't find server\")\n\t\thandleError(w, types.RESTError{\n\t\t\tError: \"Error finding server identity\",\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t})\n\t\treturn\n\t}\n\n\tdecoder := json.NewDecoder(r.Body)\n\tvar ed deprecatedEntityDeath\n\terr = decoder.Decode(&ed)\n\tif err != nil {\n\t\tedLog.WithError(err).Error(\"Invalid JSON\")\n\t\thandleError(w, types.RESTError{\n\t\t\tError: \"Invalid request\",\n\t\t\tStatusCode: http.StatusBadRequest,\n\t\t})\n\t\treturn\n\t}\n\n\ted.upgrade()\n\n\tfor i := range ed.OwnerIDs {\n\t\ted.OwnerIDs[i] = fmt.Sprintf(\"%s:%s\", sc.game, ed.OwnerIDs[i])\n\t}\n\n\tif len(ed.ServerName) == 0 {\n\t\ted.ServerName = sc.server.Name\n\t}\n\n\tif len(ed.ServerKey) == 8 {\n\t\ted.ServerKey = sc.server.Key\n\t}\n\n\talertAt := 10 * time.Second\n\tvalidUntil := 15 * time.Minute\n\n\tsAlertAt, err := time.ParseDuration(sc.server.RaidDelay)\n\tif err == nil {\n\t\talertAt = sAlertAt\n\t}\n\n\tsValidUntil, err := time.ParseDuration(sc.server.RaidCooldown)\n\tif err == nil {\n\t\tvalidUntil = sValidUntil\n\t}\n\n\te.raa.AddInfo(alertAt, validUntil, ed.EntityDeath)\n}", "func (h *HydrationHandler) Handle(ctx context.Context, evt AssetEvent) error {\n\tlogger := h.LogFn(ctx)\n\tasset := domain.Asset(evt)\n\tassetWithVulnerabilityDetails, err := h.Hydrator.HydrateVulnerabilities(ctx, asset)\n\tif err != nil {\n\t\tlogger.Error(logs.HydrationError{Reason: err.Error()})\n\t\treturn err\n\t}\n\tassetVulnEvent := domainAssetVulnerabilityDetailsToEvent(assetWithVulnerabilityDetails)\n\t_, err = h.Producer.Produce(ctx, assetVulnEvent)\n\treturn err\n}", "func (h *TestHandler) Handle(err error) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.errors = append(h.errors, err)\n}", "func denitialise(h *HTTP) {\n\tclose(h.events)\n\tclose(h.signals)\n}", "func (fe ForbiddenChange) Unwrap() error {\n\treturn fe.UndError\n}", "func handleDelete(ctx *verifierContext, status *types.VerifyImageStatus) {\n\n\tlog.Functionf(\"handleDelete(%s) refcount %d\",\n\t\tstatus.ImageSha256, status.RefCount)\n\n\tif _, err := os.Stat(status.FileLocation); err == nil {\n\t\tlog.Functionf(\"handleDelete removing %s\",\n\t\t\tstatus.FileLocation)\n\t\tif err := os.RemoveAll(status.FileLocation); err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t} else {\n\t\tlog.Warnf(\"handleDelete: Unable to delete %s: %s\",\n\t\t\tstatus.FileLocation, err)\n\t}\n\n\tunpublishVerifyImageStatus(ctx, status)\n\tlog.Functionf(\"handleDelete done for %s\", status.ImageSha256)\n}", "func (m *TestFixClient) Handle(msg *fix.Message) {\n\t// no-op\n}", "func (o *singleObserver) Handle(item interface{}) {\n\tswitch item := item.(type) {\n\tcase error:\n\t\to.errHandler(item)\n\t\treturn\n\tdefault:\n\t\to.nextHandler(item)\n\t}\n}", "func (b *RawBackend) handleRawDelete(ctx context.Context, req *logical.Request, data *framework.FieldData) (*logical.Response, error) {\n\tpath := data.Get(\"path\").(string)\n\n\tif b.recoveryMode {\n\t\tb.logger.Info(\"deleting\", \"path\", path)\n\t}\n\n\t// Prevent access of protected paths\n\tfor _, p := range protectedPaths {\n\t\tif strings.HasPrefix(path, p) {\n\t\t\terr := fmt.Sprintf(\"cannot delete '%s'\", path)\n\t\t\treturn logical.ErrorResponse(err), logical.ErrInvalidRequest\n\t\t}\n\t}\n\n\tif err := b.barrier.Delete(ctx, path); err != nil {\n\t\treturn handleErrorNoReadOnlyForward(err)\n\t}\n\treturn nil, nil\n}", "func (r *relay) handleDrop(reason error) {\n\t// Notify the app of the drop if premature\n\tif reason != nil {\n\t\tr.handler.HandleDrop(reason)\n\t}\n\n\t// Close all open tunnels\n\tr.tunLock.Lock()\n\tfor _, tun := range r.tunLive {\n\t\ttun.handleClose()\n\t}\n\tr.tunLive = nil\n\tr.tunLock.Unlock()\n}", "func (sp *ExponentialBackOffSupervisor) Handle(err interface{}, targetAddr Addr, target Actor, parent Actor) {\n\tsp.work.Lock()\n\tdefer sp.work.Unlock()\n\n\tfailed := atomic.LoadInt64(&sp.failed)\n\tif int(failed) >= sp.Max {\n\t\ttarget.Stop()\n\t\tif sp.Invoker != nil {\n\t\t\tsp.Invoker.InvokedStop(err, target.Stats(), targetAddr, target)\n\t\t}\n\n\t\treturn\n\t}\n\n\tvar backoff int64\n\tif failed > 0 {\n\t\tbackoff = failed * sp.Backoff.Nanoseconds()\n\t} else {\n\t\tbackoff = sp.Backoff.Nanoseconds()\n\t}\n\n\tnoise := rand.Int63n(500)\n\tdur := time.Duration(backoff + noise)\n\n\ttime.AfterFunc(dur, func() {\n\t\tactionErr := sp.Action(err, targetAddr, target, parent)\n\t\tif sp.Invoker != nil {\n\t\t\tsp.Invoker.InvokedRestart(err, target.Stats(), targetAddr, target)\n\t\t}\n\n\t\tif actionErr != nil {\n\t\t\tatomic.AddInt64(&sp.failed, 1)\n\t\t\tsp.Handle(err, targetAddr, target, parent)\n\t\t\treturn\n\t\t}\n\n\t\tatomic.StoreInt64(&sp.failed, 0)\n\t})\n}", "func (c *Controller) handleAborted(ctx context.Context, pipelineRun k8s.PipelineRun) error {\n\tintent := pipelineRun.GetSpec().Intent\n\tif intent == api.IntentAbort && pipelineRun.GetStatus().Result == api.ResultUndefined {\n\t\tpipelineRun.UpdateMessage(\"Aborted\")\n\t\treturn c.updateStateAndResult(ctx, pipelineRun, api.StateCleaning, api.ResultAborted, metav1.Now())\n\t}\n\treturn nil\n}", "func throwaway(interface{}) {}", "func (Empty) Handle(event term.Event) bool {\n\treturn false\n}", "func (handler *AllowAllHandler) Release() {\n\treturn\n}", "func (fn DeleteVMTempHandlerFunc) Handle(params DeleteVMTempParams) middleware.Responder {\n\treturn fn(params)\n}", "func (shareXRouter *ShareXRouter) handleDelete(writer http.ResponseWriter, request *http.Request) {\n\t//get the delete reference\n\tdeleteReference, ok := mux.Vars(request)[deleteReferenceVar]\n\tif !ok {\n\t\thttp.Error(writer, \"400 Bad request\", http.StatusBadRequest)\n\t\treturn\n\t}\n\t//delete the entry\n\terr := shareXRouter.Storage.Delete(deleteReference)\n\tif err != nil {\n\t\tshareXRouter.sendInternalError(writer, fmt.Sprintf(\"deleting entry with call reference %v\", strconv.Quote(deleteReference)), err)\n\t\treturn\n\t}\n\twriter.WriteHeader(http.StatusOK)\n}", "func (p *PortForwardDelete) Handle(ctx context.Context, alerter action.Alerter, payload action.Payload) error {\n\tp.logger.With(\"payload\", payload).Debugf(\"received action payload\")\n\tid, err := payload.String(\"id\")\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"convert payload to stop port forward request\")\n\t}\n\n\tp.portForwarder.StopForwarder(id)\n\treturn nil\n}", "func (c *PoliciesCleaner) Handle(ctx context.Context, msg *idm.ChangeEvent) error {\n\n\tif msg.Type != idm.ChangeEventType_DELETE {\n\t\treturn nil\n\t}\n\n\tvar subject string\n\tif c.Options.SubscribeRoles && msg.Role != nil {\n\t\tsubject = fmt.Sprintf(\"role:%s\", msg.Role.Uuid)\n\t}\n\tif c.Options.SubscribeUsers && msg.User != nil {\n\t\tif msg.User.IsGroup {\n\t\t\tsubject = fmt.Sprintf(\"role:%s\", msg.User.Uuid)\n\t\t} else {\n\t\t\tsubject = fmt.Sprintf(\"user:%s\", msg.User.Login)\n\t\t}\n\t}\n\n\tif len(subject) > 0 {\n\t\tlog.Logger(c.LogCtx).Debug(\"DELETING POLICIES ON EVENT\", zap.Any(\"event\", msg), zap.String(\"subject\", subject))\n\t\tdao := c.Dao.(resources.DAO)\n\t\treturn dao.DeletePoliciesBySubject(subject)\n\t}\n\treturn nil\n\n}", "func (c *Cache) HandleDelete(ctx *fasthttp.RequestCtx) {\n\tc.Remove(ctx.UserValue(\"key\").(string))\n}", "func (tr *Transport) HANDLE(met, url string, fn Handler, options ...HandlerOption) {\n\ttr.mux.Handler(\n\t\tmet, url,\n\t\tnewHandler(fn, append(tr.options, options...)...),\n\t)\n}", "func (h *Handler) Handle(data *action.SyncData) {\n\th.queue <- data\n}", "func (b *BlockManager) handleStallSample() {\n\tif atomic.LoadInt32(&b.shutdown) != 0 {\n\t\treturn\n\t}\n}", "func (h UploadHandler) Handle(w http.ResponseWriter, r *users.AuthenticatedRequest) {\n\tw.WriteHeader(http.StatusOK)\n\tif !r.IsAuthenticated() {\n\t\tvar authErr Error\n\t\tif r.AuthFailed() {\n\t\t\tauthErr = NewAuthError(r.AuthError)\n\t\t} else {\n\t\t\tauthErr = ErrUnauthorized\n\t\t}\n\t\tw.Write(authErr.AsBytes())\n\t\treturn\n\t}\n\n\tf, err := h.saveFile(r)\n\tif err != nil {\n\t\tlogger.Log().Error(err)\n\t\tmonitor.CaptureException(err)\n\t\tw.Write(NewInternalError(err).AsBytes())\n\t\treturn\n\t}\n\n\tresponse := h.Publisher.Publish(f.Name(), r.WalletID, []byte(r.FormValue(JSONRPCFieldName)))\n\n\tif err := os.Remove(f.Name()); err != nil {\n\t\tmonitor.CaptureException(err, map[string]string{\"file_path\": f.Name()})\n\t}\n\n\tw.Write(response)\n}", "func (fn DeleteAuditregistrationV1alpha1AuditSinkHandlerFunc) Handle(params DeleteAuditregistrationV1alpha1AuditSinkParams) middleware.Responder {\n\treturn fn(params)\n}", "func (fn ClearHandlerFunc) Handle(params ClearParams) middleware.Responder {\n\treturn fn(params)\n}", "func (r *router) handle(c *Context){\n\tn, params := r.getRoute(c.Method, c.Path)\n\tif n != nil {\n\t\tc.Params = params\n\t\t// connection between Context and Router!\n\t\t// it's important\n\t\tkey := c.Method + \"-\" + n.pattern\n\t\t// 两种函数都放到一起了\n\t\tc.handlers = append(c.handlers, r.handlers[key])\n\t\t//r.handlers[key](c)\n\t}else{\n\t\tc.handlers = append(c.handlers, func(c *Context){\n\t\t\tc.String(http.StatusNotFound, \"404 NOT FOUND%s\\n\", c.Path)\n\t\t})\n\t}\n\t//放在这里一起执行, 中间执行, 其逻辑导致\"并行\"效果\n\tc.Next()\n}", "func handleKill() {\n\n\tc := make(chan os.Signal, 1)\n\tsignal.Notify(c, os.Interrupt, syscall.SIGTERM)\n\n\t// Block until a signal is received.\n\ts := <-c\n\tlog.Println(\"Received signal:\", s)\n\n\t// Exit Logic\n dockerClient, err := docker.NewClient(DOCKER_ENDPOINT)\n\tcheckError(\"handleKill func: creating docker client\", err)\n\tstopContainerFromImage(dockerClient, CONFIG.DockerImageName)\n\n\tcode := 0\n\tif DEBUG {\n\t\tlog.Printf(\"Exiting with error code: %v\\n\", code)\n\t}\n\tos.Exit(code)\n}", "func (m *Middleware) Handle(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstartAt := util.TimeNow()\n\n\t\ttraceID := util.StrUniqueID()\n\t\tlogger := NewLogger(m.Writer, m.MinOutSeverity, traceID)\n\t\tctx := r.Context()\n\t\tctx = SetLogger(ctx, logger)\n\n\t\tdefer func() {\n\t\t\tif rcvr := recover(); rcvr != nil {\n\t\t\t\tmsg := Panic(ctx, rcvr)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tw.Write([]byte(msg))\n\n\t\t\t\tendAt := util.TimeNow()\n\t\t\t\tdr := endAt.Sub(startAt)\n\n\t\t\t\tlogger.WriteRequest(r, endAt, dr)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\n\t\tendAt := util.TimeNow()\n\t\tdr := endAt.Sub(startAt)\n\n\t\tlogger.WriteRequest(r, endAt, dr)\n\t})\n}", "func (it *HandleIterator) Take() *Handle {\n\thandle := it.Handle\n\tit.Handle = nil\n\treturn handle\n}", "func (da *CleanNodesAction) Handle(\n\tctx context.Context, req *cmproto.CleanNodesInGroupRequest, resp *cmproto.CleanNodesInGroupResponse) {\n\tif req == nil || resp == nil {\n\t\tblog.Errorf(\"CleanNodesAction failed, req or resp is empty\")\n\t\treturn\n\t}\n\tda.ctx = ctx\n\tda.req = req\n\tda.resp = resp\n\n\tif err := da.validate(); err != nil {\n\t\t//validate already sets response information\n\t\treturn\n\t}\n\tif err := da.getRelativeData(); err != nil {\n\t\treturn\n\t}\n\n\t// update clean node status\n\tif err := da.updateCleanNodesStatus(); err != nil {\n\t\treturn\n\t}\n\n\t// dispatch task\n\tif err := da.handleTask(); err != nil {\n\t\treturn\n\t}\n\n\terr := da.model.CreateOperationLog(da.ctx, &cmproto.OperationLog{\n\t\tResourceType: common.NodeGroup.String(),\n\t\tResourceID: da.group.NodeGroupID,\n\t\tTaskID: da.task.TaskID,\n\t\tMessage: fmt.Sprintf(\"集群%s节点池%s删除节点%v\", da.group.ClusterID, da.group.NodeGroupID, da.req.Nodes),\n\t\tOpUser: req.Operator,\n\t\tCreateTime: time.Now().String(),\n\t})\n\tif err != nil {\n\t\tblog.Errorf(\"CleanNodesFromNodeGroup[%s] CreateOperationLog failed: %v\", da.group.NodeGroupID, err)\n\t}\n\n\tresp.Data = da.task\n\tda.setResp(common.BcsErrClusterManagerSuccess, common.BcsErrClusterManagerSuccessStr)\n\treturn\n}", "func (h *StdHandle) Clear(ctx context.Context, reporter Reporter) (err error) {\n\n\tif err = h.archiver.Index(func(k string) error {\n\t\tif err = h.store.Del(ctx, k); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to delete object key\")\n\t\t}\n\n\t\treporter.HandledKey(k)\n\t\t//@TODO inform reporter\n\n\t\treturn nil\n\t}); err != nil {\n\t\treturn errors.Wrap(err, \"failed to walk index\")\n\t}\n\n\tif h.delegate != nil {\n\t\tif err = h.delegate.PostClean(ctx); err != nil {\n\t\t\treturn errors.Wrap(err, \"failed to run post clean delegate\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func handleTimeout(task *task.MessageTask, env *task.Env) {\n\tkey := fmt.Sprintf(\"%x\", task.GetMessage().Token)\n\tdelete(env.Requests(), key)\n\tlog.Info(\"<<< handleTimeout >>>\")\n}", "func (fn PostSilencesHandlerFunc) Handle(params PostSilencesParams) middleware.Responder {\n\treturn fn(params)\n}", "func TerminateHandler(w http.ResponseWriter, r *http.Request) { // rollback\n\tcurrentJobid, _ := strconv.Atoi(r.URL.Path[6:])\n\tdelete(services.JobProgress, currentJobid) // clear the services.JobProgress\n\tdelete(services.ChannelMap, currentJobid) // delete the channel\n\tfmt.Println(\"Job terminated\")\n\tfmt.Fprintf(w, \"terminateHandler\")\n}", "func (s *BasecluListener) ExitWhen_handler(ctx *When_handlerContext) {}", "func (p Processor) Handle(m *Mail) error {\n\tfor _, v := range p.mailets {\n\t\tif err := v.Handle(m); err != nil {\n\t\t\tif err == TerminateProcessing {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"failed to process mail: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func (rool *rool) Handle(w http.ResponseWriter, r *http.Request) {\n\tatomic.AddUint64(&rool.hits, 1)\n\turl := &bytes.Buffer{}\n\terr := rool.Pattern.Execute(url, r)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\t// We send TARGET in Location header on HEAD request with 200 OK status\n\tif r.Method == \"HEAD\" {\n\t\tr.Close = true\n\t\tw.Header().Add(\"Location\", strings.TrimSpace(url.String()))\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\tw.Header().Add(\"Content-Length\", \"0\")\n\thttp.Redirect(w, r, strings.TrimSpace(url.String()), http.StatusFound)\n}", "func (ctx *actorContext) handleTerminated(msg *Terminated) {\n\tif ctx.extras != nil {\n\t\tctx.extras.removeChild(msg.Who)\n\t}\n\n\tctx.InvokeUserMessage(msg)\n\tctx.tryRestartOrTerminate()\n}", "func (h CatchAllHandler) Handle() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\th.WriteErrorResponse(r.Context(), w, &apperrors.UnknownRouteError{Path: r.URL.Path})\n\t}\n}", "func (s *Server) handleWhatever() {}", "func (c *Channel) HandleSettled(blockNumber int64) {\n\n}", "func (ce *Emitter) Handle(e metrics.Entry) error {\n\t_, err := ce.Sink.Write(ce.Transform(e))\n\treturn err\n}", "func (ce *Emitter) Handle(e metrics.Entry) error {\n\t_, err := ce.Sink.Write(ce.Transform(e))\n\treturn err\n}", "func (ths *ReceiveBackEnd) handleError(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close();\n\tths.log.Println(\"Error request arrived...\");\n\thttp.Error(w, \"No such service\", http.StatusBadGateway);\n}", "func (p *Server) handle(resp *http.Response) {\n\n\tdefer resp.Body.Close()\n\n\treqId := resp.Header.Get(\"Reqid\")\n\tif reqId == \"\" {\n\t\tlog.Warn(\"unidisvr: Reqid not found\")\n\t\treturn\n\t}\n\n\tb := bufio.NewReader(resp.Body)\n\treq, err := http.ReadRequest(b)\n\tif err != nil {\n\t\tlog.Warn(\"unidisvr: ReadRequest failed -\", p.Addr, p.BaseUrl, err)\n\t\treturn\n\t}\n\n\tw := newResponseWriter(p.BaseUrl, reqId)\n\tp.Handler.ServeHTTP(w, req)\n\terr = w.Done()\n\tif err != nil {\n\t\tlog.Warn(\"unidisvr: ServeHTTP failed -\", p.Addr, p.BaseUrl, err)\n\t}\n}", "func (r *defaultRacer) handleErrInWorker(err error) {\n\tlog.Error(\"err occurred in worker\")\n\tlog.Errorf(\"%+v\", err)\n\tr.err = err\n\n\tr.closeOnce.Do(func() {\n\t\tclose(r.done) // kill all goroutines\n\t})\n}", "func (h *Handler) Dispatch() {\n\tdefer h.shutdown()\n\n\t// Handle messages from the VM\n\tgo h.dispatchInternal()\n\n\t// Handle messages from the router\n\tfor {\n\t\t// Wait until there is an unprocessed message\n\t\th.unprocessedMsgsCond.L.Lock()\n\t\tfor {\n\t\t\tif closing := h.closing.GetValue(); closing {\n\t\t\t\th.unprocessedMsgsCond.L.Unlock()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif h.unprocessedMsgs.Len() == 0 {\n\t\t\t\t// Signalled in [h.push] and [h.StartShutdown]\n\t\t\t\th.unprocessedMsgsCond.Wait()\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\t// Get the next message we should process\n\t\tmsg := h.unprocessedMsgs.Pop()\n\t\th.unprocessedMsgsCond.L.Unlock()\n\n\t\t// If this message's deadline has passed, don't process it.\n\t\tif expirationTime := msg.ExpirationTime(); !expirationTime.IsZero() && h.clock.Time().After(expirationTime) {\n\t\t\tnodeID := msg.NodeID()\n\t\t\th.ctx.Log.Verbo(\"Dropping message from %s%s due to timeout. msg: %s\",\n\t\t\t\tconstants.NodeIDPrefix, nodeID, msg)\n\t\t\th.metrics.expired.Inc()\n\t\t\tmsg.OnFinishedHandling()\n\t\t\tcontinue\n\t\t}\n\n\t\t// Process the message.\n\t\t// If there was an error, shut down this chain\n\t\tif err := h.handleMsg(msg); err != nil {\n\t\t\th.ctx.Log.Fatal(\"chain shutting down due to error %q while processing message: %s\",\n\t\t\t\terr, msg)\n\t\t\th.StartShutdown()\n\t\t\treturn\n\t\t}\n\t}\n}", "func (hf HandlerFunc) Handle(metadata Metadata) error {\n\treturn hf(metadata)\n}", "func Handle(w http.ResponseWriter, mutator func() error) {\n\terr := mutator()\n\tif err == nil {\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\tswitch err := err.(type) {\n\tcase errs.BadRequestError:\n\t\thttperr.ClientError(w, err.Error())\n\tcase errs.UnauthorizedError:\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(err.Error()))\n\tdefault:\n\t\thttperr.ServerError(w, err.Error())\n\t}\n}", "func ExampleAbsorb() {}", "func (s *Service) Handle(ctx context.Context, request []byte) ([]byte, error) {\n\treturn s.ioManager.Handler().(NextIOHandler)(ctx, request)\n}", "func (h DefaultHandler) Handle(client *hub.Client, data []byte) {\n\tclient.SendJSON(\"error\", \"unknown message type\")\n}", "func (t *Tag) Handle(p *Processor, attr string) {\n\tt.Open(p, attr)\n\tp.Process(t.name)\n\tt.Close(p, attr)\n}", "func Handle(err error) {\n\tif err != nil {\n\t\tpc, _, ln, _ := runtime.Caller(1)\n\t\tdetails := runtime.FuncForPC(pc)\n\t\tlog.Printf(\"Fatal: %s - %s %d\", err.Error(), details.Name(), ln)\n\n\t\t// log to sentry\n\t\tsentry.CaptureException(err)\n\t\tsentry.Flush(time.Second * 5)\n\t}\n}", "func (fn PostOperationsDeleteP2PPathHandlerFunc) Handle(params PostOperationsDeleteP2PPathParams) middleware.Responder {\n\treturn fn(params)\n}", "func Handle(w http.ResponseWriter, r *http.Request, HandleFunc HandleFunc) {\n\thandler := pool.Get().(*Handler)\n\tdefer pool.Put(handler)\n\n\thandler.Reset(HandleFunc)\n\thandler.ServeHTTP(w, r)\n\thandler.Reset(nil)\n}", "func handleMessage(m *sqs.Message, h Handler) error {\n var err error\n err = h.HandleMessage(m)\n if err != nil {\n return err\n }\n\n _, err = SqsService.Delete(m.ReceiptHandle)\n if err != nil {\n return err\n }\n\n log.Printf(\"Deleted message from queue: %s\\n\", aws.StringValue(m.ReceiptHandle))\n return nil\n}", "func emptyHandler(w http.ResponseWriter, req *http.Request) {}", "func AbortHandler(w http.ResponseWriter) func(context.Context, problems.Problem) {\n\treturn func(ctx context.Context, problem problems.Problem) {\n\t\tselect {\n\t\tcase <-ctx.Done(): // Context was cancelled or reached deadline\n\t\t\tlog := logger.FromContext(ctx)\n\t\t\tlog.Info(\"tried to write error response, but context was cancelled/reached deadline\")\n\t\tdefault:\n\t\t\tresponse := problems.NewErrorResponse(ctx, problem)\n\t\t\twriteErrorResponse(ctx, w, response)\n\t\t}\n\t}\n}", "func popHandleEvent(p *Parser, handle *handle_t) {\n\tpopHandle(p, handle)\n\tif len(p.DataBuffer) == 0 {\n\t\tp.onEvent(p, EVT_LEAVE)\n\t\treturn\n\t}\n\tif p.OnData != nil {\n\t\tp.OnData(p, DATA_END)\n\t\tif p.userSignal != SIG_STOP {\n\t\t\tgoto FIRE_LEAVE_EVT\n\t\t}\n\t\treturn\n\t}\nFIRE_LEAVE_EVT:\n\tp.DataBuffer = p.DataBuffer[:0]\n\tp.onEvent(p, EVT_LEAVE)\n}", "func (fn DepositFileHandlerFunc) Handle(params DepositFileParams, principal *authorization.Agent) middleware.Responder {\n\treturn fn(params, principal)\n}", "func (e *Exchanger) Handle(req *kafka.Message) (*kafka.Message, error) {\n\tbody, err := e.Handler(req.Value)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp := kafka.Message{\n\t\tTopicPartition: kafka.TopicPartition{\n\t\t\tTopic: &e.Client.ProducerTopic,\n\t\t\tPartition: kafka.PartitionAny,\n\t\t},\n\t\tValue: body,\n\t\tKey: req.Key,\n\t\tTimestamp: time.Now(),\n\t\tTimestampType: kafka.TimestampCreateTime,\n\t}\n\treturn &resp, nil\n}", "func (h *ConsecutiveResponseHandler) Handle(w http.ResponseWriter) error {\n\tif len(h.Handlers) < 1 {\n\t\treturn errors.New(\"need at least 1 handler\")\n\t}\n\tif h.HandledCount < 0 {\n\t\treturn errors.New(\"cannot have negative handled count\")\n\t}\n\t// default to last handler\n\thandler := h.Handlers[len(h.Handlers)-1]\n\t// use handler at count if less than size of handlers\n\tif h.HandledCount < len(h.Handlers) {\n\t\thandler = h.Handlers[h.HandledCount]\n\t}\n\th.HandledCount++\n\treturn handler.Handle(w)\n}", "func (b *Bucket) Handle() *storage.BucketHandle {\n\treturn b.bkt\n}", "func (fn CancelHandlerFunc) Handle(params CancelParams) middleware.Responder {\n\treturn fn(params)\n}", "func (h *Handler) HandleWithTimeout(data *action.SyncData, timeout time.Duration) {\n\tselect {\n\tcase h.queue <- data:\n\t\tmetrics.ReportK8sWatchHandlerQueueLengthInc(h.clusterID, h.dataType)\n\tcase <-time.After(timeout):\n\t\tmetrics.ReportK8sWatchHandlerDiscardEvents(h.clusterID, h.dataType)\n\t\tglog.Warn(\"can't handle data, queue timeout\")\n\t}\n}", "func (m *SomeMiddleware) Handle(ctx context.Context, r *http.Request, next rest.Next) (context.Context, int, http.Header, interface{}) {\n\t// code\n\treturn next(ctx)\n}", "func Handle(rxPacket models.RXPacket) error {\n\tctx := proprietaryContext{\n\t\tRXPacket: rxPacket,\n\t}\n\n\tfor _, t := range tasks {\n\t\tif err := t(&ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (r *analyticsDeferredResultHandle) executeHandle(req *gocbcore.HttpRequest, valuePtr interface{}) error {\n\tresp, err := r.provider.DoHttpRequest(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tjsonDec := json.NewDecoder(resp.Body)\n\terr = jsonDec.Decode(valuePtr)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\terr = resp.Body.Close()\n\tif err != nil {\n\t\tlogDebugf(\"Failed to close socket (%s)\", err)\n\t}\n\n\treturn nil\n}", "func ExampleAbsorbTrytes() {}" ]
[ "0.6007517", "0.5981388", "0.5857966", "0.57566375", "0.56773746", "0.5534087", "0.55161464", "0.5505347", "0.5505347", "0.549327", "0.548301", "0.5447733", "0.5444", "0.5431213", "0.5402641", "0.5367901", "0.533009", "0.53240347", "0.53202474", "0.5319494", "0.5318252", "0.5315578", "0.53092754", "0.529741", "0.5284512", "0.5273361", "0.52624846", "0.5234853", "0.5229237", "0.5224541", "0.521918", "0.5196554", "0.51839864", "0.51746726", "0.5169666", "0.5160349", "0.5143205", "0.51226765", "0.512069", "0.5117439", "0.5105312", "0.5098026", "0.5095678", "0.5075611", "0.506768", "0.50659895", "0.5057338", "0.505143", "0.50488544", "0.50404215", "0.5019741", "0.5019469", "0.5001037", "0.49958304", "0.49933293", "0.4983179", "0.4981749", "0.49650317", "0.49638388", "0.49480587", "0.49433193", "0.494208", "0.4937262", "0.4936551", "0.49354672", "0.49321243", "0.49228594", "0.4922653", "0.49124172", "0.49120343", "0.4909309", "0.49078658", "0.49078658", "0.49073637", "0.49039778", "0.49029374", "0.4902495", "0.4898746", "0.48959193", "0.48894644", "0.48883575", "0.4881095", "0.4879163", "0.48761132", "0.48741025", "0.48705155", "0.4866896", "0.48657456", "0.48655578", "0.48557648", "0.48554257", "0.48549473", "0.4853417", "0.4852749", "0.48513278", "0.4850651", "0.48502266", "0.48406616", "0.48400095", "0.4837001" ]
0.59973496
1
NewLogHandler returns a new LogHandler.
func NewLogHandler(logger errorLogger) Handler { return &LogHandler{logger} }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewHandler(log zerolog.Logger) func(httpserver.Handler) httpserver.Handler {\n\treturn func(next httpserver.Handler) httpserver.Handler {\n\t\treturn httpserver.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {\n\t\t\t// Create a copy of the logger (including internal context slice)\n\t\t\t// to prevent data race when using UpdateContext.\n\t\t\tl := log.With().Logger()\n\t\t\tr = r.WithContext(l.WithContext(r.Context()))\n\t\t\treturn next.ServeHTTP(w, r)\n\t\t})\n\t}\n}", "func New() *Handler {\n\treturn &Handler{\n\t\tEntries: make([]log.Entry, 0),\n\t}\n}", "func NewLogHandler() *LogHandler {\n\treturn &LogHandler{}\n}", "func NewLogHandler(output io.Writer) operations.LogHandler {\n\treturn LogHandler{\n\t\tlogger: log.New(output, \"\", 0),\n\t}\n}", "func New(logger logger.Logger) *Handler {\n\treturn &Handler{\n\t\tlogger: logger,\n\t}\n}", "func New(eh *exit.Handler, lgr logger.OutputIface) *Handler {\n\treturn &Handler{\n\t\tex: eh,\n\t\tLogger: lgr,\n\t\tmu: &sync.Mutex{},\n\t}\n}", "func New(c config.Handler, l logger.Handler) Handler {\n\treturn &handler{\n\t\tconfig: c,\n\t\tlog: l,\n\t}\n}", "func NewLoggingHandler(h http.Handler, log *logrus.Logger) http.Handler {\n\treturn http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {\n\t\tsetLogger(req, log)\n\t\tstart := time.Now()\n\t\tstatusRes := newStatusCapturingResponseWriter(res)\n\t\th.ServeHTTP(statusRes, req)\n\t\tlatency := time.Since(start)\n\n\t\tlog.WithFields(logrus.Fields{\n\t\t\t\"method\": req.Method,\n\t\t\t\"path\": req.URL.Path,\n\t\t\t\"request_uri\": req.RequestURI,\n\t\t\t\"status\": statusRes.statusCode,\n\t\t\t\"time\": latency,\n\t\t\t\"request_time\": latency.Seconds(),\n\t\t}).Info(\"Handled a request\")\n\t})\n}", "func NewLog(out io.Writer, prefix string, flag int) *logHandler {\n\tl := logHandler{}\n\tl.logger = log.New(out, prefix, flag)\n\treturn &l\n}", "func New(conf Config) (log.CloseHandler, error) {\n\tctx := conf.Ctx\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\tclient, err := logging.NewClient(ctx, conf.Parent, conf.Opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\th := &handler{\n\t\tlogName: conf.LogName,\n\t\tclient: client,\n\t\tcodec: conf.Codec,\n\t}\n\tif h.codec == nil {\n\t\th.codec = codec.Simple()\n\t}\n\treturn h, nil\n}", "func NewHandler(log Logger, h http.Handler) *Handler {\n\treturn &Handler{\n\t\tlog: log,\n\t\th: h,\n\t}\n}", "func newLoggerHandler(level Level, extraStackDepth int, handlers []Handler) log.Handler {\n\tvar logHandler log.Handler\n\n\tif len(handlers) == 0 {\n\t\tlogHandler = log.StderrHandler\n\t} else {\n\t\thandlerArr := []log.Handler{}\n\t\tfor _, handler := range handlers {\n\t\t\tvar lh log.Handler\n\t\t\tif l, ok := handler.(*fromLog15Handler); ok {\n\t\t\t\tlh = l.internal\n\t\t\t} else {\n\t\t\t\tlh = &toLog15Handler{handler}\n\t\t\t}\n\t\t\thandlerArr = append(handlerArr, lh)\n\t\t}\n\n\t\tif len(handlerArr) == 1 {\n\t\t\tlogHandler = handlerArr[0]\n\t\t} else {\n\t\t\tlogHandler = log.MultiHandler(handlerArr...)\n\t\t}\n\t}\n\n\treturn log.LvlFilterHandler(log.Lvl(level),\n\t\tcallerFileLog15Handler(8+extraStackDepth, logHandler))\n}", "func NewHandler(logger *log.Logger, db *sql.DB) Handler {\n\treturn Handler{\n\t\tlogger: logger,\n\t\tdb: db,\n\t}\n}", "func NewHandler() Handler {\n\treturn Handler{}\n}", "func NewHandler(logger *zap.Logger, destination string) *Handler {\n\t handler := &Handler{\n\t\t logger: logger,\n\t\t dispatcher: provisioners.NewMessageDispatcher(logger.Sugar()),\n\t\t destination: destination,\n\t }\n\t // The receiver function needs to point back at the handler itself, so set it up after\n\t // initialization.\n\t handler.receiver = provisioners.NewMessageReceiver(createReceiverFunction(handler), logger.Sugar())\n \n\t return handler\n }", "func New(next http.Handler, opts ...Option) http.Handler {\n\toptions := &Options{}\n\tfor _, fn := range opts {\n\t\tfn(options)\n\t}\n\n\treturn &logging{\n\t\tnext: next,\n\t\toptions: options,\n\t}\n}", "func New(handler Handler, flag int) *Logger {\n\tvar l = new(Logger)\n\n\tl.level = LevelInfo\n\tl.handler = handler\n\n\tl.flag = flag\n\n\tl.quit = make(chan struct{})\n\tl.closed = false\n\n\tl.msg = make(chan []byte, 1024)\n\n\tl.bufs = make([][]byte, 0, 16)\n\n\tl.wg.Add(1)\n\tgo l.run()\n\n\treturn l\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tentry: newEntries(),\n\t}\n}", "func New(lc Checker, lw Writer) *Handler {\n\treturn &Handler{\n\t\tlc: lc,\n\t\tlw: lw,\n\t}\n}", "func New() *Handler {\n\th := Handler{}\n\th.init()\n\treturn &h\n}", "func (t *Trigger) NewHandler(settings map[string]interface{}) *Handler {\n\n\tnewHandler := &Handler{settings: settings}\n\tt.handlers = append(t.handlers, newHandler)\n\n\treturn newHandler\n}", "func New(c *configuration.Configuration) *Handler {\n\treturn &Handler{\n\t\tSession: c.Session,\n\t\tConfiguration: c.Environment,\n\t\tLog: c.Logger,\n\t}\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func NewHandler() *Handler {\n\treturn &Handler{}\n}", "func NewHandler(logger abstractlogger.Logger, client Client, executorPool ExecutorPool) (*Handler, error) {\n\treturn NewHandlerWithInitFunc(logger, client, executorPool, nil)\n}", "func New(r *mux.Router, db *sql.DB) *Handler {\n\treturn &Handler{r, db}\n}", "func NewHandler(h http.Handler) http.Handler {\n\treturn handler{Handler: h}\n}", "func NewHandler(family *Family) *Handler {\n\treturn &Handler{\n\t\tfamily,\n\t\tmake(map[int32]HandlerFunc),\n\t\tos.Getenv(\"TP_DEBUG\") == \"true\",\n\t}\n}", "func NewHandler(logger *zap.Logger, destination string) *Handler {\n\thandler := &Handler{\n\t\tlogger: logger,\n\t\tdispatcher: provisioners.NewMessageDispatcher(logger.Sugar()),\n\t\tdestination: fmt.Sprintf(\"http://%s\", destination),\n\t}\n\t// The receiver function needs to point back at the handler itself, so set it up after\n\t// initialization.\n\thandler.receiver = provisioners.NewMessageReceiver(createReceiverFunction(handler), logger.Sugar())\n\n\treturn handler\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func (am AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(am.keeper)\n}", "func NewHandler(newEventStream NewEventStreamHandler) *Handler {\n\treturn NewHandlerBuffered(newEventStream, 0)\n}", "func NewHandler(service Service) Handler {\n\treturn Handler{service: service}\n}", "func NewLogger(client *Client, mode int, ttl time.Duration) *Logger {\n\tl := &Logger{\n\t\tclient: client,\n\t\tqueue: make(chan LogEntry, 1024),\n\t\tnow: time.Now,\n\t\tmode: mode,\n\t}\n\tif mode != LogDiscard {\n\t\tgo l.readQueue(ttl)\n\t}\n\treturn l\n}", "func (alog *AppLogger) New(requestID string) Logger {\n\t// shortcut\n\tif alog.requestID == requestID {\n\t\treturn alog\n\t}\n\n\tlg := alog.pool.Get()\n\tif nlog, ok := lg.(*AppLogger); ok {\n\t\tnlog.requestID = requestID\n\t\tnlog.SetTags(requestID)\n\n\t\treturn nlog\n\t}\n\n\treturn lg.(Logger).New(requestID)\n}", "func NewHandler() *Handler {\n\th := &Handler{\n\t\tHandler: &http.Handler{},\n\t\tProductHandler: NewProductHandler(),\n\t}\n\th.Handler.ProductHandler = h.ProductHandler.ProductHandler\n\treturn h\n}", "func newLog(prefix string) *logging.Logger {\n\tfdFmt := logging.MustStringFormatter(\n\t\t`%{level:.4s}[%{id:03x}]%{time:2006-01-02 15:04:05.000}: %{message}`,\n\t)\n\t// nolint\n\tfd, err := os.OpenFile(logFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err.Error())\n\t}\n\n\tfdLog := logging.NewLogBackend(fd, \"\", 0)\n\tfdFmttr = logging.NewBackendFormatter(fdLog, fdFmt)\n\n\tsysFmttr, err := logging.NewSyslogBackend(prog + \": \")\n\tif err != nil {\n\t\tfmt.Fprint(os.Stderr, err.Error())\n\t}\n\n\tlogging.SetBackend(fdFmttr, sysFmttr)\n\n\treturn logging.MustGetLogger(prog)\n}", "func New(coll *mongo.Collection, log logger.Logger, firebaseRepo auth.Repository) *Handler {\n\treturn &Handler{\n\t\tlog: log,\n\t\tservice: service.New(coll, log, firebaseRepo),\n\t}\n}", "func NewHandler(counter *Counter, level logging.Level) (h *Handler) {\n\treturn &Handler{\n\t\tCounter: counter,\n\t\tLevel: level,\n\t}\n}", "func (app AppModule) NewHandler() sdk.Handler {\n\treturn NewHandler(app.msKeeper, app.poaKeeper)\n}", "func NewMiddleware(l *zap.Logger) func(next http.Handler) http.Handler {\n\treturn loggerMiddleware{l}.Handler\n}", "func New(h []IHandler) *Handler {\n\treturn &Handler{handler: h}\n}", "func NewHandler(db dal.MessageDB) *Handler {\n\treturn &Handler{\n\t\tdb: db,\n\t}\n}", "func NewHandler(t mockConstructorTestingTNewHandler) *Handler {\n\tmock := &Handler{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func NewHandler(store *datastore.Datastore, running *lifecycle.Running) *Handler {\n\treturn &Handler{\n\t\tStore: *store,\n\t\tRunning: running,\n\t}\n}", "func NewHandler(service *Service) *Handler {\n\treturn &Handler{\n\t\tservice: service,\n\t}\n}", "func NewFileHandler(path string, levels ...LogLevel) Handler {\n\treturn &fileHandler{\n\t\tleveled: leveled{levels},\n\t\tpath: path,\n\t\tfile: nil,\n\t}\n}", "func NewHandler(l logger.Logger) http.Handler {\n\thandlerLogger := l.With(\"module\", moduleNameHTTPHandler)\n\tr := chi.NewRouter()\n\n\tr.Use(logger.ChiRequestLoggerMiddleware(handlerLogger))\n\tr.NotFound(transport.Error(handlerLogger, http.StatusNotFound))\n\tr.MethodNotAllowed(transport.Error(handlerLogger, http.StatusMethodNotAllowed))\n\n\tr.Route(\"/_\", func(r chi.Router) {\n\t\tr.Get(\"/health\", transport.NewHealthHandler())\n\t})\n\n\treturn r\n}", "func New(pattern string) *Handler {\n\trhandlerm.Lock()\n\tdefer rhandlerm.Unlock()\n\n\t_, exists := rhandlers[pattern]\n\tif exists {\n\t\tpanic(\"handler `\" + pattern + \"` already exists\")\n\t}\n\n\th := &Handler{\n\t\tpattern: pattern,\n\t\twstrings: make(chan wstring, 1),\n\t\twints: make(chan wint, 1),\n\t}\n\trhandlers[pattern] = h\n\twhandlers <- h\n\n\treturn h\n}", "func New(info logger.Info) (logger.Logger, error) {\n\tlogDir := removeLogDirOption(info.Config)\n\tif logDir == \"\" {\n\t\tlogDir = defaultLogDir\n\t}\n\tinfo.LogPath = filepath.Join(logDir, info.ContainerID)\n\n\tif err := os.MkdirAll(filepath.Dir(info.LogPath), 0755); err != nil {\n\t\treturn nil, fmt.Errorf(\"error setting up logger dir: %v\", err)\n\t}\n\n\treturn jsonfilelog.New(info)\n}", "func NewHandler(folderName string) *Handler {\n\treturn &Handler{BaseDir: folderName, SplitCache: make(map[[16]byte]CacheEntry, 0)}\n}", "func NewHandler(config *config.Config) *handler {\n\th := &handler{\n\t\tdailInfo: &mgo.DialInfo{\n\t\t\tPoolLimit: 4096,\n\t\t\tTimeout: time.Second,\n\t\t\tFailFast: true,\n\t\t\tUsername: config.Storage.Username,\n\t\t\tPassword: config.Storage.Password,\n\t\t\tAddrs: []string{config.Storage.Address},\n\t\t\tDatabase: config.Storage.Database,\n\t\t},\n\t\tdatabase: config.Storage.Database,\n\t}\n\treturn h\n}", "func New(notifier *gobrake.Notifier) *Handler {\n\th := Handler{notifier}\n\treturn &h\n}", "func NewLogger(prefix string, logf func(ctx context.Context, format string, args ...interface{})) datastore.Middleware {\n\treturn &logger{Prefix: prefix, Logf: logf, counter: 1}\n}", "func New(logger *logger.Logger) *Log {\n\treturn &Log{write: logger}\n}", "func NewHandler(next http.Handler) Handler {\n\treturn Handler{\n\t\tNext: next,\n\t\tLogger: JSONLogger,\n\t\tSkip: SkipHealthEndpoint,\n\t}\n}", "func loggingHandler(h http.Handler) http.Handler {\n\treturn loggingHandlerFunc(h.ServeHTTP)\n}", "func NewHandler(transport *http.Transport) http.Handler {\n\treturn &Handler{\n\t\treverseProxy: httputil.ReverseProxy{\n\t\t\tErrorLog: log.New(ioutil.Discard, \"\", 0), // prints to stderr if nil\n\t\t\tDirector: func(r *http.Request) {},\n\t\t\tTransport: transport,\n\t\t},\n\t\ttransport: transport,\n\t}\n}", "func NewHandler() sdk.Handler {\n\treturn &Handler{}\n}", "func NewHandler(db *db.Client) *Handler {\n\treturn &Handler{db}\n}", "func NewFileHandler(path string) (*FileHandler, error) {\n\tpath, _ = filepath.Abs(path)\n\n\tf := &FileHandler{\n\t\tmin: LogLevelDebug,\n\t\tmax: LogLevelFatal,\n\t\tpath: path,\n\t\tformatter: NewLineFormatter(),\n\t\tm: sync.Mutex{},\n\t}\n\n\t// Determine of the path is a file or directory\n\t// We cannot assume the path exists yet\n\tstat, err := os.Stat(path)\n\tif err == nil { // Easiest, path exists\n\t\tf.separate = stat.IsDir()\n\t\treturn f, nil\n\t}\n\n\tif !os.IsNotExist(err) {\n\t\treturn nil, err\n\t}\n\n\t// Typically an extension means it's a file\n\text := filepath.Ext(path)\n\tif ext == \"\" {\n\t\t// Attempt to create the directory\n\t\tif err := os.MkdirAll(path, 0755); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.separate = true\n\t} else {\n\t\t// Attempt to create directory path\n\t\tdir := filepath.Dir(path)\n\t\tif err := os.MkdirAll(dir, 0755); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Attempt to create the file\n\t\tfile, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfile.Close()\n\t\tf.separate = false\n\t}\n\treturn f, nil\n}", "func New(c Cache) *Handler {\n\treturn &Handler{\n\t\tcache: c,\n\t}\n}", "func NewLog(dir string, c Config) (*Log, error) {\n\tif c.Segment.MaxStoreBytes == 0 {\n\t\tc.Segment.MaxStoreBytes = 1024\n\t}\n\tif c.Segment.MaxIndexBytes == 0 {\n\t\tc.Segment.MaxIndexBytes = 1024\n\t}\n\tl := &Log{\n\t\tDir: dir,\n\t\tConfig: c,\n\t}\n\treturn l, l.setup()\n}", "func (l *Logger) NewLogEntry(r *http.Request) middleware.LogEntry {\n\te := &LogEntry{\n\t\treq: r,\n\t\tbuf: &bytes.Buffer{},\n\t}\n\n\treturn e\n}", "func newCommandHandler() *commandHandler {\n\treturn &commandHandler{make(cmdMap)}\n}", "func newCommandHandler() *commandHandler {\n\treturn &commandHandler{make(cmdMap)}\n}", "func newLogFormatter(globals server.Globals) handlers.LogFormatter {\n\treturn logFormatter{\n\t\tlogger: globals.Logger,\n\t}.format\n}", "func (l Loggers) NewLogger(name string, level logging.Level, handlers ...logging.Handler) *logging.Logger {\n\ths := []logging.Handler{}\n\tif l.writer != nil {\n\t\ths = append(hs, &logging.WriteHandler{\n\t\t\tFormatter: &logging.StandardFormatter{TimeFormat: logging.StandardTimeFormat},\n\t\t\tWriter: l.writer,\n\t\t\tLevel: logging.DEBUG,\n\t\t})\n\t} else {\n\t\tfor _, h := range handlers {\n\t\t\tif h != nil {\n\t\t\t\ths = append(hs, h)\n\t\t\t}\n\t\t}\n\t}\n\treturn logging.NewLogger(name, level, hs, 0)\n}", "func Handler(fn http.Handler) http.Handler {\n\treturn logger{fn}\n}", "func NewLoggerHandler() *LoggerHandler {\n\treturn &LoggerHandler{}\n}", "func NewLoggerHandler() *LoggerHandler {\n\treturn &LoggerHandler{}\n}", "func New(logFile string, prefix string) (*Logger, error) {\n\tlogger := new(Logger)\n\tvar err error\n\tlogger.file, err = os.OpenFile(logFile, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0600)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tlogger.logger.SetOutput(logger.file)\n\tlogger.logger.SetPrefix(prefix)\n\tlogger.logger.SetFlags(log.LstdFlags)\n\treturn logger, nil\n}", "func (path *Path) NewHandler() http.HandlerFunc {\r\n\treturn func(w http.ResponseWriter, r *http.Request) {\r\n\t\tdata, err := doRequest(path.Site, path, r)\r\n\t\tpath.Flush(w, data, err)\r\n\t}\r\n}", "func NewHandler(service service.Interface) *Handler {\n\treturn &Handler{service: service}\n}", "func New() LogWriter {\n\tinitBuf := &bytes.Buffer{}\n\treturn &logWriter{\n\t\tinitBuf: initBuf,\n\t\tw: bufio.NewWriter(initBuf),\n\t\tfirstSet: true,\n\t\twriteLock: new(sync.Mutex),\n\t\tloggers: make([]Logger, MaxLoggers),\n\t\tcurLoggersIdx: new(uint32),\n\t}\n}", "func New(config logging.Config) logging.Logger {\n\treturn rem.New(config, writeWithStd)\n}", "func NewHandler(s *Server) http.Handler {\n\treturn newHandler(s)\n}", "func New(svc event.Service, logger takrib.Logger) *LogService {\n\treturn &LogService{\n\t\tService: svc,\n\t\tlogger: logger,\n\t}\n}", "func newLogger(lineCap int) *logger {\n\treturn &logger{\n\t\tlogs: make(chan *LogLine, lineCap),\n\t}\n}", "func newLog() {\n\tlogBuffer = log.NewLogBuffer(DefaultHttpLogBuffers)\n\tsrvLog = NewSrvLog()\n\n\ttrace.DebugLogger = srvLog\n\ttrace.ErrorLogger = srvLog\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\ttemplateStore: defaultTemplateStore,\n\t\tactions: make([]HandlerAction, 0),\n\t}\n}", "func NewLogger(logLevel int, file string) Logger {\n\tif logLevel > LogDebug {\n\t\tlogLevel = LogDebug2\n\t}\n\tif logLevel < LogFatal {\n\t\tlogLevel = LogFatal\n\t}\n\tf, err := newLog(file)\n\tif err != nil {\n\t\tpanic(\"Cannot instantiate logger with file \" + file)\n\t}\n\tw := log.New(f, \"\", log.Lshortfile|log.LUTC|log.LstdFlags)\n\treturn &logHandler{logLevel, w, f, file}\n}", "func New(ctrl *storagecluster.Controller) *Handler {\n\treturn &Handler{\n\t\tctrl: ctrl,\n\t\tclient: ctrl.GetKubernetesClient(),\n\t\tdriver: ctrl.Driver,\n\t}\n}", "func NewLog(appender Appender, prefix string, tags ...string) (res *Log) {\n\tres = &Log{\n\t\ttags: tags,\n\t\tprefix: prefix,\n\t\tappenderPtr: new(unsafe.Pointer),\n\t\tcallDepth: 2,\n\t}\n\tres.SetAppender(appender)\n\treturn\n}", "func NewHandler(config *core.Config, requestQueue chan<- string, maxQueueSize int, debug *log.Logger) *Handler {\n\th := Handler{\n\t\tconfig: config,\n\t\tdebug: debug,\n\t\trequestQueue: requestQueue,\n\t\tmaxQueueSize: maxQueueSize,\n\t}\n\treturn &h\n}", "func NewHandler(config *api.APIConfig, service Service, databaseClient database.Client) Handler {\n\treturn Handler{\n\t\tconfig: config,\n\t\tservice: service,\n\t\tdatabaseClient: databaseClient,\n\t}\n}", "func NewHandler(fp string, fs http.FileSystem, fc FragmentCache) http.Handler {\n\treturn &Handler{fs, fc, fp}\n}", "func newHandler(conn net.Conn, l logger, c *config, users map[string]string) (*handler, error) {\n\t// get current directory\n\tdir, err := os.Getwd()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// create a new handler object\n\th := &handler{\n\t\tconfig: c,\n\t\tconn: conn,\n\t\tlogger: l,\n\t\tdir: dir,\n\t\tusers: users,\n\t\tisLoggedIn: false,\n\t\tcommands: make(map[CommandCode]handleFunc),\n\t}\n\n\th.logMessage(fmt.Sprintf(\"Accepted connection from %v\", h.conn.RemoteAddr()))\n\n\t// initialize commands for not logged in state\n\th.initCommandTable()\n\n\t//initialize default data connection\n\tif h.config.pasv {\n\t\th.initPassiveDataConn()\n\t} else {\n\t\t// calculate default data port\n\t\thost, port, err := net.SplitHostPort(conn.RemoteAddr().String())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tvar portNum int\n\t\t_, err = fmt.Sscanf(port, \"%d\", &portNum)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tportNum++\n\t\tport = fmt.Sprintf(\"%d\", portNum)\n\t\th.initActiveDataConn(net.JoinHostPort(host, port))\n\t}\n\n\treturn h, nil\n}", "func NewHandler(path string) *Handler {\n\treturn &Handler{\n\t\tpath: path,\n\t}\n}", "func newHandler(chain *Chain, handler Handler) (ch *ChainHandler) {\n\tch = new(ChainHandler)\n\tch.chain = chain\n\tch.handler = handler\n\treturn\n}", "func NewHandler(cfg *config.Config) Handler {\n\treturn &handler{\n\t\tcfg: cfg,\n\t}\n}", "func NewHandler(repository Repository) *Handler {\n\treturn &Handler{repository: repository}\n}", "func NewHandler(config HandlerConfig) *handler {\n\treturn &handler{config: config}\n}", "func NewHandler(gp types.GamePoolAbstraction, m persistence.MongoAbstraction, l *log.Logger) (h *Handler) {\n\tif gp == nil {\n\t\tpanic(\"GamePool argument is nil\")\n\t}\n\tif m == nil {\n\t\tpanic(\"MongoSession argument is nil\")\n\t}\n\tif l == nil {\n\t\tpanic(\"Logger argument is nil\")\n\t}\n\th = &Handler{\n\t\tgPool: gp,\n\t\tmongo: m,\n\t\tlogger: l,\n\t}\n\tl.Printf(\"Startup: Handler created\")\n\treturn\n}", "func New(w io.Writer) *Logger {\n\treturn &Logger{w: w}\n}", "func NewHandler() *Handler {\n\treturn &Handler{\n\t\tevents: []*event.Event{},\n\t}\n}", "func New(reader Reader, ctx context.Context) *Handler {\n\treturn &Handler{\n\t\treader: reader,\n\t}\n}", "func newFileLogger() *fileLogger {\n\t// Open the log file for writing.\n\tf, err := os.OpenFile(*logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\tif err != nil {\n\t\tglog.Fatalf(\"could not open log file: %v\", err)\n\t}\n\treturn &fileLogger{f: f}\n}" ]
[ "0.759498", "0.7515866", "0.7479773", "0.7462031", "0.7342905", "0.727814", "0.7169634", "0.71449417", "0.7024961", "0.70092463", "0.6963473", "0.6908752", "0.6862878", "0.662858", "0.66166955", "0.65458745", "0.65179574", "0.64601105", "0.64248633", "0.64237076", "0.6400495", "0.63970053", "0.6373994", "0.6373994", "0.6373994", "0.6367612", "0.6365383", "0.6351665", "0.633116", "0.6330594", "0.6313067", "0.6313067", "0.6313067", "0.63071626", "0.62768114", "0.62717414", "0.62524813", "0.6251107", "0.625041", "0.62441325", "0.623943", "0.62297857", "0.62101567", "0.6205517", "0.61960423", "0.6184068", "0.61776376", "0.6174293", "0.61695117", "0.61682606", "0.6146667", "0.61339825", "0.61319655", "0.6120174", "0.6119859", "0.6116545", "0.61137086", "0.61120695", "0.6095032", "0.6091875", "0.60869735", "0.6086562", "0.608426", "0.60802734", "0.60751086", "0.60735685", "0.60675836", "0.60675836", "0.60664266", "0.60646343", "0.60644084", "0.60628015", "0.60628015", "0.60618526", "0.605766", "0.6057593", "0.6054524", "0.6052749", "0.60495126", "0.6047332", "0.6033625", "0.60255176", "0.60167724", "0.6016513", "0.6015263", "0.6013959", "0.6013724", "0.60136473", "0.60128146", "0.600862", "0.60069484", "0.59975624", "0.5995464", "0.5993444", "0.59928024", "0.5988853", "0.5985952", "0.59845644", "0.5981578", "0.5981258" ]
0.7025196
8
Handle takes care of an error by logging it.
func (h *LogHandler) Handle(err error) { h.logger.Error(err) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func Handle(err error) {\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func Handle(err error) {\n\tif err != nil {\n\t\tlog.Panic(err)\n\t}\n}", "func handleError(err error) {\n\tif err != nil {\n\t\tlog.Println(err.Error()) // Just for example purpose. You should use proper error handling instead of panic\n\t}\n}", "func Handle(err error) {\n\tif err != nil {\n\t\tpc, _, ln, _ := runtime.Caller(1)\n\t\tdetails := runtime.FuncForPC(pc)\n\t\tlog.Printf(\"Fatal: %s - %s %d\", err.Error(), details.Name(), ln)\n\n\t\t// log to sentry\n\t\tsentry.CaptureException(err)\n\t\tsentry.Flush(time.Second * 5)\n\t}\n}", "func handleError(err error) {\n\tif err != nil {\n\t\tlog.Fatalf(\"%v\", err)\n\t}\n}", "func (config *Configuration) errorHandle(\n\terr error,\n\twriter http.ResponseWriter,\n\tlogging logging.Logging) bool {\n\tif err != nil {\n\t\terrorString := err.Error()\n\t\tlogging.Error(errorString)\n\t\tif !config.Development {\n\t\t\terrorString = \"An internal server has occurred, please contact [email protected]\"\n\t\t}\n\t\thttp.Error(writer, errorString, 500)\n\t\treturn true\n\t}\n\treturn false\n}", "func (c *CaddyController) handleErr(err error, action interface{}) {\n\tlogrus.Error(err)\n}", "func HandleError(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tpanic(err)\n\t}\n}", "func handleError(w http.ResponseWriter, err error, prefix string, logger api.Logger) {\n\tmessage := prefix\n\tif message != \"\" {\n\t\tmessage += \": \"\n\t}\n\tmessage += err.Error()\n\tlogger.Error(message)\n\tvar ec int\n\tswitch e := err.(type) {\n\tcase *errorx.Error:\n\t\tswitch e.Code() {\n\t\tcase errorx.NOT_FOUND:\n\t\t\tec = http.StatusNotFound\n\t\tdefault:\n\t\t\tec = http.StatusBadRequest\n\t\t}\n\tdefault:\n\t\tec = http.StatusBadRequest\n\t}\n\thttp.Error(w, message, ec)\n}", "func HandleErr(c *gin.Context, err error) error {\n\tif err != nil {\n\t\tc.Error(err)\n\t}\n\treturn err\n}", "func (ths *ReceiveBackEnd) handleError(w http.ResponseWriter, r *http.Request) {\n\tdefer r.Body.Close();\n\tths.log.Println(\"Error request arrived...\");\n\thttp.Error(w, \"No such service\", http.StatusBadGateway);\n}", "func handleError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func handleError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func handleError(err error) {\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func HandleError(err error) {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}", "func handleError(err error) {\r\n\tif err != nil {\r\n\t\tpanic(err)\r\n\t}\r\n}", "func HandleErr(w http.ResponseWriter, err error) {\n\thttp.Error(w, fmt.Sprintf(\"%+v\", err), 500)\n}", "func Handle(err error) {\n\n\tlog.Error(err.Error())\n\tlog.Warn(\"Cauldron stopped\\n\")\n\n\tos.Exit(1)\n}", "func Handle(ctx context.Context, rp interface{}) {\n\tpw, ok := rp.(*PanicWrap)\n\tif ok {\n\t\tlog.Ctx(ctx).Error().Msgf(\"Panic: %v\", pw.err)\n\t\trp = pw.err // unwrap error\n\t} else {\n\t\tlog.Ctx(ctx).Error().Msgf(\"Error: %v\", rp)\n\t}\n\tlog.Stack(ctx)\n\n\tsentryEvent{ctx, nil, rp, \"\"}.Send()\n}", "func handleError(err error) {\n\tlogger.L.Fatalf(\"config error %v\", err.Error())\n}", "func HandleError(res http.ResponseWriter, e error) {\n\t// generic error handling for any error we encounter.\n\tif e != nil {\n\t\thttp.Error(res, e.Error(), http.StatusInternalServerError)\n\t}\n}", "func handleErr(w http.ResponseWriter, errorcode int, err error, msg string) {\n\tif err != nil {\n\t\tlogger.WithField(\"error\", err.Error()).Error(msg)\n\t} else {\n\t\tlogger.Error(msg)\n\t}\n\thttp.Error(w, \"\", errorcode)\n}", "func (h *TestHandler) Handle(err error) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\n\th.errors = append(h.errors, err)\n}", "func HandleErr(err error, message string) {\n\tif err != nil {\n\t\tlog.Fatal().Err(err).Msg(message)\n\t}\n}", "func defaulErrHandle(c *Context, err interface{}) {\n\tvar msg interface{}\n\tswitch err.(type) {\n\tcase string:\n\t\tmsg = err.(string)\n\tcase error:\n\t\tmsg = err.(error).Error()\n\tcase []interface{}:\n\t\tmsg = err.([]interface{})\n\tcase map[string]string:\n\t\tmsg = err.(map[string]string)\n\tcase []string:\n\t\tmsg = err.([]string)\n\t}\n\tvar code interface{}\n\t// default code :request params failed to exam.\n\tcode = 402\n\tif c.ErrCode != nil {\n\t\tcode = c.ErrCode\n\t}\n\tc.GinContext.JSON(http.StatusOK, gin.H{\n\t\t\"state\": 0,\n\t\t\"code\": code,\n\t\t\"msg\": msg,\n\t})\n\tc.GinContext.Abort()\n}", "func errHandle(w http.ResponseWriter, longmsg string, shortmsg string, status int) {\n\tlog.Errorf(longmsg)\n\terrorResponse := ErrorResponse{\n\t\tStatus: status,\n\t\tErrorMessage: shortmsg,\n\t}\n\tdata, _ := json.Marshal(errorResponse)\n\tresponse := JSONResponse{}\n\tresponse.status = http.StatusUnauthorized\n\tresponse.data = data\n\tresponse.Write(w)\n}", "func HandleError(page http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\tif response, ok := r.(database.ErrorResponse); ok {\n\t\t\t\t\tif response.ErrorObject != nil {\n\t\t\t\t\t\traven.CaptureError(response.ErrorObject, nil)\n\t\t\t\t\t}\n\t\t\t\t\tdata, _ := json.Marshal(response)\n\t\t\t\t\thttp.Error(res, string(data), http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t}\n\t\t}()\n\t\tpage(res, req)\n\t})\n}", "func RouteHandler(w http.ResponseWriter, r *http.Request) {\n\turl := r.URL.Path\n\t// fmt.Println(\"]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]] url: \", url)\n\t// 1. skip special resources. TODO Expand to config. // TODO better this\n\tif url == \"/favicon.ico\" {\n\t\treturn\n\t}\n\n\tvar starttime time.Time\n\tif config.ROUTE_PRINT_TIME {\n\t\tfmt.Println(\">>> Start Logging time. now is: \", time.Now())\n\t\tstarttime = time.Now()\n\t}\n\tprintAccessHeader(r)\n\n\t// -------- Error Handling --------------------------------------------------------------\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\n\t\t\tif !enable_error_handler {\n\t\t\t\tif true { // Debug print\n\t\t\t\t\tfmt.Println(\"\\n_______________________________________________________________\")\n\t\t\t\t\tfmt.Println(\"---- DEBUG: ErrorHandler >> Meet An Error -------------------------\")\n\t\t\t\t\t// fmt.Println(reflect.TypeOf(err))\n\t\t\t\t\tif e, ok := err.(error); ok {\n\t\t\t\t\t\tfmt.Println(debug.StackString(e))\n\t\t\t\t\t} else if s, ok := err.(string); ok {\n\t\t\t\t\t\terr = fmt.Errorf(s)\n\t\t\t\t\t\tdebug.DebugPrintVariable(err)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tdebug.DebugPrintVariable(err)\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Println(\"-------------------------------------------------------------------\")\n\t\t\t\t\tfmt.Println(\"- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - --\")\n\t\t\t\t\tfmt.Println(\"\")\n\t\t\t\t}\n\n\t\t\t\tw.Header().Add(\"content-type\", \"text/plain\")\n\t\t\t\tw.Write([]byte(fmt.Sprint(\"[ErrorHandler can't handler this error!]<br>\\n\")))\n\t\t\t\tw.Write([]byte(fmt.Sprint(err)))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Error hancler process.\n\n\t\t\tfmt.Println(\"\\n============= ErrorHandler: Panic Occured. =============\")\n\t\t\t// Give control to ErrorHandler if panic occurs.\n\t\t\tif b := errorhandler.Process(w, r, err); b == false {\n\t\t\t\t// return\n\t\t\t\tif false { // **** disable this function\n\t\t\t\t\tw.Header().Add(\"content-type\", \"text/plain\")\n\t\t\t\t\tw.Write([]byte(fmt.Sprint(\"[ErrorHandler can't handler this error, it returns false]\")))\n\t\t\t\t\tw.Write([]byte(fmt.Sprint(err)))\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\n\t\t// clear request scope data store.:: should clear context here? Where to?\n\t\tcontext.Clear(r)\n\n\t\tif config.ROUTE_PRINT_TIME {\n\t\t\tfmt.Println(\">>> Request Execution Time: \", time.Now().Sub(starttime))\n\t\t}\n\t\tprintAccessFooter(r)\n\n\t\t// this route is ended here.\n\t}()\n\t// -------- Routing... --------------------------------------------------------------\n\n\t// 3. let'sp find the right pages.\n\tresult := lookup(url)\n\tif logRoute.Trace() {\n\t\tlogRoute.Printf(\"Lookup(%s) is:\\n%v\", url, result)\n\t}\n\tif result == nil && !result.IsValid() {\n\t\tpanic(exception.NewPageNotFoundError(fmt.Sprintf(\"Page %s not found!\", r.URL.Path)))\n\t}\n\n\t// TODO Later: Create New page object every request? howto share some page object? see tapestry5.\n\n\tvar lcc *lifecircle.LifeCircleControl\n\n\t// Check if this is an page request after redirect.\n\t// if has verification code, this is a redirect page and with some data.\n\tpageRedirectVerificationKeys, ok := r.URL.Query()[config.VERIFICATION_CODE_KEY]\n\tif ok && len(pageRedirectVerificationKeys) > 0 {\n\t\tfmt.Println(\"********************************************************************************\")\n\t\tfmt.Println(\"********************************************************************************\")\n\n\t\tvar flash_session_key = config.PAGE_REDIRECT_KEY + pageRedirectVerificationKeys[0]\n\t\tsessionId := sessions.SessionId(r, w) // called when needed.\n\t\tif targetPageInterface, ok := sessions.GetOk(sessionId, flash_session_key); ok {\n\t\t\tfmt.Println(\"key is \", flash_session_key)\n\t\t\tfmt.Println(\"target page interface is \", targetPageInterface)\n\t\t\tif targetPage, ok := targetPageInterface.(core.Pager); ok {\n\t\t\t\tlcc = lifecircle.NewPageFlowFromExistingPage(w, r, targetPage)\n\t\t\t\tfmt.Println(\"successfully get targetpage and continue. TODO:!!!!! here is a memory leak!\")\n\n\t\t\t\t// remove targetpage from session. OR will memery leak!!\n\t\t\t\tsessions.Delete(sessionId, flash_session_key)\n\t\t\t}\n\t\t}\n\t\tfmt.Println(\"********************************************************************************\")\n\t\tfmt.Println(\"********************************************************************************\")\n\t}\n\n\t// ************************************************************\n\t// Normal request page flow, create then flow.\n\t// ************************************************************\n\tif lcc == nil {\n\t\tlcc = lifecircle.NewPageFlow(w, r, result.Segment)\n\t}\n\tlcc.SetParameters(result.Parameters)\n\tlcc.SetEventName(result.EventName) // ?\n\n\t// set lcc to session\n\tlcc.SetToRequest(config.LCC_OBJECT_KEY, lcc)\n\n\t// Done: print some information.\n\tdefer func() {\n\t\t// fmt.Println(\"---- [defer] ------------------------\")\n\t\t// fmt.Println(\"Describe the page structure:\")\n\t\t// fmt.Println(lcc.PrintCallStructure())\n\n\t\t// fmt.Println(\"-- Page Result is ---------\")\n\t\t// fmt.Println(result)\n\t}()\n\n\t// Process result & returns.\n\tif !result.IsEventCall() {\n\t\t// page render flow\n\t\tlcc.PageFlow()\n\t\t// handleReturn(lcc, result.Segment)\n\t} else {\n\t\t// event call\n\t\tlcc.EventCall(result)\n\n\t\t// TODO wrong here. this is wrong. sudo refactor lifecircle-return.\n\t\t// if lcc not returned, return the current page.\n\t\tif lcc.Err != nil {\n\t\t\tpanic(lcc.Err.Error())\n\t\t}\n\t\t// // default return the current page.\n\t\t// if result.Segment != nil && lcc.ResultType == \"\" {\n\t\t// \turl := lcc.r.URL.Path\n\t\t// \thttp.Redirect(lcc.w, lcc.r, url, http.StatusFound)\n\t\t// }\n\t}\n}", "func ErrorHandling(err error, requestId int64) model.Response {\n\n\t//Variable declaration\n\tvar Response model.Response\n\n\tif err != nil {\n\t\tResponse.Code = SomeThingWentWrong\n\t\tResponse.Description = StatusCodes(SomeThingWentWrong)\n\t}\n\n\t//Inserting error in DB\n\tutilityData.InsertErrorLogs(requestId, fmt.Sprint(errors.Errorf(err.Error()).ErrorStack()))\n\tif err != nil {\n\t\tResponse.Code = SomeThingWentWrong\n\t\tResponse.Description = StatusCodes(SomeThingWentWrong)\n\n\t}\n\treturn Response\n}", "func (h *NullHandler) Handle(err error) {\n}", "func (t *LogProviderHandler) Handle(chain *Chain, i *invocation.Invocation, cb invocation.ResponseCallBack) {\n\tif !config.GlobalDefinition.Ggs.AccessLog.Enabled {\n\t\tchain.Next(i, cb)\n\t\treturn\n\t}\n\n\tl, err := newLogParams(i)\n\tif err != nil {\n\t\tchain.Next(i, cb)\n\t\treturn\n\t}\n\n\tchain.Next(i, func(r *invocation.Response) (err error) {\n\t\terr = cb(r)\n\n\t\tl.format(r.Status, r.Err)\n\t\treturn\n\t})\n}", "func handleErr(err error, w http.ResponseWriter) {\n\tif err != nil {\n\t\tlog.Println(\"jwt/handler.go: Error \" + err.Error())\n\t\tw.WriteHeader(500)\n\t}\n}", "func HandlePanic(c lars.Context, trace []byte) {\n\n\t// redirect to or directly render friendly error page\n}", "func (c *Controller) HandlePanic(v interface{}) {\n status := http.StatusInternalServerError\n switch e := v.(type) {\n case *perror.Error:\n status = e.Status()\n c.Json(EmptyObject, status, e.Message())\n default:\n c.Json(EmptyObject, status)\n }\n\n c.Context().Error(\"%s, trace[%s]\", util.ToString(v), util.PanicTrace(TraceMaxDepth, false))\n}", "func Handle(w http.ResponseWriter, mutator func() error) {\n\terr := mutator()\n\tif err == nil {\n\t\tw.WriteHeader(http.StatusOK)\n\t\treturn\n\t}\n\tswitch err := err.(type) {\n\tcase errs.BadRequestError:\n\t\thttperr.ClientError(w, err.Error())\n\tcase errs.UnauthorizedError:\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\tw.Write([]byte(err.Error()))\n\tdefault:\n\t\thttperr.ServerError(w, err.Error())\n\t}\n}", "func handleError(URL string, resp *http.Response) error {\n\terrBytes, _ := ioutil.ReadAll(resp.Body)\n\terrInfo := string(errBytes)\n\t// Check if we have a JSON representation of the failure, if so decode it.\n\tif resp.Header.Get(\"Content-Type\") == contentTypeJSON {\n\t\terrorResponse, err := unmarshallError(errBytes)\n\t\t//TODO (hduran-8): Obtain a logger and log the error\n\t\tif err == nil {\n\t\t\terrInfo = errorResponse.Error()\n\t\t}\n\t}\n\thttpError := &HttpError{\n\t\tresp.StatusCode, map[string][]string(resp.Header), URL, errInfo,\n\t}\n\tswitch resp.StatusCode {\n\tcase http.StatusNotFound:\n\t\treturn errors.NewNotFoundf(httpError, \"\", \"Resource at %s not found\", URL)\n\tcase http.StatusForbidden, http.StatusUnauthorized:\n\t\treturn errors.NewUnauthorisedf(httpError, \"\", \"Unauthorised URL %s\", URL)\n\tcase http.StatusBadRequest:\n\t\tdupExp, _ := regexp.Compile(\".*already exists.*\")\n\t\tif dupExp.Match(errBytes) {\n\t\t\treturn errors.NewDuplicateValuef(httpError, \"\", string(errBytes))\n\t\t}\n\t}\n\treturn httpError\n}", "func badErrHandler(err error) {\n\tif err != nil {\n\t\tclient.Ux.Print(fmt.Sprint(err))\n\t\tpanic(err)\n\t}\n}", "func (h CatchAllHandler) Handle() http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\th.WriteErrorResponse(r.Context(), w, &apperrors.UnknownRouteError{Path: r.URL.Path})\n\t}\n}", "func Handler() {\n\terr := recover()\n\tif err == nil {\n\t\treturn\n\t}\n\tm, ok := err.(msg)\n\tif !ok {\n\t\tpanic(err)\n\t}\n\tif m.string > \"\\n\" {\n\t\tswitch {\n\t\tcase m.Logger != nil:\n\t\t\tm.Logger.Print(m.string)\n\t\tcase terminal.IsTerminal(int(os.Stderr.Fd())):\n\t\t\tlog.SetFlags(0)\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tlog.Print(m.string)\n\t\t}\n\t}\n\tos.Exit(m.ExitCode)\n}", "func (h DefaultHandler) Handle(client *hub.Client, data []byte) {\n\tclient.SendJSON(\"error\", \"unknown message type\")\n}", "func (h *TaskHandler) panicHandler(w http.ResponseWriter, r *http.Request, rcv interface{}) {\n\tctx := r.Context()\n\tpe := &errors2.Error{\n\t\tCode: errors2.EInternal,\n\t\tMsg: \"a panic has occurred\",\n\t\tErr: fmt.Errorf(\"%s: %v\", r.URL.String(), rcv),\n\t}\n\n\tif entry := h.log.Check(zapcore.ErrorLevel, pe.Msg); entry != nil {\n\t\tentry.Stack = string(debug.Stack())\n\t\tentry.Write(zap.Error(pe.Err))\n\t}\n\n\th.HandleHTTPError(ctx, pe, w)\n}", "func (s *Service) Handle(path string, handle http.HandlerFunc) {\n\ts.h.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {\n\t\tstatus := \"success\"\n\n\t\t// 请求结束,打印日志\n\t\tdefer func(start time.Time) {\n\t\t\t// 打印请求日志\n\t\t\t// 格式样例:\n\t\t\t// 2019/09/16 15:53:04 [Access] success 127.0.0.1 /todo/add 0.233\n\t\t\tlog.Printf(\n\t\t\t\t\"[Access] %s %s %s %.3f\\n\",\n\t\t\t\tstatus, // 接口响应状态 success failed\n\t\t\t\tstrings.Split(r.RemoteAddr, \":\")[0],\n\t\t\t\tpath, // 接口路径\n\t\t\t\tfloat64(time.Now().Sub(start).Nanoseconds())/1e6, // 接口响应时间,毫秒\n\t\t\t)\n\t\t}(time.Now())\n\n\t\t// 拦截接口处理逻辑中的panic,并标记请求失败\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tlog.Printf(\"[Error] [panic] %v\\n\", err)\n\t\t\t\tstatus = \"failed\"\n\t\t\t\tresp(w, 10000, nil)\n\t\t\t}\n\t\t}()\n\n\t\thandle(w, r)\n\t})\n}", "func (mr *MockqueueTaskMockRecorder) HandleErr(err interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"HandleErr\", reflect.TypeOf((*MockqueueTask)(nil).HandleErr), err)\n}", "func (o *singleObserver) Handle(item interface{}) {\n\tswitch item := item.(type) {\n\tcase error:\n\t\to.errHandler(item)\n\t\treturn\n\tdefault:\n\t\to.nextHandler(item)\n\t}\n}", "func handleErr(w http.ResponseWriter, statusCode int, msg string) {\n\tw.WriteHeader(statusCode)\n\tw.Write([]byte(msg + \"\\n\"))\n}", "func Handle(f func(error)) {\n\ta := recover()\n\tif a != nil {\n\t\tif fc, ok := a.(failedCheck); ok {\n\t\t\tf(fc.err)\n\t\t} else {\n\t\t\tpanic(a)\n\t\t}\n\t}\n}", "func handleErr(e error, msg string){\n\tif e != nil {\n\t\tfmt.Println(msg)\n\t\tos.Exit(0)\n\t}\n}", "func errHandler(w http.ResponseWriter, code int, err error) {\n\tlog.Println(\"Error:\", err)\n\thttp.Error(w, http.StatusText(code), code)\n}", "func HandleErrLog(err error, text string) {\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %v at %v\", err, text)\n\t}\n}", "func (l *logPipe) Handle(line string) error {\n\tif l.handleFunc == nil {\n\t\treturn nil\n\t}\n\tif l.Match(line) {\n\t\treturn l.handleFunc(line)\n\t}\n\treturn nil\n}", "func Error(w http.ResponseWriter, r *http.Request, err error) {\n\thandler, ok := err.(http.Handler)\n\tif !ok {\n\t\terrCode, ok := err.(ErrorCode)\n\t\tif !ok {\n\t\t\terrCode = errcode.Add(500, err)\n\t\t}\n\t\thandler = errorCodeHandler{\n\t\t\terr: errCode,\n\t\t}\n\t}\n\thandler.ServeHTTP(w, r)\n}", "func (h ErrorHandler) HandleRequest(c context.Context, fc *fasthttp.RequestCtx) error {\n\treturn errorHandle(HTTPHandlerFunc(h), c, fc)\n}", "func handleError(er error) {\n\tif er != nil {\n\t\tfmt.Fprintf(os.Stderr, \"cat: %v\\n\", er)\n\t}\n}", "func errorHandler(err error) {\n\tpanic(err)\n}", "func HandleErr(handler func(error)) {\n\tif r := recover(); r != nil {\n\t\tif e, ok := r.(wrap); ok {\n\t\t\thandler(e.err)\n\t\t} else {\n\t\t\tpanic(r)\n\t\t}\n\t}\n}", "func HandleErr(ctx context.Context, errCh <-chan error, errFn func(error)) {\n\tfor {\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn\n\t\tcase err := <-errCh:\n\t\t\terrFn(err)\n\t\t}\n\t}\n}", "func (e *DefaultErrorHandler) Error(err error) {\n\tlog.Print(\"error: \", err)\n}", "func errHandler(err error) {\n\tlog.Fatal(err)\n\tos.Exit(1)\n}", "func HandleEntry(e *Entry) {\n\tLogger.HandleEntry(e)\n}", "func runHandle(fn func() error) {\n\tif err := fn(); err != nil {\n\t\tlog.Errorf(\"An error occurred when processing a VM update: %v\\n\", err)\n\t}\n}", "func (e TPMFmt1Error) Handle() (bool, int) {\n\tif e.subject != handleRelated {\n\t\treturn false, 0\n\t}\n\treturn true, e.index\n}", "func errHandler(context router.Context, e error) {\n\n\t// Cast the error to a status error if it is one, if not wrap it in a Status 500 error\n\terr := router.ToStatusError(e)\n\n\tview := view.New(context)\n\n\tview.AddKey(\"title\", err.Title)\n\tview.AddKey(\"message\", err.Message)\n\n\tif !context.Production() {\n\t\tview.AddKey(\"status\", err.Status)\n\t\tview.AddKey(\"file\", err.FileLine())\n\t\tview.AddKey(\"error\", err.Err)\n\t}\n\n\t// Set the status correctly for errors\n\tcontext.Writer().WriteHeader(err.Status)\n\n\t// Use our error template\n\tview.Template(\"app/views/error.html.got\")\n\n\tcontext.Logf(\"#error %s\\n\", err)\n\tview.Render()\n}", "func defaultHandle(writer http.ResponseWriter, request *http.Request) {\n\tlog.Println(\"Not valid route\")\n\thttp.Error(writer, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)\n}", "func (m *Middleware) Handle(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstartAt := util.TimeNow()\n\n\t\ttraceID := util.StrUniqueID()\n\t\tlogger := NewLogger(m.Writer, m.MinOutSeverity, traceID)\n\t\tctx := r.Context()\n\t\tctx = SetLogger(ctx, logger)\n\n\t\tdefer func() {\n\t\t\tif rcvr := recover(); rcvr != nil {\n\t\t\t\tmsg := Panic(ctx, rcvr)\n\t\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t\tw.Write([]byte(msg))\n\n\t\t\t\tendAt := util.TimeNow()\n\t\t\t\tdr := endAt.Sub(startAt)\n\n\t\t\t\tlogger.WriteRequest(r, endAt, dr)\n\t\t\t}\n\t\t}()\n\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\n\t\tendAt := util.TimeNow()\n\t\tdr := endAt.Sub(startAt)\n\n\t\tlogger.WriteRequest(r, endAt, dr)\n\t})\n}", "func (h Handler) Handle(ctx context.Context, input events.KinesisEvent) error {\n\t// create a request-specific logger, attach it to ctx, and add the Lambda request ID.\n\tctx = logger.NewContext(ctx, logger.New(os.Getenv(\"APP_NAME\")))\n\tif lambdaContext, ok := lambdacontext.FromContext(ctx); ok {\n\t\tlogger.FromContext(ctx).AddContext(\"aws-request-id\", lambdaContext.AwsRequestID)\n\t}\n\tif err := h.handle(ctx, input); err != nil {\n\t\tlogger.FromContext(ctx).ErrorD(\"error\", logger.M{\n\t\t\t\"error\": err.Error(),\n\t\t})\n\t\t// do not return the error, as we need to guarantee that the lambda continues to process events\n\t}\n\treturn nil\n}", "func (p *VolumePlugin) handleErrorResponse(resp *http.Response, endpoint, volName string) error {\n\t// The official plugin reference implementation uses HTTP 500 for\n\t// errors, but I don't think we can guarantee all plugins do that.\n\t// Let's interpret anything other than 200 as an error.\n\t// If there isn't an error, don't even bother decoding the response.\n\tif resp.StatusCode != http.StatusOK {\n\t\terrResp, err := io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"reading response body from volume plugin %s: %w\", p.Name, err)\n\t\t}\n\n\t\terrStruct := new(volume.ErrorResponse)\n\t\tif err := json.Unmarshal(errResp, errStruct); err != nil {\n\t\t\treturn fmt.Errorf(\"unmarshalling JSON response from volume plugin %s: %w\", p.Name, err)\n\t\t}\n\n\t\treturn p.makeErrorResponse(errStruct.Err, endpoint, volName)\n\t}\n\n\treturn nil\n}", "func (c *LogrusAdapter) Handle(e ulog.Entry) {\n\tl := c.Logger\n\tfor _, f := range e.Fields() {\n\t\tl = l.WithField(f.Key, f.Value)\n\t}\n\tswitch e.Level {\n\tcase ulog.ErrorLevel:\n\t\tl.Error(e.Message)\n\tcase ulog.WarnLevel:\n\t\tl.Warn(e.Message)\n\tcase ulog.InfoLevel:\n\t\tl.Info(e.Message)\n\tcase ulog.DebugLevel:\n\t\tl.Debug(e.Message)\n\t}\n}", "func (handler LogHandler) Handle(params operations.LogParams) middleware.Responder {\n\tevent := strings.TrimSpace(params.Event)\n\terr := validator.ValidateJSONFormat(event)\n\tif err != nil {\n\t\treturn operations.NewLogBadRequest()\n\t}\n\n\t// Add a `via_kayvee_logger_service` field to identify logs proxied through\n\t// this service.\n\tvar kayveeData map[string]interface{}\n\tjson.Unmarshal([]byte(event), &kayveeData)\n\tkayveeData[\"via_kayvee_logger_service\"] = true\n\tfinalOutput, _ := json.Marshal(kayveeData)\n\n\thandler.logger.Println(string(finalOutput))\n\n\treturn operations.NewLogOK()\n}", "func (h *Handler) Handle(ctx context.Context, conn *jsonrpc2.Conn, req *jsonrpc2.Request) {\n\tif resp, err := h.handle(req.Method, req.Params); err != nil {\n\t\t// check if the error is a jsonrpc error\n\t\tjsonerr, ok := err.(*jsonrpc2.Error)\n\n\t\tif !ok {\n\t\t\t// if it's not a jsonrpc error then create a CodeInternalError\n\t\t\tjsonerr = &jsonrpc2.Error{\n\t\t\t\tCode: jsonrpc2.CodeInternalError,\n\t\t\t\tMessage: fmt.Sprintf(\"%s\", err),\n\t\t\t}\n\t\t}\n\n\t\tif err := conn.ReplyWithError(ctx, req.ID, jsonerr); err != nil {\n\t\t\tlog.Error(\"Failed to send error response: %s\", err)\n\t\t}\n\t} else if resp != nil {\n\t\tif err := conn.Reply(ctx, req.ID, resp); err != nil {\n\t\t\tlog.Error(\"Failed to send response: %s\", err)\n\t\t}\n\t}\n}", "func (r *Handler) Error(w *libweb.Watch, err error) {\n\tlog.Info(\n\t\t\"event: error.\",\n\t\t\"id\",\n\t\tr.id,\n\t\t\"error\",\n\t\terr.Error())\n\tif !r.ended {\n\t\t_ = w.Repair()\n\t}\n}", "func (l *LoggingCallback) Handle(s measurement.Sample) error {\n\tsampleFields := []zapcore.Field{}\n\tsampleFields = append(sampleFields, zap.String(\"device\", s.DeviceName()))\n\tfor k, v := range s.Tags() {\n\t\tsampleFields = append(sampleFields, zap.String(k, v))\n\t}\n\tfor _, d := range s.Datapoints() {\n\t\tsampleFields = append(sampleFields, zap.Float32(d.Name(), d.Value()))\n\t}\n\t// if no data given in sample, report that instead\n\tif len(sampleFields) == 1 {\n\t\tl.logger.Info(\"no data from device\")\n\t} else {\n\t\tl.logger.Info(\"device successfully read\",\n\t\t\tsampleFields...,\n\t\t)\n\t}\n\treturn nil\n}", "func Handle(h Handler) {\n\tHandleFunc(HandlerFunc(h.HandleLogs))\n}", "func ServeHandleIncorrect(w http.ResponseWriter, r *http.Request) {\n\thttp.Error(w, \"Handle Incorrect\", http.StatusNotFound)\n}", "func ErrHandler(err error) {\n\tif err != nil {\n\t\tswitch os.Getenv(\"RUNMODE\") {\n\t\tcase \"production\":\n\t\t\tL.Error(\"Error occured\", \"error\", err)\n\t\tcase \"testing\":\n\t\t\tlog.Root().SetHandler(LogFuncHandler)\n\t\t\tL.Error(\"Error occured\", \"error\", err)\n\t\tcase \"development\":\n\t\t\tfallthrough\n\t\tdefault:\n\t\t\tdebug.PrintStack()\n\t\t\tlog.Root().SetHandler(LogStackHandler)\n\t\t\tL.Error(\"Error occured\", \"error\", err)\n\t\t}\n\t}\n}", "func Catch(err error) {\n\tif err == io.EOF {\n\t\treturn\n\t} else if err != nil {\n\t\tlogger.Error(err.Error())\n\t}\n}", "func (sc *SocketClient) HandleErrors() {\n\terr := recover()\n\tif err == nil {\n\t\treturn\n\t}\n\n\tswitch err := err.(type) {\n\tcase *RequestError:\n\t\tif err.code >= 500 {\n\t\t\tsc.log.Debugf(\"panic: %v\\n%s\", err, debug.Stack())\n\t\t}\n\t\tsc.log.Warning(err)\n\t\terr.Format(sc)\n\tdefault:\n\t\tsc.log.Debugf(\"panic: %v\\n%s\", err, debug.Stack())\n\t\tsc.log.Error(err)\n\t}\n}", "func (h *Handler) HandleLog(e *log.Entry) error {\n\treturn h.q.Push(func() {\n\t\tif e := h.send(e); e != nil {\n\t\t\tstdlog.Printf(\"log/firehose: %s\", e)\n\t\t}\n\t})\n}", "func (h *SimpleFileHandler) Handle(r *slog.Record) (err error) {\n\tvar bts []byte\n\tbts, err = h.Formatter().Format(r)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// if enable lock\n\th.Lock()\n\tdefer h.Unlock()\n\n\t// direct write logs\n\t_, err = h.file.Write(bts)\n\treturn\n}", "func (c *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\t// Forget about the #AddRateLimited history of the key on every successful synchronization.\n\t\t// This ensures that future processing of updates for this key is not delayed because of\n\t\t// an outdated error history.\n\t\tc.queue.Forget(key)\n\t\treturn\n\t}\n\n\tklog.Infof(\"Error syncing Flunder %v: %v\", key, err)\n\n\t// Re-enqueue the key rate limited. Based on the rate limiter on the\n\t// queue and the re-enqueue history, the key will be processed later again.\n\tc.queue.AddRateLimited(key)\n\treturn\n}", "func (fn GetFacilityUploadsErrorsHandlerFunc) Handle(params GetFacilityUploadsErrorsParams, principal *models.JWTClaimBody) middleware.Responder {\n\treturn fn(params, principal)\n}", "func (h HandlerFunc) Handle(e Event) { h(e) }", "func ErrHandling(err string) {\n\tAllOutput.Mutex.Lock()\n\tdefer AllOutput.Mutex.Unlock()\n\tJobCount++\n\tAllOutput.List[JobCount] = &agentscommon.JobOutput{\"error\", err}\n}", "func handleFailure(fhandler *flowHandler, context *faasflow.Context, err error) {\n\tvar data []byte\n\n\tcontext.State = faasflow.StateFailure\n\t// call failure handler if available\n\tif fhandler.getPipeline().FailureHandler != nil {\n\t\tfmt.Printf(\"[Request `%s`] Calling failure handler for error, %v\\n\",\n\t\t\tfhandler.id, err)\n\t\tdata, err = fhandler.getPipeline().FailureHandler(err)\n\t}\n\n\tfhandler.finished = true\n\n\t// call finally handler if available\n\tif fhandler.getPipeline().Finally != nil {\n\t\tfmt.Printf(\"[Request `%s`] Calling Finally handler with state: %s\\n\",\n\t\t\tfhandler.id, faasflow.StateFailure)\n\t\tfhandler.getPipeline().Finally(faasflow.StateFailure)\n\t}\n\tif data != nil {\n\t\tfmt.Printf(\"%s\", string(data))\n\t}\n\n\t// Cleanup data and state for failure\n\tif fhandler.stateStore != nil {\n\t\tfhandler.stateStore.Cleanup()\n\t}\n\tfhandler.dataStore.Cleanup()\n\n\t// stop req span if request has finished\n\tfhandler.tracer.stopReqSpan()\n\n\t// flash any pending trace item if tracing enabled\n\tfhandler.tracer.flushTracer()\n\n\tpanic(fmt.Sprintf(\"[Request `%s`] Failed, %v\\n\", fhandler.id, err))\n}", "func handle(handler func(evt interface{}, args ...interface{}), evt interface{}, args ...interface{}) {\n\tdefer util.HandlePanic()\n\thandler(evt, args...)\n}", "func (h *handler) HandleLog(e *log.Entry) error {\n\th.Lock()\n\tdefer h.Unlock()\n\n\t// if we have a blank line we don't want padding or prefixes\n\tif e.Message == \"\" {\n\t\t_, _ = fmt.Fprintln(h.writer)\n\t\treturn nil\n\t}\n\n\tif h.wantTime {\n\t\tts := h.timer().Format(timeFmt)\n\t\t_, _ = fmt.Fprint(h.writer, appendMissingLineFeed(fmt.Sprintf(\"%s %s%s\", ts, formatLevel(e.Level), e.Message)))\n\t\treturn nil\n\t}\n\n\t_, _ = fmt.Fprint(h.writer, appendMissingLineFeed(fmt.Sprintf(\"%s%s\", formatLevel(e.Level), e.Message)))\n\n\treturn nil\n}", "func (h *Handler) error(w http.ResponseWriter, error string, code int) {\n\t// TODO: Return error as JSON.\n\thttp.Error(w, error, code)\n}", "func ErrorHandler(w http.ResponseWriter, r *http.Request, errMsg string, status int) {\n\tvar buffer bytes.Buffer\n\n\t// Get current user information for signin links\n\tctx := appengine.NewContext(r)\n\tgoogleUser := appengineUser.Current(ctx)\n\tvar loginUrl string\n\tvar loginMessage string\n\tvar err error\n\n\t// Build correct login/logout links for Google but don't worry about\n\t// showing full user information, so don't get user object\n\tif googleUser == nil {\n\t\tloginUrl, err = appengineUser.LoginURL(ctx, html.EscapeString(r.URL.Path))\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tloginMessage = \"Sign In\"\n\t} else {\n\t\tloginUrl, err = appengineUser.LogoutURL(ctx, \"/\")\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tloginMessage = \"Sign Out\"\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"title\": status,\n\t\t\"errMsg\": errMsg,\n\t\t\"LoginUrl\": loginUrl,\n\t\t\"LoginMessage\": loginMessage,\n\t}\n\n\tw.WriteHeader(status)\n\terr = templates[\"dormant/error\"].ExecuteTemplate(&buffer, baseName, data)\n\tif err != nil {\n\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tio.Copy(w, &buffer)\n}", "func (c *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\t// Forget about the #AddRateLimited history of the key on every successful synchronization.\n\t\t// This ensures that future processing of updates for this key is not delayed because of\n\t\t// an outdated error history.\n\t\tc.queue.Forget(key)\n\t\treturn\n\t}\n\n\tklog.Infof(\"Error syncing ConfigMap %v: %v\", key, err)\n\n\t// Re-enqueue the key rate limited. Based on the rate limiter on the\n\t// queue and the re-enqueue history, the key will be processed later again.\n\tc.queue.AddRateLimited(key)\n\treturn\n}", "func (g *Handler) Handle(cnf *viper.Viper, opt ...Options) error {\n\tvar log logger.Logger = logger.New(&logger.Options{\n\t\tVerbose: cnf.GetBool(\"verbose\"),\n\t})\n\tvar rrp resultRenderProcessor = &processor{log}\n\tvar taskRunner taskRunner = engine.New(nil)\n\tif len(opt) == 1 {\n\t\tif opt[0].ResultRenderProcessor != nil {\n\t\t\trrp = opt[0].ResultRenderProcessor\n\t\t}\n\t\tif opt[0].Logger != nil {\n\t\t\tlog = opt[0].Logger\n\t\t}\n\t}\n\treturn handle(cnf, log, rrp, taskRunner)\n}", "func HandleErrMsg(pbsData sendmodel.SendPayload, op *kafka.KafkaOpreations) {\n\tresponseMsg := strings.Split(pbsData.MsgType, \":\")\n\txmlMsgType := responseMsg[1]\n\tstatusCode, _ := strconv.Atoi(responseMsg[2])\n\tinstrId := pbsData.InstructionId\n\n\toriginalGrpInf := &pacs002struct.OriginalGroupInformation29{\n\t\tOrgnlMsgId: getReportMax35Text(pbsData.MsgId),\n\t\tOrgnlMsgNmId: getReportMax35Text(xmlMsgType),\n\t}\n\n\tLOGGER.Warningf(\"Receiving error message %s on OFI or RFI side during request handling: %d\", pbsData.MsgType, statusCode)\n\tLOGGER.Infof(\"Incoming message type: %s\", xmlMsgType)\n\n\ttargetParticipant, report, err := parse.KafkaErrorRouter(xmlMsgType, instrId, pbsData.OfiId, pbsData.RfiId, statusCode, true, originalGrpInf)\n\tif err != nil {\n\t\treturn\n\t}\n\n\top.SendRequestToKafka(targetParticipant+\"_\"+kafka.TRANSACTION_TOPIC, report)\n\n\treturn\n}", "func (c *Controller) handleErr(err error, key interface{}) {\n\tif err == nil {\n\t\tc.queue.Forget(key)\n\t\treturn\n\t}\n\n\t// This controller retries 5 times if something goes wrong. After that, it stops trying.\n\tif c.queue.NumRequeues(key) < 5 {\n\t\tfmt.Printf(\"Error syncing onionservice %v: %v\\n\", key, err)\n\n\t\t// Re-enqueue the key rate limited. Based on the rate limiter on the\n\t\t// queue and the re-enqueue history, the key will be processed later again.\n\t\tc.queue.AddRateLimited(key)\n\t\treturn\n\t}\n\n\tc.queue.Forget(key)\n\t// Report to an external entity that, even after several retries, we could not successfully process this key\n\truntime.HandleError(err)\n\tfmt.Printf(\"Dropping onionservice %q out of the queue: %v\\n\", key, err)\n}", "func Handler(w http.ResponseWriter, err error) {\n\tvar res *errors.Error\n\tErr, ok := err.(*errors.Error)\n\tif ok {\n\t\tres = Err\n\t} else {\n\t\tres = errors.NewError(\"500\", \"Error server\", err)\n\t}\n\tsc, ok := statusMap()[res.Code]\n\tif !ok {\n\t\tsc = http.StatusInternalServerError\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tw.WriteHeader(sc)\n\tif err = render.Write(w, res); err != nil {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tfmt.Fprint(w, \"Error rendering response\")\n\t}\n}", "func Handle(c Checker, pattern string, h http.Handler) {\n\thttp.Handle(pattern, NewHandler(c, h))\n}", "func (h BaseHandler) Err(ctx *fasthttp.RequestCtx, err error) error {\n\treturn Err(ctx, err)\n}", "func handleErr(r interface{}) error {\n\tswitch v := r.(type) {\n\tcase map[string]interface{}:\n\t\tcode, ok := v[\"err_code\"]\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\n\t\terr, ok := v[\"err_msg\"]\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\n\t\treturn fmt.Errorf(\"error %g: %v\", code, err)\n\tdefault:\n\t\treturn fmt.Errorf(\"I don't know about type %T!\\n\", v)\n\t}\n}", "func (fh *FileHandle) Handle(w http.ResponseWriter, r *http.Request, ps Params) {\n\tr.URL.Path = ps.ByName(\"filepath\")\n\tr.RequestURI = r.URL.String()\n\n\tfh.handler.ServeHTTP(w, r)\n}", "func (recv *Receiver) handle(req Request, event cloudevents.Event) error {\n\n\terr := recv.s3ification(req.Description, event)\n\tif err != nil {\n\t\trecv.logger.Errorw(\"and error occured posting to s3 \", zap.Error(err))\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (h *JiraHandler) Handle(ctx context.Context, event sdk.Event) error {\n\tlog.Debug(\"handle event\")\n\tswitch o := event.Object.(type) {\n\tcase *v1alpha1.Jira:\n\t\terr := handleJira(o)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to handle jira: %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (h *PgoutputEventHandler) Handle(ctx context.Context, msg pgoutput.Message) error {\n\n\tswitch v := msg.(type) {\n\tcase pgoutput.Relation:\n\t\th.log.Debug(\"received RELATION message\")\n\t\th.relations.Add(v)\n\tcase pgoutput.Insert:\n\t\th.log.Debug(\"received INSERT message\")\n\t\treturn h.handleCreate(ctx, v.RelationID, v.Row)\n\tcase pgoutput.Update:\n\t\th.log.Debug(\"received UPDATE message\")\n\t\treturn h.handleUpdate(ctx, v.RelationID, v.Row)\n\tcase pgoutput.Delete:\n\t\th.log.Debug(\"received DELETE message\")\n\t\treturn h.handleDelete(ctx, v.RelationID, v.Row)\n\t}\n\treturn nil\n}", "func (c *Command) Handle() {\n\tfmt.Println(\"Handle Method Should Be Rewrite\")\n\tos.Exit(0)\n}" ]
[ "0.7045426", "0.7045426", "0.6901015", "0.68650657", "0.6856234", "0.6716931", "0.6665394", "0.66072434", "0.6598165", "0.65944666", "0.65339744", "0.65293866", "0.65293866", "0.65293866", "0.6510664", "0.6501705", "0.6500989", "0.6466162", "0.6414426", "0.63757294", "0.63680875", "0.632305", "0.6211358", "0.6113464", "0.60577744", "0.6018371", "0.600847", "0.5951617", "0.59504294", "0.59337103", "0.5928397", "0.59119487", "0.58997685", "0.5879248", "0.58055884", "0.5798739", "0.57918555", "0.5790511", "0.5766725", "0.57600725", "0.5757144", "0.574146", "0.57342446", "0.5727537", "0.57123154", "0.5701409", "0.56913155", "0.56903493", "0.5688263", "0.56860024", "0.5677838", "0.56677234", "0.5666331", "0.56596005", "0.56391305", "0.5634871", "0.5630162", "0.56122065", "0.5607732", "0.559569", "0.5590053", "0.5577128", "0.55737185", "0.5559612", "0.5550064", "0.55488753", "0.554512", "0.54987246", "0.5487153", "0.54863477", "0.5482196", "0.5481314", "0.5451228", "0.5427187", "0.54256284", "0.5419031", "0.5398937", "0.53874314", "0.5386523", "0.53691727", "0.53547", "0.531854", "0.53127897", "0.5285478", "0.52810633", "0.5253333", "0.52392507", "0.5233438", "0.52329874", "0.52202344", "0.5218303", "0.52148306", "0.52128124", "0.5205411", "0.5195942", "0.5164923", "0.51642114", "0.5155246", "0.51535076", "0.5149976" ]
0.7338173
0
NewMigrator creates a migrator instance
func NewMigrator(s []string, d string, k io.Reader) *Migrator { return &Migrator{ src: s, dst: d, keys: readKeys(k), result: make(chan *I18nItem), wg: new(sync.WaitGroup), } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func NewMigrator(db *sql.DB, c *Config) Migrator {\n\treturn &migrator{\n\t\tdb,\n\t\tc,\n\t}\n}", "func NewMigrator(c *pop.Connection, l *logrusx.Logger, tracer *otelx.Tracer, perMigrationTimeout time.Duration) *Migrator {\n\treturn &Migrator{\n\t\tConnection: c,\n\t\tl: l,\n\t\tMigrations: map[string]Migrations{\n\t\t\t\"up\": {},\n\t\t\t\"down\": {},\n\t\t},\n\t\ttracer: tracer,\n\t\tPerMigrationTimeout: perMigrationTimeout,\n\t}\n}", "func New(client client.Client) Migrator {\n\treturn &migrator{\n\t\tclient: client,\n\t}\n}", "func New(client client.Client) Migrator {\n\treturn &migrator{\n\t\tclient: client,\n\t}\n}", "func NewMigratorTask(id string) *asynq.Task {\n\tfmt.Println(\"NewMigratorTask\")\n\t// Specify task payload.\n\tpayload := map[string]interface{}{\n\t\t\"tenant_id\": id, // set tenant ID\n\t}\n\n\t// Return a new task with given type and payload.\n\tfmt.Println(payload)\n\treturn asynq.NewTask(TypeMigratorPayload, payload)\n}", "func NewMigrator(hosts *HostSet) *Migrator {\n\tshards := make(map[hostdb.HostPublicKey]*renter.SectorBuilder)\n\tfor hostKey := range hosts.sessions {\n\t\tshards[hostKey] = new(renter.SectorBuilder)\n\t}\n\treturn &Migrator{\n\t\thosts: hosts,\n\t\tshards: shards,\n\t}\n}", "func ProvideMigrator(logger *Logger, conn *Connection) (*Migrator, error) {\n\treturn &Migrator{Logger: logger, Connection: conn}, nil\n}", "func NewMigration(version int, commands ...string) Migration {\n\treturn Migration{\n\t\tVersion: version,\n\t\tCommands: commands,\n\t}\n}", "func NewDBMigratorTool(m *DBMigrator) (*DBMigratorTool, error) {\n\tservice, err := migration.NewServiceTool(m.domain.Migration.Service)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tm.domain.Migration.Service = service\n\tmt := &DBMigratorTool{m}\n\treturn mt, nil\n}", "func New(path string, dbURI string, database string) (*MyMigrate, error) {\n\tnoDbPostgres := strings.Replace(dbURI, fmt.Sprintf(\"/%s\", database), \"\", 1)\n\terr := createDatabaseIfNotExists(noDbPostgres, database)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tpath = fmt.Sprintf(\"file://%v\", path)\n\tcrdbURI := strings.Replace(dbURI, \"postgresql\", \"cockroachdb\", 1)\n\tmigrater, err := migrate.New(path, crdbURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmyMigrater := &MyMigrate{migrater, dbURI, database}\n\t// handle Ctrl+c\n\tsignals := make(chan os.Signal, 1)\n\tsignal.Notify(signals, syscall.SIGINT)\n\tgo func() {\n\t\tfor range signals {\n\t\t\tlog.Println(\"Stopping after this running migration ...\")\n\t\t\tmyMigrater.GracefulStop <- true\n\t\t\treturn\n\t\t}\n\t}()\n\treturn myMigrater, err\n}", "func (_SushiV2Factory *SushiV2FactoryCallerSession) Migrator() (common.Address, error) {\n\treturn _SushiV2Factory.Contract.Migrator(&_SushiV2Factory.CallOpts)\n}", "func NewMigration(id string, queries, dependencies []string, postmigrations ...func(context *context.Context) error) Migrationer {\n\treturn &simpleMigration{id: id, queries: queries,\n\t\tdependencies: dependencies, postmigrations: postmigrations}\n}", "func makeTestMigrator(options ...Option) *Migrator {\n\ttableName := time.Now().Format(time.RFC3339Nano)\n\toptions = append(options, WithTableName(tableName))\n\treturn NewMigrator(options...)\n}", "func (_SushiV2Factory *SushiV2FactorySession) Migrator() (common.Address, error) {\n\treturn _SushiV2Factory.Contract.Migrator(&_SushiV2Factory.CallOpts)\n}", "func migrateNew() {\n\tif len(flag.Args()) == 0 {\n\t\tlog.Fatalf(\"ERROR: Migration's name not specified\\n\")\n\t\treturn\n\t}\n\twd, _ := os.Getwd()\n\tname := path.Join(wd, \"migrations\", fmt.Sprintf(\"%d_%s.sql\", time.Now().Unix(), flag.Arg(0)))\n\tfile, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t\treturn\n\t}\n\tfmt.Fprintf(file, \"-- +migrate Up\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Up' is executed when this migration is applied\\n\\n\\n\")\n\tfmt.Fprintf(file, \"-- +migrate Down\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Down' is executed when this migration is rolled back\\n\\n\\n\")\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t} else {\n\t\tlog.Printf(\"INFO: File %s has been successfully created\\n\", name)\n\t}\n}", "func (_SushiV2Factory *SushiV2FactoryTransactor) SetMigrator(opts *bind.TransactOpts, _migrator common.Address) (*types.Transaction, error) {\n\treturn _SushiV2Factory.contract.Transact(opts, \"setMigrator\", _migrator)\n}", "func NewMigration(migrationLocation string) *Migration {\n\treturn &Migration{\n\t\tmigrationFileLocation: migrationLocation,\n\t\tname: migrationName(migrationLocation),\n\t}\n}", "func New(name string) error {\n\treturn createMigration(name, \"/* Your up migration code here */\", \"/* Your down migration code here */\")\n}", "func (_SushiV2Factory *SushiV2FactoryCaller) Migrator(opts *bind.CallOpts) (common.Address, error) {\n\tvar out []interface{}\n\terr := _SushiV2Factory.contract.Call(opts, &out, \"migrator\")\n\n\tif err != nil {\n\t\treturn *new(common.Address), err\n\t}\n\n\tout0 := *abi.ConvertType(out[0], new(common.Address)).(*common.Address)\n\n\treturn out0, err\n\n}", "func (_SushiV2Factory *SushiV2FactoryTransactorSession) SetMigrator(_migrator common.Address) (*types.Transaction, error) {\n\treturn _SushiV2Factory.Contract.SetMigrator(&_SushiV2Factory.TransactOpts, _migrator)\n}", "func (_SushiV2Factory *SushiV2FactorySession) SetMigrator(_migrator common.Address) (*types.Transaction, error) {\n\treturn _SushiV2Factory.Contract.SetMigrator(&_SushiV2Factory.TransactOpts, _migrator)\n}", "func New(db *sqlx.DB, migrations []Migration) (*SqlxMigrate, error) {\n\tif _, ok := supportedDrivers[db.DriverName()]; !ok {\n\t\treturn nil, fmt.Errorf(\"Unsupported driver name: %s\", db.DriverName())\n\t}\n\n\treturn &SqlxMigrate{\n\t\tdb: db,\n\t\tmigrations: migrations,\n\t}, nil\n}", "func NewMigrationRunner(db *Database, migrations ...Migration) (*MigrationRunner, error) {\n\tconn, closeConn, err := db.Conn(context.Background())\n\tif err != nil {\n\t\tlog.\n\t\t\tError().\n\t\t\tErr(err).\n\t\t\tMsg(\"failed to get conn for creating migrations table\")\n\t\treturn nil, err\n\t}\n\tdefer closeConn()\n\n\terr = sqlitex.ExecScript(conn, strings.TrimSpace(`\n\t\tCREATE TABLE IF NOT EXISTS migrations(\n\t\t\tname TEXT NOT NULL,\n\t\t\tPRIMARY KEY (name)\n\t\t);\n\t`))\n\tif err != nil {\n\t\tlog.\n\t\t\tError().\n\t\t\tErr(err).\n\t\t\tMsg(\"failed to create migrations table\")\n\t\treturn nil, err\n\t}\n\n\treturn &MigrationRunner{\n\t\tdb: db,\n\t\tmigrations: migrations,\n\t}, nil\n}", "func newStorageMigrateCmd() (cmd *cobra.Command) {\n\tcmd = &cobra.Command{\n\t\tUse: \"migrate\",\n\t\tShort: cmdAutheliaStorageMigrateShort,\n\t\tLong: cmdAutheliaStorageMigrateLong,\n\t\tExample: cmdAutheliaStorageMigrateExample,\n\t\tArgs: cobra.NoArgs,\n\n\t\tDisableAutoGenTag: true,\n\t}\n\n\tcmd.AddCommand(\n\t\tnewStorageMigrateUpCmd(), newStorageMigrateDownCmd(),\n\t\tnewStorageMigrateListUpCmd(), newStorageMigrateListDownCmd(),\n\t\tnewStorageMigrateHistoryCmd(),\n\t)\n\n\treturn cmd\n}", "func MigrateCreate(defaultPath string) cli.Command {\n\tif len(defaultPath) == 0 {\n\t\tdefaultPath = defaultMigratePath()\n\t}\n\n\taction := func(ctx *cli.Context) error {\n\t\tmpath := ctx.String(\"path\")\n\t\tif len(mpath) == 0 {\n\t\t\tmpath = defaultPath\n\t\t}\n\n\t\tif _, err := os.Stat(mpath); err != nil {\n\t\t\tlog.Fatalf(\"migration path not found: %v\", err)\n\t\t}\n\n\t\tname := strings.Join(ctx.Args(), \"_\")\n\t\tname = strings.ToLower(name)\n\n\t\tif len(name) == 0 {\n\t\t\tlog.Fatal(\"migration name not set\")\n\t\t}\n\n\t\tif err := migrate.CreateMigration(mpath, name); err != nil {\n\t\t\tlog.Fatalf(\"migration not created: %v\", err)\n\t\t}\n\n\t\tlog.Infof(\"migration created: %s\", name)\n\n\t\treturn nil\n\t}\n\n\treturn cli.Command{\n\t\tName: \"migrate:create\",\n\t\tShortName: \"m:c\",\n\t\tUsage: \"new <migration-name> --path=<to-migrations>\",\n\t\tDescription: \"Create new migration\",\n\t\tCategory: \"Migrate commands\",\n\t\tFlags: []cli.Flag{mpathFlag},\n\t\tAction: action,\n\t}\n}", "func newSubscriptionMigrator(kymaClient kymaeventingclientset.Interface,\n\tknativeClient kneventingclientset.Interface, namespaces []string) (*subscriptionMigrator, error) {\n\n\tm := &subscriptionMigrator{\n\t\tkymaClient: kymaClient,\n\t\tknativeClient: knativeClient,\n\t}\n\n\tif err := m.populateSubscriptions(namespaces); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := m.populateTriggers(namespaces); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn m, nil\n}", "func Migrate(migrationPolicy MigrationPolicy) {\n\tcontainer.Make(\n\t\tfunc(gormDB *gorm.DB) {\n\n\t\t\tif migrationPolicy == OrmMigration {\n\t\t\t\terr := gormDB.AutoMigrate(\n\t\t\t\t\t&dbmodel.User{},\n\t\t\t\t\t&dbmodel.Department{},\n\t\t\t\t\t&dbmodel.Province{},\n\t\t\t\t\t&dbmodel.District{},\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t\t}\n\t\t\t} else if migrationPolicy == SQLScriptsMigration {\n\t\t\t\tsqlDB, err := gormDB.DB()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t\t}\n\n\t\t\t\terr = sqlDB.Ping()\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t\t}\n\n\t\t\t\tdriver, _ := mysql.WithInstance(\n\t\t\t\t\tsqlDB, &mysql.Config{},\n\t\t\t\t)\n\n\t\t\t\tm, err := migrate.NewWithDatabaseInstance(\n\t\t\t\t\t\"file://internal/database/migrations/mysql\",\n\t\t\t\t\tmySQLDriver,\n\t\t\t\t\tdriver,\n\t\t\t\t)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t\t}\n\n\t\t\t\terr = m.Up()\n\t\t\t\tif err != nil && err != migrate.ErrNoChange {\n\t\t\t\t\tlog.Fatalln(err.Error())\n\t\t\t\t}\n\t\t\t}\n\t\t},\n\t)\n}", "func New(ctx context.Context, l logger.Logger, migConf migration.Config) (storage.Storage, error) {\n\tl.Infof(\"applying database migrations from %s\", migConf.Path)\n\n\tdb, err := postgres.New(ctx, migConf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &pg{db: db, logger: l}, nil\n}", "func NewSQLLiteMigrator(db *sql.DB) (Migrator, error) {\n\treturn &SQLLiteMigrator{\n\t\tdb: db,\n\t\tmigrationsTable: DefaultMigrationsTable,\n\t\tmigrations: migrations.All(),\n\t}, nil\n}", "func ExecuteMigrator(config *config.Config, action *string, createConnector func(*config.Config) db.Connector, createLoader func(*config.Config) loader.Loader) int {\n\n\tswitch *action {\n\tcase PrintConfigAction:\n\t\tlog.Printf(\"Configuration file ==>\\n%v\\n\", config)\n\t\treturn 0\n\tcase ListDiskMigrationsAction:\n\t\tdiskMigrations := LoadDiskMigrations(config, createLoader)\n\t\tlog.Printf(\"List of disk migrations ==>\\n%v\", types.MigrationArrayString(diskMigrations))\n\t\treturn 0\n\tcase ListDBMigrationsAction:\n\t\tdbMigrations := LoadDBMigrations(config, createConnector)\n\t\tlog.Printf(\"List of db migrations ==> \\n%v\", types.MigrationDBArrayString(dbMigrations))\n\t\treturn 0\n\tcase ListDBTenantsAction:\n\t\tdbTenants := LoadDBTenants(config, createConnector)\n\t\tlog.Printf(\"List of db tenants ==> \\n%v\", types.TenantArrayString(dbTenants))\n\t\treturn 0\n\tcase ApplyAction:\n\t\tmigrationsApplied := ApplyMigrations(config, createConnector, createLoader)\n\t\tlog.Printf(\"List of migrations applied ==>\\n%v\", types.MigrationArrayString(migrationsApplied))\n\t\treturn 0\n\tdefault:\n\t\tlog.Printf(\"Unknown action to run %q. For usage please run migrator with -h flag.\", *action)\n\t\treturn 1\n\t}\n}", "func CreateNewMigration(migrationFolder string, name string) {\n\tfolder := strings.ReplaceAll(migrationFolder, \"file://\", \"\")\n\tnow := time.Now()\n\tver := now.Format(versionTimeFormat)\n\n\tup := fmt.Sprintf(\"%s/%s_%s.up.sql\", folder, ver, name)\n\tdown := fmt.Sprintf(\"%s/%s_%s.down.sql\", folder, ver, name)\n\n\tlogger.Infof(\"create migration: %s\", name)\n\n\tif err := ioutil.WriteFile(up, []byte{}, 0644); err != nil {\n\t\tlogger.Fatalf(\"create migration up error: %v\", err)\n\t}\n\tif err := ioutil.WriteFile(down, []byte{}, 0644); err != nil {\n\t\tlogger.Fatalf(\"create migration down error: %v\", err)\n\t}\n}", "func Migration(connStr string) (m *migrate.Migrate, err error) {\n\tconst tenantId = \"\" // tenantId is empty because we will not separate data for \"apps\" in the db\n\tsrc, err := migration.Immigration(context.Background(), tenantId, migrations)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsource.Register(driverSourceName, src)\n\tm, err = migrate.NewWithSourceInstance(driverSourceName, src, connStr)\n\treturn\n}", "func NewServiceMigration() *serviceMigration {\n\tServiceMigration := &serviceMigration{\n\t\tcommon.Service{\n\t\t\tName: \"service-migration\",\n\t\t\tURL: \"/migration\",\n\t\t},\n\t\tnil,\n\t}\n\tServiceMigration.Router = common.NewSubRouter(nil)\n\treturn ServiceMigration\n}", "func New(migrationAddresses []string) (*MigrationShard, error) {\n\treturn &MigrationShard{\n\t\tMap: make(foundation.StableMap),\n\t\tFreeMigrationAddresses: migrationAddresses,\n\t}, nil\n}", "func New(uri, migrationsDir string) (DB, error) {\n\tdb, err := sql.Open(\"postgres\", uri)\n\tif err != nil {\n\t\treturn DB{}, errors.Wrap(err, \"cannot open postgres db\")\n\t}\n\n\tif err := dbWait(db); err != nil {\n\t\treturn DB{}, errors.Wrap(err, \"cannot establish db connection\")\n\t}\n\n\tif migrationsDir != \"\" {\n\t\t// Add file scheme if no scheme is present\n\t\tif !strings.HasPrefix(migrationsDir, \"file:\") {\n\t\t\tmigrationsDir = \"file:\" + migrationsDir\n\t\t}\n\n\t\tm, err := migrate.New(migrationsDir, uri)\n\t\tif err != nil {\n\t\t\treturn DB{}, errors.Wrap(err, \"database migrations initialization failed\")\n\t\t}\n\n\t\tlevel.Info(util_log.Logger).Log(\"msg\", \"running database migrations...\")\n\n\t\tif err := m.Up(); err != nil {\n\t\t\tif err != migrate.ErrNoChange {\n\t\t\t\treturn DB{}, errors.Wrap(err, \"database migrations failed\")\n\t\t\t}\n\t\t\tlevel.Debug(util_log.Logger).Log(\"msg\", \"no change in schema, error (ignored)\", \"err\", err)\n\t\t}\n\t}\n\n\treturn DB{\n\t\tdbProxy: db,\n\t\tStatementBuilderType: statementBuilder(db),\n\t}, err\n}", "func generateMigration(migrator *dbmigrate.Migrator, engines []string, args ...string) error {\n\tif len(engines) == 1 && engines[0] == enginesNoOptDefVal {\n\t\tengines[0] = migrator.Engine\n\t}\n\n\tif len(engines) == 1 && engines[0] == \"all\" {\n\t\tengines = dbmigrate.Engines()\n\t}\n\n\tfpaths, err := migrator.GenerateMigration(strings.Join(args, \" \"), engines...)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"can't generate migration\")\n\t}\n\n\tfor _, fpath := range fpaths {\n\t\tfmt.Printf(\"created %s\\n\", fpath)\n\t}\n\n\treturn nil\n}", "func (m *Migrator) CreateSchemaMigrations(ctx context.Context) error {\n\tspan, ctx := m.startSpan(ctx, MigrationInitOpName)\n\tdefer span.End()\n\n\tc := m.Connection.WithContext(ctx)\n\n\tmtn := m.sanitizedMigrationTableName(c)\n\tm.l.WithField(\"migration_table\", mtn).Debug(\"Checking if legacy migration table exists.\")\n\t_, err := c.Store.Exec(fmt.Sprintf(\"select version from %s\", mtn))\n\tif err != nil {\n\t\tm.l.WithError(err).WithField(\"migration_table\", mtn).Debug(\"An error occurred while checking for the legacy migration table, maybe it does not exist yet? Trying to create.\")\n\t\t// This means that the legacy pop migrator has not yet been applied\n\t\treturn m.createTransactionalMigrationTable(ctx, c, m.l)\n\t}\n\n\tm.l.WithField(\"migration_table\", mtn).Debug(\"A migration table exists, checking if it is a transactional migration table.\")\n\t_, err = c.Store.Exec(fmt.Sprintf(\"select version, version_self from %s\", mtn))\n\tif err != nil {\n\t\tm.l.WithError(err).WithField(\"migration_table\", mtn).Debug(\"An error occurred while checking for the transactional migration table, maybe it does not exist yet? Trying to create.\")\n\t\treturn m.migrateToTransactionalMigrationTable(ctx, c, m.l)\n\t}\n\n\tm.l.WithField(\"migration_table\", mtn).Debug(\"Migration tables exist and are up to date.\")\n\treturn nil\n}", "func New(store stores.Store, writer stores.Writer) Transactor {\n\treturn &transactor{\n\t\tstore: store,\n\t\ttransactionCommands: make(map[int64][]kvdb.Command),\n\t\twriter: writer,\n\t}\n}", "func DefaultMigration(table string) Initializer {\n\treturn Migration(table, guessMigrationDirectory())\n}", "func Migration(table, directory string) Initializer {\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\tstartup_base.PanicOnError(err, \"No database migration files found\")\n\t}\n\n\treturn func(db *sqlx.DB) error {\n\t\tmigrate.SetTable(table)\n\n\t\tmigrations := &migrate.FileMigrationSource{Dir: directory}\n\t\tn, err := migrate.Exec(db.DB, \"postgres\", migrations, migrate.Up)\n\t\tif err != nil {\n\t\t\treturn errors.WithMessage(err, \"applying database migration\")\n\t\t}\n\n\t\tlogrus.WithField(\"prefix\", \"database\").\n\t\t\tInfof(\"%d migrations executed\", n)\n\n\t\treturn nil\n\t}\n}", "func Migrate() {\n\tlog.Info(\"Executing migrations...\")\n\tDb.AutoMigrate(&models.Repository{}, &models.Week{}, &models.Contributor{})\n}", "func (m *SQLLiteMigrator) Migrate(ctx context.Context) error {\n\ttx, err := m.db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer func() {\n\t\tif err := tx.Rollback(); err != nil && !strings.Contains(err.Error(), \"transaction has already been committed\") {\n\t\t\tlogrus.WithError(err).Warnf(\"couldn't rollback\")\n\t\t}\n\t}()\n\n\tversion, err := m.version(ctx, tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif err := tx.Commit(); err != nil {\n\t\treturn tx.Rollback()\n\t}\n\treturn m.Up(ctx, m.migrations.From(version+1))\n}", "func (w *Wrapper) Migration() *Migration {\n\treturn newMigration(w.db)\n}", "func NewPersister(c *pop.Connection) (*Persister, error) {\n\tvar mb, err = pop.NewMigrationBox(migrations, c)\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\n\treturn &Persister{c: c, mb: mb}, nil\n}", "func (t *TypesMigrator) Migrate() {\n\tif t.ActivityTypeMigrator == nil {\n\t\tt.ActivityTypeMigrator = new(ActivityTypeMigrator)\n\t}\n\tif t.DomainMigrator == nil {\n\t\tt.DomainMigrator = new(DomainMigrator)\n\t}\n\tif t.WorkflowTypeMigrator == nil {\n\t\tt.WorkflowTypeMigrator = new(WorkflowTypeMigrator)\n\t}\n\tif t.StreamMigrator == nil {\n\t\tt.StreamMigrator = new(StreamMigrator)\n\t}\n\n\tt.DomainMigrator.Migrate()\n\tParallelMigrate(\n\t\tt.WorkflowTypeMigrator.Migrate,\n\t\tt.ActivityTypeMigrator.Migrate,\n\t\tt.StreamMigrator.Migrate,\n\t)\n}", "func TestCreateMigrationsTable(t *testing.T) {\n\twithEachTestDB(t, func(t *testing.T, tdb *TestDB) {\n\n\t\tdb := tdb.Connect(t)\n\t\tdefer func() { _ = db.Close() }()\n\n\t\tmigrator := makeTestMigrator(WithDialect(tdb.Dialect))\n\t\terr := tdb.Dialect.CreateMigrationsTable(migrator.ctx, db, migrator.QuotedTableName())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Error occurred when creating migrations table: %s\", err)\n\t\t}\n\n\t\t// Test that we can re-run it again with no error\n\t\terr = tdb.Dialect.CreateMigrationsTable(migrator.ctx, db, migrator.QuotedTableName())\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Calling createMigrationsTable a second time failed: %s\", err)\n\t\t}\n\t})\n}", "func Migrate(cfg *config.Config, logger log.Logger, command string) error {\n\tdb, err := sql.Open(\"mysql\", cfg.DB.Dsn)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tpath, err := os.Getwd()\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tmigrationPath := fmt.Sprintf(\"file://%s/migration\", path)\n\tlogger.Infof(\"migrationPath : %s\", migrationPath)\n\n\tdriver, err := mysql.WithInstance(db, &mysql.Config{})\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tm, err := migrater.NewWithDatabaseInstance(\n\t\tmigrationPath,\n\t\t\"mysql\",\n\t\tdriver,\n\t)\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\tif command == \"up\" {\n\t\tlogger.Info(\"Migrate up\")\n\t\tif err := m.Up(); err != nil && err != migrater.ErrNoChange {\n\t\t\tlogger.Errorf(\"An error occurred while syncing the database.. %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif command == \"down\" {\n\t\tlogger.Info(\"Migrate down\")\n\t\tif err := m.Down(); err != nil && err != migrater.ErrNoChange {\n\t\t\tlogger.Errorf(\"An error occurred while syncing the database.. %v\", err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err != nil {\n\t\tlogger.Error(err)\n\t\treturn err\n\t}\n\n\tlogger.Info(\"Migrate complete\")\n\treturn nil\n}", "func createMigrationsTable(db *sql.DB) {\n\tquery := `\n\t\tCREATE TABLE IF NOT EXISTS _migrations(\n\t\t id serial PRIMARY KEY,\n\t\t migration VARCHAR (255) UNIQUE NOT NULL,\n\t\t migrated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP\n\t\t);\n\t`\n\n\t_, err := db.Exec(query)\n\tif err != nil {\n\t\tLogErr(\"%s\\n\", err)\n\t}\n}", "func Migrate(logger logger.Logger, db *sqlx.DB) {\n\tlogger.Info().Msg(\"Starting database migration\")\n\n\tdbInstance, err := postgres.WithInstance(db.DB, &postgres.Config{})\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate database instance\")\n\t}\n\n\tsrcInstance, err := httpfs.New(pkger.Dir(\"/migrate/migrations\"), \"\")\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migrate source instance\")\n\t}\n\n\tms, err := migrate.NewWithInstance(\"httpfs\", srcInstance, \"postgres\", dbInstance)\n\tif err != nil {\n\t\tlogger.Fatal().Err(err).Msg(\"Failed to create migration service\")\n\t}\n\n\tversion, _, err := ms.Version()\n\tif err != nil {\n\t\tif err == migrate.ErrNilVersion {\n\t\t\tlogger.Info().Msg(\"No migrations have been applied yet\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to get migration version\")\n\t\t}\n\t} else {\n\t\tlogger.Info().Uint(\"migrationVersion\", version).Send()\n\t}\n\n\tif err := ms.Up(); err != nil {\n\t\tif err == migrate.ErrNoChange {\n\t\t\tlogger.Info().Msg(\"No new migrations to apply\")\n\t\t} else {\n\t\t\tlogger.Fatal().Err(err).Msg(\"Failed to apply migrations\")\n\t\t}\n\t}\n\n\tlogger.Info().Msg(\"Database migration complete\")\n}", "func Migrate(tx *gorm.DB) error {\n\treturn tx.Exec(`\n\tCREATE OR REPLACE FUNCTION notifyPipelineRunStarted() RETURNS TRIGGER AS $_$\n\tBEGIN\n\t\tIF NEW.finished_at IS NULL THEN\n\t\t\tPERFORM pg_notify('pipeline_run_started', NEW.id::text);\n\t\tEND IF;\n\t\tRETURN NEW;\n\tEND\n\t$_$ LANGUAGE 'plpgsql';\n\t`).Error\n}", "func initNew(sess *xorm.Session) error {\n\tif err := syncAll(sess); err != nil {\n\t\treturn err\n\t}\n\n\t// dummy run migrations\n\tfor _, task := range migrationTasks {\n\t\tif _, err := sess.Insert(&migrations{task.name}); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func migrate() *gorm.DB {\n\tdb.AutoMigrate(&models.Book{})\n\treturn db\n}", "func (m *migrater) getNewMigrations() []migrationModel {\n\n\tvar names []string\n\tfor k, _ := range pool.migrations {\n\t\tnames = append(names, k)\n\t}\n\n\tsort.Strings(names)\n\n\tstep := 20 // limit\n\tresult := make([]migrationModel, 0)\n\texistMigrations := make(map[string]bool)\n\tfor i := 0; i < len(names); {\n\n\t\ti += step\n\t\tvar chunkNames []string\n\t\tif i <= len(names) {\n\t\t\tchunkNames = names[i-step : i]\n\t\t} else {\n\t\t\tchunkNames = names[i-step:]\n\t\t}\n\n\t\trows := make([]struct{ Name string }, 0)\n\t\tif err := m.db.Model(m.newMigrationModel()).\n\t\t\tWhere(\"name IN (?)\", chunkNames).\n\t\t\tScan(&rows).Error; err != nil {\n\n\t\t\tpanic(err)\n\t\t}\n\t\t\n\t\tfor _, row := range rows {\n\t\t\texistMigrations[row.Name] = true\n\t\t}\n\t}\n\n\tfor _, name := range names {\n\t\tif _, ok := existMigrations[name]; !ok {\n\t\t\tmodel := m.newMigrationModel()\n\t\t\tmodel.Name = name\n\t\t\tresult = append(result, model)\n\t\t}\n\t}\n\n\treturn result\n}", "func migrate0001(db *gorm.DB) error {\n\tmigrationName := \"oauth_initial\"\n\n\tmigration := new(migrations.Migration)\n\tfound := !db.Where(\"name = ?\", migrationName).First(migration).RecordNotFound()\n\n\tif found {\n\t\tlogger.INFO.Printf(\"Skipping %s migration\", migrationName)\n\t\treturn nil\n\t}\n\n\tlogger.INFO.Printf(\"Running %s migration\", migrationName)\n\n\tvar err error\n\n\t// Create oauth_clients table\n\tif err := db.CreateTable(new(Client)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_clients table: %s\", err)\n\t}\n\n\t// Create oauth_scopes table\n\tif err := db.CreateTable(new(Scope)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_scopes table: %s\", err)\n\t}\n\n\t// Create oauth_users table\n\tif err := db.CreateTable(new(User)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_users table: %s\", err)\n\t}\n\n\t// Create oauth_refresh_tokens table\n\tif err := db.CreateTable(new(RefreshToken)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_refresh_tokens table: %s\", err)\n\t}\n\n\t// Create oauth_access_tokens table\n\tif err := db.CreateTable(new(AccessToken)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_access_tokens table: %s\", err)\n\t}\n\n\t// Create oauth_authorization_codes table\n\tif err := db.CreateTable(new(AuthorizationCode)).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error creating oauth_authorization_codes table: %s\", err)\n\t}\n\n\t// Add foreign key on oauth_refresh_tokens.client_id\n\terr = db.Model(new(RefreshToken)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_refresh_tokens.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_refresh_tokens.user_id\n\terr = db.Model(new(RefreshToken)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_refresh_tokens.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_access_tokens.client_id\n\terr = db.Model(new(AccessToken)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_access_tokens.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_access_tokens.user_id\n\terr = db.Model(new(AccessToken)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_access_tokens.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_authorization_codes.client_id\n\terr = db.Model(new(AuthorizationCode)).AddForeignKey(\n\t\t\"client_id\",\n\t\t\"oauth_clients(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_authorization_codes.client_id for oauth_clients(id): %s\", err)\n\t}\n\n\t// Add foreign key on oauth_authorization_codes.user_id\n\terr = db.Model(new(AuthorizationCode)).AddForeignKey(\n\t\t\"user_id\",\n\t\t\"oauth_users(id)\",\n\t\t\"RESTRICT\",\n\t\t\"RESTRICT\",\n\t).Error\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating foreign key on \"+\n\t\t\t\"oauth_authorization_codes.user_id for oauth_users(id): %s\", err)\n\t}\n\n\t// Save a record to migrations table,\n\t// so we don't rerun this migration again\n\tmigration.Name = migrationName\n\tif err := db.Create(migration).Error; err != nil {\n\t\treturn fmt.Errorf(\"Error saving record to migrations table: %s\", err)\n\t}\n\n\treturn nil\n}", "func New(logger lager.Logger) *gorm.DB {\n\tonce.Do(func() {\n\t\tDbConnection = SetupDb(logger)\n\t\tif err := RunMigrations(DbConnection); err != nil {\n\t\t\tpanic(fmt.Sprintf(\"Error migrating database: %s\", err.Error()))\n\t\t}\n\t})\n\treturn DbConnection\n}", "func Migrate(tx *gorm.DB) error {\n\treturn tx.Exec(`\n\t ALTER TABLE initiators ADD COLUMN \"polling_interval\" BigInt;\n\t`).Error\n}", "func migrate(name string, port uint64, peerListenUrls string, peerAdvertiseUrls string, clientListenUrls string,\n\tbinPath string, dataDirPath string, etcdDataPrefix string, ttlKeysDirectory string,\n\tinitialCluster string, target *EtcdVersionPair, bundledVersions SupportedVersions, etcdServerArgs string) {\n\n\tdataDir, err := OpenOrCreateDataDirectory(dataDirPath)\n\tif err != nil {\n\t\tklog.Fatalf(\"Error opening or creating data directory %s: %v\", dataDirPath, err)\n\t}\n\n\tcfg := &EtcdMigrateCfg{\n\t\tbinPath: binPath,\n\t\tname: name,\n\t\tport: port,\n\t\tpeerListenUrls: peerListenUrls,\n\t\tpeerAdvertiseUrls: peerAdvertiseUrls,\n\t\tclientListenUrls: clientListenUrls,\n\t\tetcdDataPrefix: etcdDataPrefix,\n\t\tttlKeysDirectory: ttlKeysDirectory,\n\t\tinitialCluster: initialCluster,\n\t\tsupportedVersions: bundledVersions,\n\t\tdataDirectory: dataDirPath,\n\t\tetcdServerArgs: etcdServerArgs,\n\t}\n\tclient, err := NewEtcdMigrateClient(cfg)\n\tif err != nil {\n\t\tklog.Fatalf(\"Migration failed: %v\", err)\n\t}\n\tdefer client.Close()\n\n\tmigrator := &Migrator{cfg, dataDir, client}\n\n\terr = migrator.MigrateIfNeeded(target)\n\tif err != nil {\n\t\tklog.Fatalf(\"Migration failed: %v\", err)\n\t}\n}", "func (s Sequence) Migrate() error {\n\tif s.cfg.Active && s.db != nil {\n\t\tif err := goose.Up(s.db, s.cfg.Dir); err != nil {\n\t\t\treturn fmt.Errorf(errApplyMigration, err)\n\t\t}\n\t}\n\n\treturn nil\n}", "func New(tb testing.TB, dir string, ver string, logger func(string)) (*DB, error) {\n\tdb, err := doNew(tb, dir, ver, logger)\n\tif err != nil && tb != nil {\n\t\ttb.Fatal(\"failed initializing database: \", err)\n\t}\n\treturn db, err\n}", "func (i *Index) Migration(opts ...PopulateOption) *IndexMigration {\n\treturn &IndexMigration{\n\t\tIndex: i,\n\t\topts: opts,\n\t}\n}", "func TestInitSchemaWithMigrations(t *testing.T) {\n\tforEachDatabase(t, func(db *sqlx.DB) {\n\t\tm := New(db, DefaultOptions, migrations)\n\t\tm.InitSchema(func(tx *sqlx.DB) error {\n\t\t\tq := `CREATE TABLE \"people\" (\"id\" serial,\"created_at\" timestamp with time zone,\"updated_at\" timestamp with time zone,\"deleted_at\" timestamp with time zone,\"name\" text , PRIMARY KEY (\"id\"))`\n\t\t\t_, err := tx.Exec(q)\n\t\t\treturn err\n\t\t})\n\n\t\tassert.NoError(t, m.Migrate())\n\t\tassert.True(t, m.hasTable(\"people\"))\n\t\tassert.False(t, m.hasTable(\"pets\"))\n\t\tassert.Equal(t, 3, tableCount(t, db, \"migrations\"))\n\t})\n}", "func (component *Database) createMigrateVersionTable() error {\n\tsession := component.NewSession()\n\tmigration := new(tables.Migration)\n\treturn session.Sync2(migration)\n}", "func DbMigrate() (*gorm.DB, error) {\n\t// conn, err := ConnectDb()\n\t// if err != nil {\n\t// \treturn nil, err\n\t// }\n\t// defer conn.Close()\n\n\tDbClient.AutoMigrate(&models.News{}, &models.Topic{})\n\tlog.Println(\"Migration has been processed\")\n\n\treturn DbClient, nil\n}", "func init() {\n\tMigrations = append(Migrations, addUserMigration0001)\n}", "func NewMantle(name string) (*Mantle, error) {\n\tdbPath := filepath.Join(botDir, \"mantle_\"+name+\".db\")\n\tc, err := core.New(&core.Config{\n\t\tDBPath: dbPath,\n\t\tNet: dex.Simnet,\n\t\tLogger: loggerMaker.Logger(\"CORE:\" + name),\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error initializing core: %w\", err)\n\t}\n\n\twaiter := dex.NewStartStopWaiter(c)\n\twaiter.Start(ctx)\n\n\terr = c.InitializeClient(pass, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize client\")\n\t}\n\n\tm := &Mantle{\n\t\tCore: c,\n\t\twaiter: waiter,\n\t\tname: name,\n\t\tlog: loggerMaker.Logger(\"MANTLE:\" + name),\n\t\twallets: make(map[uint32]*botWallet),\n\t\tnotes: c.NotificationFeed(),\n\t}\n\n\treturn m, nil\n}", "func DefaultMigratorConfig() MigratorConfig {\n\treturn MigratorConfig{\n\t\tBootstrap: false,\n\t\tMaxEntries: iotago.MaxMigratedFundsEntryCount,\n\t\tStartIndex: 1,\n\t\tStateFilePath: \"migrator.state\",\n\t}\n}", "func NewRepoMigrateCreated() *RepoMigrateCreated {\n\treturn &RepoMigrateCreated{}\n}", "func New(dbConn, migrationsPathh string) (*DB, error) {\n\tconn, err := sqlx.Connect(\"mysql\", dbConn)\n\tif err != nil {\n\t\tconn, err = sqlx.Connect(\"mysql\", \"comedian:comedian@tcp(localhost:3306)/comedian?parseTime=true\")\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tdb := &DB{conn}\n\n\tgoose.SetDialect(\"mysql\")\n\n\tcurrent, err := goose.EnsureDBVersion(conn.DB)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to EnsureDBVersion: %v\", err)\n\t}\n\n\tfiles, err := ioutil.ReadDir(migrationsPathh)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmigrations, err := goose.CollectMigrations(migrationsPathh, current, int64(len(files)))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, m := range migrations {\n\t\terr := m.Up(conn.DB)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn db, nil\n}", "func Migrate(db *gorm.DB) {\n\tdb.AutoMigrate(&User{})\n\tfmt.Println(\"Auto migration has been completed\")\n}", "func (driver *Driver) Migrate(migration *m.PlannedMigration) error {\n\t// Note: Driver does not support DDL statements in a transaction. If DDL statements are\n\t// executed in a transaction, it is an implicit commit.\n\t// See: http://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html\n\tvar migrationStatements *parser.ParsedMigration\n\n\tif migration.Direction == m.Up {\n\t\tmigrationStatements = migration.Up\n\t} else if migration.Direction == m.Down {\n\t\tmigrationStatements = migration.Down\n\t}\n\n\tfor _, sqlStmt := range migrationStatements.Statements {\n\t\tif len(strings.TrimSpace(sqlStmt)) > 0 {\n\t\t\tif _, err := driver.db.Exec(sqlStmt); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Error executing statement: %s\\n%s\", err, sqlStmt)\n\t\t\t}\n\t\t}\n\t}\n\n\tif migration.Direction == m.Up {\n\t\tif _, err := driver.db.Exec(\"INSERT INTO \"+mysqlTableName+\" (version) VALUES (?)\", migration.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tif _, err := driver.db.Exec(\"DELETE FROM \"+mysqlTableName+\" WHERE version=?\", migration.ID); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func Migrate(ctx context.Context, s *store.Store, serializer serialization.Serializer) error {\n\tsteps := []MigrationStep{\n\t\tcreateTempTables,\n\t\treencodeDocuments,\n\t\treencodeResultChunks,\n\t\treencodeDefinitions,\n\t\treencodeReferences,\n\t\tswapTables,\n\t}\n\n\t// NOTE: We need to serialize with the JSON serializer, NOT the current serializer. This is\n\t// because future migrations assume that v4 was written with the most current serializer at\n\t// that time. Using the current serializer will cause future migrations to fail to read the\n\t// encoded data.\n\tdeserializer := jsonserializer.New()\n\n\tfor _, step := range steps {\n\t\tif err := step(ctx, s, deserializer, serializer); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (s Sequence) Migrate() error {\n\tif s.cfg.Active && s.db != nil {\n\t\treturn goose.Up(s.db, s.cfg.Dir)\n\t}\n\n\treturn nil\n}", "func init() {\n\tmigrations.AddPluginMigration(\"inputs.cassandra\", migrate)\n}", "func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {\n\tmigrate, err := schema.NewMigrate(s.drv, opts...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"ent/migrate: %w\", err)\n\t}\n\treturn migrate.Create(ctx, tables...)\n}", "func Migrate() error {\n\n\toldVersion, newVersion, err := migrations.Run(database.DB, \"init\")\n\toldVersion, newVersion, err = migrations.Run(database.DB)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif newVersion != oldVersion {\n\t\tlog.Printf(\"migrated from version %d to %d\\n\", oldVersion, newVersion)\n\t}\n\t// else {\n\t// \tlog.Printf(\"version is %d\\n\", oldVersion)\n\t// }\n\treturn nil\n}", "func Migrate(db *gorm.DB) {\n\tdb.AutoMigrate(&User{}, &Team{})\n\n\tdb.Model(&Team{}).AddForeignKey(\"owner_id\", \"users(id)\", \"CASCADE\", \"CASCADE\")\n\tfmt.Println(\"Auto Migration has beed processed\")\n}", "func Migrations() *Migrate {\n\tif migrations == nil {\n\t\tmigrations = &Migrate{\n\t\t\tdb: nil,\n\t\t\tprepared: false,\n\t\t\tmigrations: map[string]*gormigrate.Migration{},\n\t\t}\n\t}\n\n\treturn migrations\n}", "func New() Mediator {\n\treturn Mediator{Database:make(map[string]dbRecord)}\n}", "func (m *migrator) Migrate() error {\n\tmigrate.SetTable(m.config.MigrationsTable)\n\n\t_, err := migrate.Exec(\n\t\tm.db,\n\t\t\"mysql\",\n\t\t&migrate.FileMigrationSource{\n\t\t\tDir: m.config.MigrationsDir,\n\t\t},\n\t\tmigrate.Up,\n\t)\n\n\tif err != nil {\n\t\tif !m.config.AllowOutdatedMigrations {\n\t\t\treturn err\n\t\t}\n\n\t\tif err2, ok := err.(*migrate.PlanError); !ok || err2.ErrorMessage != \"unknown migration in database\" {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func AddMigrations(mg *Migrator) {\n\taddMigrationLogMigrations(mg)\n\taddCollectorMigration(mg)\n\taddCheckMigration(mg)\n\taddEndpointMigration(mg)\n\taddAlertSchedulerValueMigration(mg)\n\taddQuotaMigration(mg)\n}", "func migrate() {\n\n}", "func NewMigrationContext(ctx context.Context) context.Context {\n\treq := &http.Request{Host: \"localhost\"}\n\tparams := url.Values{}\n\tctx = goa.NewContext(ctx, nil, req, params)\n\t// set a random request ID for the context\n\tvar reqID string\n\tctx, reqID = client.ContextWithRequestID(ctx)\n\n\tlog.Debug(ctx, nil, \"Initialized the migration context with Request ID: %v\", reqID)\n\n\treturn ctx\n}", "func newMigratorMetrics(registerFunc func(k8smetrics.Registerable) error) *migratorMetrics {\n\t// objectMigrates is defined in kube-storave-version-migrator\n\tobjectsMigrated := k8smetrics.NewCounterVec(\n\t\t&k8smetrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"migrated_objects\",\n\t\t\tHelp: \"The total number of objects that have been migrated, labeled with the full resource name\",\n\t\t}, []string{\"resource\"})\n\tregisterFunc(objectsMigrated)\n\n\t// migration is defined in kube-storave-version-migrator\n\tmigration := k8smetrics.NewCounterVec(\n\t\t&k8smetrics.CounterOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"migrations\",\n\t\t\tHelp: \"The total number of completed migration, labeled with the full resource name, and the status of the migration (failed or succeeded)\",\n\t\t}, []string{\"resource\", \"status\"})\n\tregisterFunc(migration)\n\n\t// migrationDuration is not defined upstream but uses the same Namespace and Subsystem\n\t// as the other metrics that are defined in kube-storave-version-migrator\n\tmigrationDuration := k8smetrics.NewHistogramVec(\n\t\t&k8smetrics.HistogramOpts{\n\t\t\tNamespace: namespace,\n\t\t\tSubsystem: subsystem,\n\t\t\tName: \"migration_duration_seconds\",\n\t\t\tHelp: \"How long a successful migration takes in seconds, labeled with the full resource name\",\n\t\t\tBuckets: prometheus.ExponentialBuckets(120, 2, 7),\n\t\t}, []string{\"resource\"})\n\tregisterFunc(migrationDuration)\n\n\treturn &migratorMetrics{\n\t\tobjectsMigrated: objectsMigrated,\n\t\tmigration: migration,\n\t\tmigrationDuration: migrationDuration,\n\t}\n}", "func NewDBMigrationSuite(params DBMigrationSuiteParams, dnsSubdomain string, client *model.Client, kubeClient kubernetes.Interface, logger logrus.FieldLogger) *DBMigrationSuite {\n\tinstallationSuite := NewInstallationSuite(params.InstallationSuiteParams, InstallationSuiteMeta{}, dnsSubdomain, client, kubeClient, nil, logger)\n\n\treturn &DBMigrationSuite{\n\t\tInstallationSuite: installationSuite,\n\t\tclient: client,\n\t\tkubeClient: kubeClient,\n\t\tlogger: logger.WithField(\"suite\", \"db-migration\"),\n\t\tParams: params,\n\t\tMeta: DBMigrationSuiteMeta{},\n\t}\n}", "func initMigrate() (bool, bool) {\n\tvar err error\n\tconnectionString = fmt.Sprintf(\"%s://%s:%s@%s:%s/%s?sslmode=%s\", dbDriver, dbUser, dbPassword, hostIP, hostPort, dbName, sslMode)\n\tif trafficVault {\n\t\tmigrateInstance, err = migrate.New(\"file:\"+trafficVaultMigrationsPath, connectionString)\n\t} else {\n\t\tmigrateInstance, err = migrate.New(\"file:\"+dbMigrationsDir, connectionString)\n\t}\n\tif errors.Is(err, os.ErrNotExist) {\n\t\treturn false, false\n\t}\n\tif err != nil {\n\t\tdie(\"Starting Migrate: \" + err.Error())\n\t}\n\tmigrateInstance.Log = &Log{}\n\treturn maybeMigrateFromGoose(), true\n}", "func NewInitiator(opts *xmsv3.PostInitiatorsReq) (resp *xmsv3.PostInitiatorsResp, err error) {\n\treturn xms.PostInitiators(opts)\n}", "func (factory) Create(cfg config.NodeHostConfig,\n\tcb config.LogDBCallback, dirs []string, wals []string) (raftio.ILogDB, error) {\n\treturn CreateTan(cfg, cb, dirs, wals)\n}", "func Migrate() {\n\tif err := Db.Ping(); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdriver, _ := postgres.WithInstance(Db, &postgres.Config{})\n\n\tm, e := migrate.NewWithDatabaseInstance(\n\t\t\"file:///home/osama/go/src/graphServer/db/mydatabase\",\n\t\t\"postgres\",\n\t\tdriver,\n\t)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\n\t\tfmt.Println(\"Eror\")\n\t\tlog.Fatal(err)\n\t}\n\n}", "func initialMigration() {\n\tdb, err := gorm.Open(\"sqlite3\", \"test.db\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\tdefer db.Close()\n\n\t// Migrate the schema\n\tdb.AutoMigrate(&User{})\n}", "func (s *permisoService) Migrate() error {\n\treturn nil\n\t// return s.service.Migrate()\n}", "func (d *SQLike) Migrate(tk *wanderer.Toolkit, migration *wanderer.Migration) error {\n\tif d.env.Migrations == nil || len(d.env.Migrations) == 0 {\n\t\treturn nil\n\t}\n\n\treturn sqlike.RunMigration(d.env.DB, filepath.Join(d.env.Migrations...), migration)\n}", "func newShardPersistence(db sqlplugin.DB, currentClusterName string, log log.Logger) (persistence.ShardManager, error) {\n\treturn &sqlShardManager{\n\t\tsqlStore: sqlStore{\n\t\t\tdb: db,\n\t\t\tlogger: log,\n\t\t},\n\t\tcurrentClusterName: currentClusterName,\n\t}, nil\n}", "func New(db *db.DB) core.StepStore {\n\treturn &stepStore{db}\n}", "func New(db *reform.DB, logger *logrus.Logger) *MW {\n\treturn &MW{\n\t\tdb: db,\n\t\tlog: logger,\n\t}\n}", "func New(log logrus.FieldLogger, cig ConsumerInstanceGetter, schemas ...StateManager) *Manager {\n\thandlers := make(map[string]StateManager, len(schemas))\n\n\tmanager := &Manager{\n\t\tlog: log,\n\t\thandlers: handlers,\n\t\tcig: cig,\n\t\tdg: &duplicateGuard{\n\t\t\tcache: map[string]interface{}{},\n\t\t\tlock: &sync.Mutex{},\n\t\t},\n\t}\n\n\tfor _, schema := range schemas {\n\t\tmanager.RegisterNewSchema(schema)\n\t}\n\n\treturn manager\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func New() Manager {\n\treturn &manager{dao: dao.New()}\n}", "func (m *MigrationService) Migrate(args []string) error {\n\n\tfolder, _ := m.getCurrentFolder()\n\tluaRunner := luascript.NewLGoLua()\n\tluaRunner.RunLua(folder)\n\treturn nil\n}", "func New(connectionString string, log *log.Logger) (*Store, error) {\n\tdb, err := gorm.Open(postgres.Open(connectionString), &gorm.Config{})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := db.AutoMigrate(&gh.Repository{}, &gh.Commit{}); err != nil {\n\t\treturn nil, err\n\t}\n\tlog.Println(\"db init successful\")\n\treturn &Store{\n\t\tdb: db,\n\t\tlog: log,\n\t}, nil\n}", "func (m *SqlxMigrate) Migrate() error {\n\terr := m.createMigrationTable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, migration := range m.migrations {\n\t\tvar found string\n\t\terr := m.db.Get(&found, \"SELECT id FROM migrations WHERE id=?\", migration.ID)\n\t\tswitch err {\n\t\tcase sql.ErrNoRows:\n\t\t\tlog.Printf(\"Running migration: %v\\n\", migration.ID)\n\t\t\t// we need to run the migration so we continue to code below\n\t\tcase nil:\n\t\t\tlog.Printf(\"Skipping migration: %v\\n\", migration.ID)\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"looking up migration by id: %w\", err)\n\t\t}\n\t\terr = m.runMigration(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "0.7871999", "0.7779378", "0.7431109", "0.7431109", "0.65816855", "0.6477545", "0.6307592", "0.6224991", "0.61895764", "0.6133309", "0.61306", "0.6119002", "0.6105274", "0.6100708", "0.5975033", "0.59550226", "0.5905531", "0.588605", "0.5720147", "0.5672678", "0.5659228", "0.55868393", "0.5538255", "0.5538238", "0.55103433", "0.5504967", "0.5426139", "0.54207873", "0.5359475", "0.53543013", "0.53029615", "0.52664715", "0.5259229", "0.52461493", "0.52202517", "0.52006125", "0.5125203", "0.51251155", "0.511607", "0.50829655", "0.50730526", "0.5068908", "0.50674385", "0.50376034", "0.5018435", "0.50057995", "0.5000239", "0.49837658", "0.497264", "0.4966949", "0.4934293", "0.4902053", "0.48946851", "0.4880553", "0.48732832", "0.48634902", "0.4844971", "0.48384255", "0.48285225", "0.48273343", "0.48136297", "0.48110488", "0.4809255", "0.47797555", "0.4771375", "0.47514942", "0.47360754", "0.4713629", "0.4712482", "0.4710589", "0.4708774", "0.4701886", "0.46986088", "0.46941975", "0.46863565", "0.46633735", "0.46632674", "0.4662466", "0.46613714", "0.4658094", "0.46568745", "0.46491417", "0.46398753", "0.46366766", "0.462824", "0.46220064", "0.4620666", "0.4617935", "0.46143574", "0.460923", "0.46085262", "0.4598193", "0.4597634", "0.45769805", "0.45757994", "0.45624372", "0.45618477", "0.45612332", "0.45511836", "0.45493189" ]
0.6497706
5
Run launches the migration
func (m *Migrator) Run() { // filename->key->val map i18nMultiMap := make(map[string]map[string]string) // run the workers to search for query for _, src := range m.src { filepath.Walk(src, func(path string, file os.FileInfo, err error) error { if !file.IsDir() { m.wg.Add(1) go m.searchInFile(path) } return nil }) } // wait for workers and then close the result chan go func() { m.wg.Wait() close(m.result) }() // consume the result chan for item := range m.result { _, ok := i18nMultiMap[item.filename] if !ok { i18nMultiMap[item.filename] = make(map[string]string) } i18nMultiMap[item.filename][item.key] = item.value } // write files for filename, i18nMap := range i18nMultiMap { if len(i18nMap) == 0 { continue } f, err := os.Create(fmt.Sprintf("%s/%s", m.dst, filename)) defer f.Close() check(err) for _, key := range m.keys { if len(key) == 0 || strings.HasPrefix(key, "#") { f.WriteString(fmt.Sprintln(key)) continue } val, ok := i18nMap[key] if ok { f.WriteString(fmt.Sprintln(val)) } } } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (this *Migrate) Run(args []string) (exitCode int) {\n\tvar how bool\n\tctx := base.GetMigrationContext()\n\tcmdFlags := flag.NewFlagSet(\"migrate\", flag.ContinueOnError)\n\tcmdFlags.StringVar(&ctx.InspectorConnectionConfig.Key.Hostname, \"host\", \"127.0.0.1\", \"\")\n\tcmdFlags.IntVar(&ctx.InspectorConnectionConfig.Key.Port, \"port\", 3306, \"\")\n\tcmdFlags.StringVar(&ctx.DatabaseName, \"db\", \"\", \"\")\n\tcmdFlags.StringVar(&ctx.OriginalTableName, \"table\", \"\", \"\")\n\tcmdFlags.StringVar(&ctx.AlterStatement, \"alter\", \"\", \"\")\n\tcmdFlags.BoolVar(&how, \"how\", false, \"\")\n\tcmdFlags.BoolVar(&ctx.Noop, \"dryrun\", false, \"\")\n\tcmdFlags.StringVar(&ctx.CliUser, \"user\", \"root\", \"\")\n\tcmdFlags.StringVar(&ctx.CliPassword, \"pass\", \"\", \"\")\n\tcmdFlags.Usage = func() { this.Ui.Output(this.Help()) }\n\tif err := cmdFlags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\tif how {\n\t\tthis.printHowItWorks()\n\t\treturn\n\t}\n\n\tctx.AllowedRunningOnMaster = true\n\tctx.OkToDropTable = true\n\tctx.InitiallyDropOldTable = true\n\tctx.InitiallyDropGhostTable = true\n\tctx.ServeSocketFile = \"/tmp/dbc.migrate.sock\"\n\tctx.SetChunkSize(1000)\n\tctx.SetDMLBatchSize(100)\n\tctx.SetDefaultNumRetries(3)\n\tctx.ApplyCredentials()\n\n\tlog.SetLevel(log.DEBUG)\n\n\tlog.Infof(\"starting\")\n\n\t// a migrator contains a sql parser(parsing alter statement), an inspector, applier and binlog streamer.\n\t// migrator.onChangelogStateEvent\n\t// migrator.onApplyEventStruct\n\t// 1. change log table\n\t// 2. ghost table\n\t// 3. alter ghost table\n\tmigrator := logic.NewMigrator()\n\tif err := migrator.Migrate(); err != nil {\n\t\tmigrator.ExecOnFailureHook()\n\t\tlog.Fatale(err)\n\t}\n\tlog.Infof(\"OK %d rows copied, %s, %s\", ctx.GetTotalRowsCopied(), ctx.ElapsedRowCopyTime(), ctx.ElapsedTime())\n\n\treturn\n}", "func (c *generateMigrationCommand) Run(args []string) error {\n\tif len(args) < 1 || args[0] == \"\" {\n\t\treturn fmt.Errorf(\"no NAME given\")\n\t}\n\tname := args[0]\n\tif c.option.ORM == \"\" {\n\t\tc.option.ORM = defaultORM\n\t}\n\torm, exists := ORM[c.option.ORM]\n\tif !exists {\n\t\treturn fmt.Errorf(\"unsupported ORM: `%v'\", c.option.ORM)\n\t}\n\tnow := _time.Now().Format(\"20060102150405\")\n\tdata := map[string]interface{}{\n\t\t\"Name\": util.ToCamelCase(name),\n\t\t\"TimeStamp\": now,\n\t\t\"ImportPath\": orm.ImportPath(),\n\t\t\"TxType\": reflect.TypeOf(orm.TransactionType()).String(),\n\t}\n\tif err := util.CopyTemplate(\n\t\tfilepath.Join(skeletonDir(\"migration\"), \"migration.go\"+util.TemplateSuffix),\n\t\tfilepath.Join(\"db\", \"migration\", fmt.Sprintf(\"%v_%v.go\", now, util.ToSnakeCase(name))),\n\t\tdata,\n\t); err != nil {\n\t\treturn err\n\t}\n\tinitPath := filepath.Join(\"db\", \"migration\", \"init.go\")\n\tif _, err := os.Stat(initPath); os.IsNotExist(err) {\n\t\tappDir, err := util.FindAppDir()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := util.CopyTemplate(\n\t\t\tfilepath.Join(skeletonDir(\"migration\"), \"init.go\"+util.TemplateSuffix),\n\t\t\tinitPath, map[string]interface{}{\n\t\t\t\t\"typeName\": c.option.ORM,\n\t\t\t\t\"tx\": strings.TrimSpace(util.GoString(orm)),\n\t\t\t\t\"dbImportPath\": path.Join(appDir, \"db\"),\n\t\t\t},\n\t\t); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&Todo{})\n\n\tfmt.Println(\"AutoMigrations completed.\")\n}", "func RunDBMigrate() error {\n\t// Add your custom code\n\tfmt.Println(\"RunDBMigrate: not implemented yet!\")\n\treturn nil\n}", "func (ctrl *MigrateController) Run(c *gin.Context) {\n\tmigrations.Run()\n\n\tc.String(http.StatusOK, \"complete \"+time.Now().Format(\"2006-01-02 15:04:05\"))\n}", "func RunMigrations(command *string) {\n\tswitch *command {\n\tcase \"new\":\n\t\tmigrateNew()\n\t\tos.Exit(0)\n\tcase \"up\":\n\t\tmigrateUp(models.GetDB(), 0)\n\t\tos.Exit(0)\n\tcase \"down\":\n\t\tmigrateDown(models.GetDB(), 1)\n\t\tos.Exit(0)\n\tcase \"redo\":\n\t\tmigrateDown(models.GetDB(), 1)\n\t\tmigrateUp(models.GetDB(), 1)\n\t\tos.Exit(0)\n\tcase \"skip\":\n\tdefault:\n\t\tlog.Fatalf(\"Wrong migration flag %q, acceptable values: up, down\\n\", *command)\n\t}\n}", "func RunMigrations(db *pg.DB) {\n\tversion, err := migrations.Version(db)\n\n\tif err != nil {\n\t\t_, _, err := migrations.Run(db, \"init\")\n\t\tlogger.Info(\"[MIGRATION] Migration table created\")\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n\n\tlogger.Info(\"[MIGRATION] Current version: \", version)\n\t_, newVersion, err := migrations.Run(db, \"up\")\n\n\tif err != nil {\n\t\tlogger.Info(\"An error happend during migration\")\n\t\tpanic(err)\n\t}\n\n\tif newVersion != version {\n\t\tlogger.Info(\"[MIGRATION] Migrated from version %d to %d\\n\", version, newVersion)\n\t} else {\n\t\tlogger.Info(\"[MIGRATION] Up to date\")\n\t}\n}", "func runMigrate() {\n\tif err := opts.validateAndDefault(); err != nil {\n\t\tklog.Fatalf(\"%v\", err)\n\t}\n\tcopyBinaries()\n\n\ttarget := &EtcdVersionPair{\n\t\tversion: MustParseEtcdVersion(opts.targetVersion),\n\t\tstorageVersion: MustParseEtcdStorageVersion(opts.targetStorage),\n\t}\n\n\tmigrate(\n\t\topts.name, opts.port, opts.peerListenUrls, opts.peerAdvertiseUrls, opts.clientListenUrls,\n\t\topts.binDir, opts.dataDir, opts.etcdDataPrefix, opts.ttlKeysDirectory, opts.initialCluster,\n\t\ttarget, opts.supportedVersions, opts.etcdServerArgs)\n}", "func Run(db DB, a ...string) (oldVersion, newVersion int64, err error) {\n\t// Make a copy so there are no side effects of sorting.\n\tmigrations := make([]Migration, len(allMigrations))\n\tcopy(migrations, allMigrations)\n\treturn RunMigrations(db, migrations, a...)\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := db.getMigrations(ctx)\n\tlogger.Infof(\"database migrations started\")\n\tif err := m.Migrate(); err != nil {\n\t\tlogger.Errorf(\"migrations failed: %v\", err)\n\t\treturn err\n\t}\n\tlogger.Infof(\"database migrations completed\")\n\treturn nil\n}", "func (db *Database) RunMigrations(ctx context.Context) error {\n\tlogger := logging.FromContext(ctx)\n\tm := gormigrate.New(db.db, gormigrate.DefaultOptions, []*gormigrate.Migration{\n\t\t{\n\t\t\tID: \"00001-CreateUsers\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating users table\")\n\t\t\t\treturn tx.AutoMigrate(&User{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"users\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00002-CreateVerificationCodes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating verification codes table\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"verification_codes\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00003-CreateAuthorizedApps\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating authorized apps table\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"authorized_apps\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00004-CreateTokens\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating tokens table\")\n\t\t\t\treturn tx.AutoMigrate(&Token{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"tokens\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00005-CreateCleanups\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: creating cleanup status table\")\n\t\t\t\tif err := tx.AutoMigrate(&CleanupStatus{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// Seed database w/ cleanup record.\n\t\t\t\tif err := tx.Create(&CleanupStatus{Type: \"cleanup\", Generation: 1, NotBefore: time.Now()}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"cleanup_statuses\").Error\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00006-AddIndexes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: add users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).AddIndex(\"users_purge_index\", \"disabled\", \"updated_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"ver_code_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: add tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).AddIndex(\"token_purge_index\", \"expires_at\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: drop users purge index\")\n\t\t\t\tif err := tx.Model(&User{}).RemoveIndex(\"users_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop verification code purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"ver_code_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tlogger.Infof(\"db migrations: drop tokens purge index\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).RemoveIndex(\"token_purge_index\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00007-AddSymptomOnset\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename test_date to symptom_date\")\n\t\t\t\t// AutoMigrate will add missing fields.\n\t\t\t\tif err := tx.AutoMigrate(&VerificationCode{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&VerificationCode{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif err := tx.AutoMigrate(&Token{}).Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\t// If not upgrading from an old version, this column will have never been created.\n\t\t\t\tif tx.NewScope(&Token{}).HasColumn(\"test_date\") {\n\t\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"test_date\").Error; err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Info(\"db migrations: rename symptom_date to test_date\")\n\t\t\t\tif err := tx.Model(&VerificationCode{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&Token{}).DropColumn(\"symptom_date\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00008-AddKeyTypes\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: upgrading authorized_apps table.\")\n\t\t\t\treturn tx.AutoMigrate(&AuthorizedApp{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"admin_key\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00009-AddIssuerColumns\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding issuer columns to issued codes\")\n\t\t\t\treturn tx.AutoMigrate(&VerificationCode{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_user\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tif err := tx.Model(&AuthorizedApp{}).DropColumn(\"issuing_app\").Error; err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tID: \"00010-AddSMSConfig\",\n\t\t\tMigrate: func(tx *gorm.DB) error {\n\t\t\t\tlogger.Infof(\"db migrations: adding sms_configs table\")\n\t\t\t\treturn tx.AutoMigrate(&SMSConfig{}).Error\n\t\t\t},\n\t\t\tRollback: func(tx *gorm.DB) error {\n\t\t\t\treturn tx.DropTable(\"sms_configs\").Error\n\t\t\t},\n\t\t},\n\t})\n\n\tlogger.Infof(\"database migrations complete\")\n\n\treturn m.Migrate()\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.Set(\"gorm:table_options\", \"ENGINE=InnoDB\")\n\tdb.Set(\"gorm:table_options\", \"collation_connection=utf8_general_ci\")\n\tdb.AutoMigrate(&model.User{}, &model.Todo{})\n}", "func RunMigrations(c config.Context) error {\n\treturn c.Db.AutoMigrate(&Plot{})\n}", "func RunMigrations(db *gorm.DB) {\n\tdb.AutoMigrate(&models.Article{})\n\tdb.AutoMigrate(&models.Page{})\n}", "func Run(db pgmigrations.DB, a ...string) (oldVersion, newVersion int64, err error) {\n\treturn pgmigrations.Run(db, a...)\n}", "func (c *MigrationsCmd) Run(cmd *cobra.Command, args []string) {\n\tc.menu.Create().MountMenu().RunMenu(args)\n}", "func (s *SQLStore) RunMigrations() error {\n\tcurrentSchemaVersion, err := s.GetCurrentVersion()\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to get the current schema version\")\n\t}\n\n\tif currentSchemaVersion.LT(LatestVersion()) {\n\t\tif err := s.Migrate(currentSchemaVersion); err != nil {\n\t\t\treturn errors.Wrapf(err, \"failed to complete migrations\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func runFirstMigration() error {\n\tsourceDriver, sourceDriverErr := source.Open(\"file:\" + dbMigrationsDir)\n\tif sourceDriverErr != nil {\n\t\treturn fmt.Errorf(\"opening the migration source driver: \" + sourceDriverErr.Error())\n\t}\n\tdbDriver, dbDriverErr := database.Open(connectionString)\n\tif dbDriverErr != nil {\n\t\treturn fmt.Errorf(\"opening the dbdriver: \" + dbDriverErr.Error())\n\t}\n\tfirstMigration, firstMigrationName, migrationReadErr := sourceDriver.ReadUp(firstMigrationTimestamp)\n\tif migrationReadErr != nil {\n\t\treturn fmt.Errorf(\"reading migration %s: %w\", firstMigrationName, migrationReadErr)\n\t}\n\tif setDirtyVersionErr := dbDriver.SetVersion(int(firstMigrationTimestamp), true); setDirtyVersionErr != nil {\n\t\treturn fmt.Errorf(\"setting the dirty version: %w\", setDirtyVersionErr)\n\t}\n\tif migrateErr := dbDriver.Run(firstMigration); migrateErr != nil {\n\t\treturn fmt.Errorf(\"running the migration: %w\", migrateErr)\n\t}\n\tif setVersionErr := dbDriver.SetVersion(int(firstMigrationTimestamp), false); setVersionErr != nil {\n\t\treturn fmt.Errorf(\"setting the version after successfully running the migration: %w\", setVersionErr)\n\t}\n\treturn nil\n}", "func runGoMigration(conf *DBConf, path string, version int64, direction int) error {\n\n\t// everything gets written to a temp dir, and zapped afterwards\n\td, e := ioutil.TempDir(\"\", \"goose\")\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\tdefer os.RemoveAll(d)\n\n\tdirectionStr := \"Down\"\n\tif direction == 1 {\n\t\tdirectionStr = \"Up\"\n\t}\n\n\ttd := &TemplateData{\n\t\tVersion: version,\n\t\tDBDriver: conf.Driver,\n\t\tDBOpen: conf.OpenStr,\n\t\tDirection: direction,\n\t\tFunc: fmt.Sprintf(\"%v_%v\", directionStr, version),\n\t}\n\tmain, e := writeTemplateToFile(filepath.Join(d, \"goose_main.go\"), goMigrationTmpl, td)\n\tif e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\toutpath := filepath.Join(d, filepath.Base(path))\n\tif _, e = copyFile(outpath, path); e != nil {\n\t\tlog.Fatal(e)\n\t}\n\n\tcmd := exec.Command(\"go\", \"run\", main, outpath)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stderr\n\tif e = cmd.Run(); e != nil {\n\t\tlog.Fatal(\"`go run` failed: \", e)\n\t}\n\n\treturn nil\n}", "func (c *Migrate) Execute() error {\n\n\tseed, err := inject.Migrate(c.ProjectPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\twd, err := os.Getwd()\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := os.Chdir(c.ProjectPath); err != nil {\n\t\treturn err\n\t}\n\tfmt.Println(\"💾 Running migrations...\")\n\terr = seed()\n\tif err1 := os.Chdir(wd); err1 != nil && err == nil {\n\t\terr = err1\n\t}\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfmt.Println(\"✅ Database migrated!\")\n\n\treturn nil\n}", "func RunMigrations(db DB, migrations []Migration, a ...string) (oldVersion, newVersion int64, err error) {\n\tsortMigrations(migrations)\n\n\tvar cmd string\n\tif len(a) > 0 {\n\t\tcmd = a[0]\n\t}\n\n\terr = createTables(db)\n\tif err != nil {\n\t\treturn\n\t}\n\n\toldVersion, err = Version(db)\n\tif err != nil {\n\t\treturn\n\t}\n\tnewVersion = oldVersion\n\n\tswitch cmd {\n\tcase \"create\":\n\t\tif len(a) < 2 {\n\t\t\tfmt.Println(\"Please enter migration description\")\n\t\t\treturn\n\t\t}\n\n\t\tvar version int64\n\t\tif len(migrations) > 0 {\n\t\t\tversion = migrations[len(migrations)-1].Version\n\t\t}\n\n\t\tfilename := fmtMigrationFilename(version+1, strings.Join(a[1:], \"_\"))\n\t\terr = createMigrationFile(filename)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tfmt.Println(\"created migration\", filename)\n\t\treturn\n\tcase \"version\":\n\t\treturn\n\tcase \"up\", \"\":\n\t\tfor i := range migrations {\n\t\t\tm := &migrations[i]\n\t\t\tif m.Version <= oldVersion {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\terr = m.Up(db)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tnewVersion = m.Version\n\t\t\terr = SetVersion(db, newVersion)\n\t\t\tif err != nil {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\treturn\n\tcase \"down\":\n\t\tnewVersion, err = down(db, migrations, oldVersion)\n\t\treturn\n\tcase \"reset\":\n\t\tversion := oldVersion\n\t\tfor {\n\t\t\tnewVersion, err = down(db, migrations, version)\n\t\t\tif err != nil || newVersion == version {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tversion = newVersion\n\t\t}\n\tcase \"set_version\":\n\t\tif len(a) < 2 {\n\t\t\terr = fmt.Errorf(\"set_version requires version as 2nd arg, e.g. set_version 42\")\n\t\t\treturn\n\t\t}\n\n\t\tnewVersion, err = strconv.ParseInt(a[1], 10, 64)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\terr = SetVersion(db, newVersion)\n\t\treturn\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupported command: %q\", cmd)\n\t\treturn\n\t}\n}", "func (c *CreateCommand) Run(args []string) int {\n\t// New DB Config\n\tfmt.Print(\"New DB Config...\")\n\tif err := dbex.NewConfig(); err != nil {\n\t\tfmt.Println(err)\n\t\treturn 1\n\t}\n\tfmt.Println(\"done\")\n\n\t// Create Database\n\tfmt.Print(\"Create Database...\")\n\tif err := CreateDatabase(dbex.GetConfig()); err != nil {\n\t\tif strings.Contains(err.Error(), \"database exists\") {\n\t\t\tfmt.Println(\"database already exists\")\n\t\t\treturn 0\n\t\t}\n\t\tfmt.Println(err)\n\t\treturn 1\n\t}\n\tfmt.Println(\"done\")\n\n\treturn 0\n}", "func (s *Starter) Run() error {\n\t// Step-1: rake config\n\t// Step-2: clone|use-local template\n\t// Step-3: ask-flow\n\t// Step-4: generate project\n\n\treturn nil\n}", "func runNamedMigration(migrationName string, db *sql.DB) {\n\tLogInfo(\"RUNNING %s MIGRATION\\n\", migrationName)\n\n\tcreateMigrationsTable(db)\n\n\tsqlQuery, fileErr := ioutil.ReadFile(fmt.Sprintf(\"./%s\", migrationName))\n\tif fileErr != nil {\n\t\tLogErr(\"%s\\n\", fileErr)\n\t}\n\n\tif checkIfMigrated(migrationName, db) {\n\t\tLogNotice(\"SKIPPING %s\\n\", migrationName)\n\t\treturn\n\t}\n\n\texecQuery(db, string(sqlQuery))\n\texecQuery(db, \"INSERT INTO _migrations (migration) VALUES($1)\", migrationName)\n\tLogSuccess(\"%s MIGRATED\\n\", migrationName)\n}", "func (m Migrator) RunMigrations() error {\n\t// Run everything in a transaction. In case of error, we can roll it back\n\ttx, err := m.Connection.Database.Begin()\n\tif err != nil {\n\t\t// Connection could not be started\n\t\treturn err\n\t}\n\n\t// First check if the database db_migrations exists\n\tres := tx.QueryRow(`SELECT EXISTS(\n\t\tSELECT *\n\t\tFROM information_schema.tables\n\t\tWHERE\n\t\t\ttable_schema = 'public' AND\n\t\t\ttable_name = 'db_migrations'\n\t)`)\n\n\tvar migTablePresent bool\n\terr = res.Scan(&migTablePresent)\n\tif err != nil {\n\t\t// result was invalid\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\talreadyRunMigrations := make(map[string]bool)\n\tif !migTablePresent {\n\t\t_, err = tx.Query(`\n\t\t\tCREATE TABLE db_migrations (version VARCHAR(50) NOT NULL, executed_at TIMESTAMP(0) NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY(version))\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not create db_migration table\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t} else {\n\t\tversionRows, err := tx.Query(`\n\t\t\tSELECT version FROM db_migrations\n\t\t`)\n\t\tif err != nil {\n\t\t\t// could not fetch the list of executed migrations\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tfor versionRows.Next() {\n\t\t\tvar version string\n\t\t\terr = versionRows.Scan(&version)\n\t\t\tif err != nil {\n\t\t\t\t// A version number could not be parsed\n\t\t\t\ttx.Rollback()\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\talreadyRunMigrations[version] = true\n\t\t}\n\t}\n\n\tavailableMigrations, err := m.checkAvailableMigrations()\n\tif err != nil {\n\t\ttx.Rollback()\n\t\treturn err\n\t}\n\n\tvar migrationsToRun []string\n\tfor version := range availableMigrations {\n\t\tif _, ok := alreadyRunMigrations[version]; !ok {\n\t\t\tmigrationsToRun = append(migrationsToRun, version)\n\t\t}\n\t}\n\tfor version := range alreadyRunMigrations {\n\t\tif _, ok := availableMigrations[version]; !ok {\n\t\t\t// Warn there is a present migration with no corresponding file\n\t\t}\n\t}\n\n\tfor _, version := range migrationsToRun {\n\t\tmigrationByteContent, err := migration.Asset(fmt.Sprintf(\"%s_up.sql\", version))\n\t\tif err != nil {\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\tmigrationContent := string(migrationByteContent)\n\n\t\t_, err = tx.Query(migrationContent)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t\t_, err = tx.Query(`INSERT INTO db_migrations (version) VALUES ($1)`, version)\n\t\tif err != nil {\n\t\t\t// There was an error running the migration\n\t\t\ttx.Rollback()\n\t\t\treturn err\n\t\t}\n\t}\n\n\ttx.Commit()\n\n\treturn nil\n}", "func RunMigrationsUp(gormdb *gorm.DB) {\n\tgormdb.AutoMigrate(&entities.Tag{})\n\tgormdb.AutoMigrate(&entities.RecordType{})\n\tgormdb.AutoMigrate(&entities.Record{})\n\tgormdb.Model(&entities.Record{}).AddForeignKey(\"record_type_id\", \"record_types(id)\", \"RESTRICT\", \"RESTRICT\")\n}", "func Run(db *sqlx.DB) {\n\trun(context.Background(), db, tasks)\n}", "func (r *Runner) Run(driver DriverInfo, migrations embed.FS) (*DBHandle, error) {\n\tres, err := r.pool.RunWithOptions(&driver.RunOpts, func(hc *docker.HostConfig) {\n\t\thc.AutoRemove = true\n\t\thc.RestartPolicy = docker.RestartPolicy{\n\t\t\tName: \"no\",\n\t\t}\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thandler, err := r.connectMigrate(res, driver, migrations)\n\tif err != nil {\n\t\t_ = res.Close()\n\t\treturn nil, err\n\t}\n\n\treturn handler, nil\n}", "func main() {\n\tcontainer := server.BuildContainer()\n\n\terr := container.Invoke(func(db *sql.DB) {\n\t\tdefer db.Close()\n\n\t\tmigration := &CreateUsersTable01{db}\n\n\t\tres, err := migration.Up()\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Println(res)\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func (w *DBMigrationSuite) RunDBMigration(ctx context.Context) error {\n\tif w.Meta.MigrationOperationID == \"\" {\n\t\tmigrationOP, err := w.client.MigrateInstallationDatabase(&model.InstallationDBMigrationRequest{\n\t\t\tInstallationID: w.InstallationSuite.Meta.InstallationID,\n\t\t\tDestinationDatabase: model.InstallationDatabaseMultiTenantRDSPostgres,\n\t\t\tDestinationMultiTenant: &model.MultiTenantDBMigrationData{DatabaseID: w.Params.DestinationDBID},\n\t\t})\n\t\tif err != nil {\n\t\t\treturn errors.Wrap(err, \"while triggering migration\")\n\t\t}\n\t\tw.Meta.MigrationOperationID = migrationOP.ID\n\t}\n\n\terr := pkg.WaitForDBMigrationToFinish(w.client, w.Meta.MigrationOperationID, w.logger)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"while waiting for migration\")\n\t}\n\n\treturn nil\n}", "func (db *Ops) Run(ctx context.Context) error {\n\tvar err error\n\n\tctx = log.ContextWithPrefix(ctx, logPrefix)\n\tlog.WithContext(ctx).Info(\"start initialization\")\n\n\tcontent := schemaV1Content\n\n\tdb.metaDB.WaitForStarting()\n\tif db.metaDB.IsLeader() {\n\t\tlistOfCommands := strings.Split(content, schemaDelimiter)\n\t\tfor _, cmd := range listOfCommands {\n\t\t\tif _, err := db.metaDB.Write(ctx, cmd); err != nil {\n\t\t\t\treturn errors.Errorf(\"error while creating db schema: %w\", err)\n\t\t\t}\n\t\t}\n\t}\n\n\tdb.writeTemplate, err = template.New(\"writeTemplate\").Parse(userInfoWriteTemplate)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error while parsing write template: %w\", err)\n\t}\n\n\tdb.queryTemplate, err = template.New(\"readTemplate\").Parse(userInfoQueryTemplate)\n\tif err != nil {\n\t\treturn errors.Errorf(\"error while parsing query template: %w\", err)\n\t}\n\n\tlog.WithContext(ctx).Info(\"done initialization\")\n\t// block until context is done\n\t<-ctx.Done()\n\tlog.WithContext(ctx).Info(\"userdata service is stopped\")\n\treturn nil\n}", "func Run() {\n\t// Load environment\n\tloadEnvironment()\n\t// Connecting to database\n\tdb := databaseConnect()\n\t// Creating dbr session\n\tsession := createDBRSession(db)\n\t// Initialize crons\n\tcronmaker.\n\t\tInitCrons(session).\n\t\tStartCronJobs()\n}", "func (s *Suite) Run(db *Db, up bool, maxSteps int) (int, int, error) {\n\ts.mtx.Lock()\n\tdefer s.mtx.Unlock()\n\tif l := len(s.Migrations); l == 0 {\n\t\treturn -1, 0, errors.New(\"cannot run suite, no migrations set\")\n\t}\n\terr := db.Query(s.Stmts.CreateTableSQL).Run()\n\tif err != nil {\n\t\treturn -1, 0, err\n\t}\n\tvar row struct {\n\t\tVersion int\n\t}\n\trow.Version = -1\n\terr = db.Query(s.Stmts.SelectVersionSQL).Rows(&row)\n\tif err != nil {\n\t\treturn -1, 0, err\n\t}\n\tstep := 0\n\tstepsApplied := 0\n\tcurrent := row.Version\n\tfor _, m := range s.buildList(up, row.Version) {\n\t\tif step++; maxSteps > 0 && step > maxSteps {\n\t\t\tbreak\n\t\t}\n\n\t\ttxn, err := db.DB.Begin()\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tnext := m.id\n\t\tif up {\n\t\t\t_, err = txn.Exec(m.Up)\n\t\t} else {\n\t\t\tnext--\n\t\t\t_, err = txn.Exec(m.Down)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tif current == -1 {\n\t\t\t_, err = txn.Exec(s.Stmts.InsertVersionSQL, next)\n\t\t} else {\n\t\t\t_, err = txn.Exec(s.Stmts.UpdateVersionSQL, next, current)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\n\t\tif err := txn.Commit(); err != nil {\n\t\t\treturn current, stepsApplied, err\n\t\t}\n\t\tcurrent = next\n\t\tstepsApplied++\n\t}\n\treturn current, stepsApplied, nil\n}", "func Perform(db *gorm.DB) {\r\n\r\n\tdb.AutoMigrate(\r\n\t\t&models.WorkItem{})\r\n}", "func RunMigrations(c *datastore.Client, ns string, migratable interface{}) {\n\n\tfmt.Println(\"Running Unison\")\n\n\t// Get the timestamp of the last applied migration\n\tlastAppliedMigrationTS := getLastAppliedMigrationTimeStamp(c, ns)\n\n\ttMigratable := reflect.TypeOf(migratable)\n\n\tmigrationMetaSet, err := generateMigrationMetaSet(tMigratable)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tsort.Sort(migrationMetaSet)\n\n\tvMigratable := reflect.ValueOf(migratable)\n\n\tfor _, migration := range migrationMetaSet.set {\n\n\t\tif migration.Timestamp <= lastAppliedMigrationTS {\n\t\t\tcontinue\n\t\t}\n\n\t\tfmt.Printf(\"Applying migration %d ... \", migration.Timestamp)\n\n\t\ttx, _ := c.NewTransaction(context.Background())\n\n\t\tmethod := vMigratable.MethodByName(migration.Name)\n\n\t\trtx := reflect.ValueOf(tx)\n\t\trns := reflect.ValueOf(ns)\n\n\t\tvalues := method.Call([]reflect.Value{rtx, rns})\n\n\t\tvalue := values[0]\n\n\t\tif !value.IsNil() {\n\t\t\te, _ := value.Interface().(error)\n\n\t\t\tfmt.Printf(\"Failed. Cause: %s\\n\", e.Error())\n\t\t\treturn\n\t\t}\n\n\t\ttxkey := &datastore.Key{Kind: UnisonMigrationMetaKind, Name: migration.Name, Namespace: ns}\n\t\tmigration.AppliedAt = time.Now()\n\n\t\ttx.Put(txkey, &migration)\n\n\t\t_, err := tx.Commit()\n\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tfmt.Printf(\"Done\\n\")\n\t}\n\n\tfmt.Printf(\"We are done !!\\n\")\n}", "func Up() error {\n\tdb, err := db()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvs, err := versions(db, false)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfiles, err := filepath.Glob(filepath.Join(DirName, \"*.up.sql\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trun := []string{}\n\tfor _, f := range files {\n\t\tname := filepath.Base(f[:len(f)-7])\n\t\texists := false\n\t\tfor _, v := range vs {\n\t\t\tif name == v {\n\t\t\t\texists = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !exists {\n\t\t\trun = append(run, name)\n\t\t}\n\t}\n\n\tfor _, r := range run {\n\t\tfmt.Println(\"running\", r)\n\t\tcontents, err := ioutil.ReadFile(filepath.Join(DirName, r+\".up.sql\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t_, err = db.Exec(string(contents))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(run) == 0 {\n\t\tfmt.Println(\"nothing to run\")\n\t}\n\n\treturn nil\n}", "func main() {\n\tvar (\n\t\terr error\n\t\tdbConn db.DB\n\t)\n\n\tfmt.Println(internal.VersionVerbose())\n\n\tutil.InitConfig()\n\n\terr = util.Retry(10, 250*time.Millisecond, func() error {\n\t\tdbConn, err = db.GetConnection()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).WithField(\"service\", \"auth\").Warning(\"Error connecting to db, retrying\")\n\t\t}\n\t\treturn err\n\t})\n\tif err != nil {\n\t\tlog.WithError(err).WithField(\"service\", \"auth\").Warning(\"Unable to connect to db, exiting\")\n\t\tos.Exit(1)\n\t}\n\n\terr = model.Migrate(dbConn)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tfmt.Println(\"Migrate succeeded\")\n}", "func RunUp(_ *context.ExecuteContext, t *Task) error {\n\tt.logger().Info(\"project up\")\n\treturn t.execCompose(\"up\", \"-d\")\n}", "func Run(conn db.Conn) {\n\tstore := NewStore()\n\tcreateMinionDir(store)\n\n\tgo runElection(conn, store)\n\tgo runNetwork(conn, store)\n\trunMinionSync(conn, store)\n}", "func (s upgradeStep) Run() error {\n\n\tchartDir, err := s.sourceGetter.SrcDirFor(s.component)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tupgradeResp, upgradeErr := s.helmClient.UpgradeRelease(\n\t\tchartDir,\n\t\ts.GetNamespacedName(),\n\t\ts.overrideData.ForRelease(s.component.GetReleaseName()),\n\t\tstring(s.step.profile))\n\n\tif upgradeErr != nil {\n\t\treturn s.onError(upgradeErr)\n\t}\n\n\ts.helmClient.PrintRelease(upgradeResp)\n\n\treturn nil\n}", "func Run(fields []types.FieldDescriptor, f flags.Flags) error {\n\tdriver, db := getDriverAndDB(f)\n\tdefer func() {\n\t\tif err := db.Close(); err != nil {\n\t\t\tlog.Print(err)\n\t\t}\n\t}()\n\tsqlInsertInput := action.SQLInsertInput{\n\t\tSingleInsertParams: &action.SingleInsertParams{\n\t\t\tDB: db,\n\t\t\tDriver: driver,\n\t\t\tTable: f.Table,\n\t\t\tFields: fields,\n\t\t},\n\t}\n\treturn runHelper(f, sqlInsertInput)\n}", "func RunMigrationsOnDb(conf *DBConf, migrationsDir string, target int64, db *sql.DB) (err error) {\n\tcurrent, err := EnsureDBVersion(conf, db)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tmigrations, err := goose.CollectMigrations(migrationsDir, current, target)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(migrations) == 0 {\n\t\tfmt.Printf(\"goose: no migrations to run. current version: %d\\n\", current)\n\t\treturn nil\n\t}\n\n\tms := migrationSorter(migrations)\n\tdirection := current < target\n\tms.Sort(direction)\n\n\tfmt.Printf(\"goose: migrating db environment '%v', current version: %d, target: %d\\n\",\n\t\tconf.Env, current, target)\n\n\tfor _, m := range ms {\n\n\t\tswitch filepath.Ext(m.Source) {\n\t\tcase \".sql\":\n\t\t\terr = runSQLMigration(conf, db, m.Source, m.Version, direction)\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"FAIL %w, quitting migration\", err)\n\t\t}\n\n\t\tfmt.Println(\"OK \", filepath.Base(m.Source))\n\t}\n\n\treturn nil\n}", "func (o *ImportOption) Run() error {\n\tf, err := os.Open(o.fileName)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open: %w\", err)\n\t}\n\tdefer f.Close()\n\n\treader := csv.NewReader(f)\n\n\tdb, err := sql.Open(o.DriverName, o.DSN)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to open: %w\", err)\n\t}\n\tdefer db.Close()\n\ttransaction := database.NewTransaction(db)\n\tmasterRepo := database.NewMasterRepository(transaction)\n\tmfRepo := database.NewMoneyForwardRepository(transaction)\n\n\tusecase := usecase.NewImportMoneyForwardRecords(reader, transaction, masterRepo, mfRepo)\n\tctx := context.Background()\n\tif err := usecase.Execute(ctx); err != nil {\n\t\treturn fmt.Errorf(\"failed to execute: %w\", err)\n\t}\n\n\treturn nil\n}", "func Migration(table, directory string) Initializer {\n\tif _, err := os.Stat(directory); os.IsNotExist(err) {\n\t\tstartup_base.PanicOnError(err, \"No database migration files found\")\n\t}\n\n\treturn func(db *sqlx.DB) error {\n\t\tmigrate.SetTable(table)\n\n\t\tmigrations := &migrate.FileMigrationSource{Dir: directory}\n\t\tn, err := migrate.Exec(db.DB, \"postgres\", migrations, migrate.Up)\n\t\tif err != nil {\n\t\t\treturn errors.WithMessage(err, \"applying database migration\")\n\t\t}\n\n\t\tlogrus.WithField(\"prefix\", \"database\").\n\t\t\tInfof(\"%d migrations executed\", n)\n\n\t\treturn nil\n\t}\n}", "func (m *Main) Run(ctx context.Context) (err error) {\n\t// // Initialize error tracking.\n\t// if m.Config.Rollbar.Token != \"\" {\n\t// \trollbar.SetToken(m.Config.Rollbar.Token)\n\t// \trollbar.SetEnvironment(\"production\")\n\t// \trollbar.SetCodeVersion(version)\n\t// \trollbar.SetServerRoot(\"github.com/benbjohnson/wtf\")\n\t// \twtf.ReportError = rollbarReportError\n\t// \twtf.ReportPanic = rollbarReportPanic\n\t// \tlog.Printf(\"rollbar error tracking enabled\")\n\t// }\n\n\t// Initialize event service for real-time events.\n\t// We are using an in-memory implementation but this could be changed to\n\t// a more robust service if we expanded out to multiple nodes.\n\n\t// eventService := inmem.NewEventService()\n\n\t// Attach our event service to the SQLite database so it can publish events.\n\t// m.DB.EventService = eventService\n\n\t// Expand the DSN (in case it is in the user home directory (\"~\")).\n\t// Then open the database. This will instantiate the SQLite connection\n\t// and execute any pending migration files.\n\tdsn, err := expandDSN(m.Config.DB.DSN)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot expand dsn: %w\", err)\n\t}\n\tif m.Client, err = ent.Open(\"postgres\", dsn); err != nil {\n\t\treturn fmt.Errorf(\"cannot open db: %w\", err)\n\t}\n\n\tif err := m.Client.Schema.Create(ctx, migrate.WithDropIndex(true), migrate.WithDropColumn(true)); err != nil {\n\t\treturn fmt.Errorf(\"failed creating schema resources: %v\", err)\n\t}\n\n\t// Create dependencies used by service middlewares\n\tvar logger log.Logger\n\t{\n\t\tlogger = log.NewLogfmtLogger(os.Stderr)\n\t\tlogger = log.With(logger, \"ts\", log.DefaultTimestampUTC)\n\t\tlogger = log.With(logger, \"caller\", log.DefaultCaller)\n\t}\n\n\tfieldKeys := []string{\"method\"}\n\trequestCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{\n\t\tNamespace: \"open_mesh\",\n\t\tSubsystem: \"booking\",\n\t\tName: \"request_count\",\n\t\tHelp: \"Number of requests received.\",\n\t}, fieldKeys)\n\terrorCount := kitprometheus.NewCounterFrom(stdprometheus.CounterOpts{\n\t\tNamespace: \"open_mesh\",\n\t\tSubsystem: \"booking\",\n\t\tName: \"error_count\",\n\t\tHelp: \"Number of errors occurred.\",\n\t}, fieldKeys)\n\trequestDuration := kitprometheus.NewSummaryFrom(stdprometheus.SummaryOpts{\n\t\tNamespace: \"open_mesh\",\n\t\tSubsystem: \"booking\",\n\t\tName: \"request_duration\",\n\t\tHelp: \"Total duration of requests in microseconds\",\n\t}, fieldKeys)\n\n\tredisCache := redis.NewRedisCache(&goredis.Options{\n\t\tAddr: m.Config.Redis.Addr,\n\t\tPassword: m.Config.Redis.Password,\n\t\tDB: m.Config.Redis.DB,\n\t})\n\n\t// Instantiate ent-backed services.\n\t// authService := ent.NewAuthService(m.Client)\n\tvar resourceService booking.ResourceService\n\t{\n\t\tresourceService = ent.NewResourceService(m.Client)\n\t\tresourceService = cache.ResourceCacheMiddleware(redisCache)(resourceService)\n\t\tresourceService = booking.ResourceValidationMiddleware()(resourceService)\n\t\tresourceService = logging.ResourceLoggingMiddleware(logger)(resourceService)\n\t\tresourceService = metrics.ResourceMetricsMiddleware(requestCount, errorCount, requestDuration)(resourceService)\n\t}\n\tvar bookingService booking.BookingService\n\t{\n\t\tbookingService = ent.NewBookingService(m.Client)\n\t\tbookingService = booking.BookingValidationMiddleware()(bookingService)\n\t\tbookingService = logging.BookingLoggingMiddleware(logger)(bookingService)\n\t\tbookingService = metrics.BookingMetricsMiddleware(requestCount, errorCount, requestDuration)(bookingService)\n\t}\n\tvar organizationService booking.OrganizationService\n\t{\n\t\torganizationService = ent.NewOrganizationService(m.Client)\n\t\torganizationService = logging.OrganizationLoggingMiddleware(logger)(organizationService)\n\t}\n\tvar unavailabilityService booking.UnavailabilityService\n\t{\n\t\tunavailabilityService = ent.NewUnavailabilityService(m.Client)\n\t\tunavailabilityService = logging.UnavailabilityLoggingMiddleware(logger)(unavailabilityService)\n\t\tunavailabilityService = metrics.UnavailabilityMetricsMiddleware(requestCount, errorCount, requestDuration)(unavailabilityService)\n\t}\n\tvar userService booking.UserService\n\t{\n\t\tuserService = ent.NewUserService(m.Client)\n\t}\n\tvar authService booking.AuthService\n\t{\n\t\tauthService = ent.NewAuthService(m.Client)\n\t\tauthService = logging.AuthLoggingMiddleware(logger)(authService)\n\t\tauthService = metrics.AuthMetricsMiddleware(requestCount, errorCount, requestDuration)(authService)\n\t}\n\t// var tokenService booking.TokenService\n\t// {\n\n\t// }\n\tvar oauthService booking.OAuthService\n\t{\n\t\toauthService = oauth.NewOAuthService(authService, map[string]*oauth2.Config{\n\t\t\tbooking.AuthSourceGitHub: {\n\t\t\t\tClientID: m.Config.GitHub.ClientID,\n\t\t\t\tClientSecret: m.Config.GitHub.ClientSecret,\n\t\t\t\tEndpoint: github.Endpoint,\n\t\t\t\tScopes: []string{},\n\t\t\t},\n\t\t})\n\t\toauthService = logging.OAuthLoggingMiddleware(logger)(oauthService)\n\t\toauthService = metrics.OAuthMetricsMiddleware(requestCount, errorCount, requestDuration)(oauthService)\n\t}\n\n\t// userService := sqlite.NewUserService(m.DB)\n\n\t// Attach user service to Main for testing.\n\t// m.UserService = userService\n\n\t// Set global GA settings.\n\t// html.MeasurementID = m.Config.GoogleAnalytics.MeasurementID\n\n\t// Copy configuration settings to the HTTP server.\n\tm.HTTPServer.Addr = m.Config.HTTP.Addr\n\tm.HTTPServer.Domain = m.Config.HTTP.Domain\n\tm.HTTPServer.HashKey = m.Config.HTTP.HashKey\n\tm.HTTPServer.BlockKey = m.Config.HTTP.BlockKey\n\tm.HTTPServer.GitHubClientID = m.Config.GitHub.ClientID\n\tm.HTTPServer.GitHubClientSecret = m.Config.GitHub.ClientSecret\n\n\t// Attach underlying services to the HTTP server.\n\t// m.HTTPServer.AuthService = authService\n\tm.HTTPServer.BookingService = bookingService\n\tm.HTTPServer.OAuthService = oauthService\n\tm.HTTPServer.OrganizationService = organizationService\n\tm.HTTPServer.ResourceService = resourceService\n\tm.HTTPServer.UnavailabilityService = unavailabilityService\n\tm.HTTPServer.UserService = userService\n\t// m.HTTPServer.EventService = eventService\n\t// m.HTTPServer.UserService = userService\n\n\t// Attach logger to server.\n\tm.HTTPServer.AttachLogger(logger)\n\t// Register routes that require services to be initialized.\n\tm.HTTPServer.RegisterRoutes()\n\n\t// Start the HTTP server.\n\tif err := m.HTTPServer.Open(); err != nil {\n\t\treturn err\n\t}\n\n\t// If TLS enabled, redirect non-TLS connections to TLS.\n\tif m.HTTPServer.UseTLS() {\n\t\tgo func() {\n\t\t\tlogger.Log(http.ListenAndServeTLSRedirect(m.Config.HTTP.Domain))\n\t\t}()\n\t}\n\n\t// Enable internal debug endpoints.\n\tgo func() { http.ListenAndServeDebug() }()\n\n\tlogger.Log(\"status\", \"running\", \"url\", m.HTTPServer.URL(), \"debug\", \"http://localhost:6060\", \"dsn\", m.Config.DB.DSN)\n\n\treturn nil\n}", "func Migrate() {\n\tif err := Migrations().Migrate(); err != nil {\n\t\tlog.Fatalf(\"Could not migrate: %v\", err)\n\t}\n\n\tlog.Printf(\"Migration did run successfully\")\n}", "func (c *InitCommand) Run(args []string) int {\n\tfs := c.Command.defaultFlagSet(\"gcloudInit\")\n\tfs.Parse(args)\n\n\tdbFile, err := c.Command.DbFile()\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to obtain database filename: %v\\n\", err)\n\t}\n\terr = cache.CreateOrUpdateDatabase(&dbFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create database: %v\\n\", err)\n\t}\n\tfmt.Printf(\"Opened database using file %s\\n\", dbFile)\n\n\tdb, err := c.DbHandle()\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to get database handle: %v\\n\", err)\n\t}\n\tdefer db.Close()\n\n\tproject := c.Command.Project\n\tif project == \"\" {\n\t\tlog.Fatalf(\"Need a project ID.\\n\")\n\t}\n\n\terr = cache.PopulateDatabase(db, project)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to populate database: %v\\n\", err)\n\t}\n\tfmt.Println(\"Populated database.\")\n\treturn 0\n}", "func (m *Main) Run(ctx context.Context) (err error) {\n\tapi.ReportError = defaultReportError\n\tapi.ReportPanic = defaultReportPanic\n\n\t// Open the database. This will instantiate the MariaDB connection\n\t// and execute any pending migration files.\n\tm.DB.DSN = m.Config.DB.DSN\n\tif err := m.DB.Open(); err != nil {\n\t\treturn fmt.Errorf(\"cannot open db: %w\", err)\n\t}\n\n\t_, err = os.Getwd()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"cannot get current directory: %w\", err)\n\t}\n\n\t// Instantiate PG-backed services.\n\tauthService := jwt.NewAuthService([]byte(m.Config.SignKey), []byte(m.Config.VerifyKey))\n\tuserService := pg.NewUserService(m.DB)\n\tgroupService := pg.NewGroupService(m.DB)\n\thomeworkService := pg.NewHomeworkService(m.DB)\n\thwSubmissionService := pg.NewHWSubmissionService(m.DB)\n\tquizService := pg.NewQuizService(m.DB)\n\tquizSubmissionService := pg.NewQuizSubmissionService(m.DB)\n\tquestionService := pg.NewQuestionService(m.DB)\n\tresponseService := pg.NewResponseService(m.DB)\n\tattendanceService := pg.NewAttendanceService(m.DB)\n\tattSubmissionService := pg.NewAttSubmissionService(m.DB)\n\n\t// Copy configuration settings to the HTTP server.\n\tm.HTTPServer.Addr = m.Config.HTTP.Addr\n\tm.HTTPServer.Domain = m.Config.HTTP.Domain\n\n\t// Attach underlying services to the HTTP server.\n\tm.HTTPServer.AuthService = authService\n\tm.HTTPServer.UserService = userService\n\tm.HTTPServer.GroupService = groupService\n\tm.HTTPServer.HomeworkService = homeworkService\n\tm.HTTPServer.HWSubmissionService = hwSubmissionService\n\tm.HTTPServer.QuizService = quizService\n\tm.HTTPServer.QuizSubmissionService = quizSubmissionService\n\tm.HTTPServer.QuestionService = questionService\n\tm.HTTPServer.ResponseService = responseService\n\tm.HTTPServer.AttendanceService = attendanceService\n\tm.HTTPServer.AttSubmissionService = attSubmissionService\n\n\t// Start the HTTP server.\n\tif err := m.HTTPServer.Open(); err != nil {\n\t\treturn err\n\t}\n\n\tlog.Printf(\"running: url=%q dsn=%q\", m.HTTPServer.URL(), m.Config.DB.DSN)\n\n\treturn nil\n}", "func (d *commandSQLAll) Run() error {\n\tcreateQueries, indexes, err := defaultModelCache.getDbCreateSQL(d.al)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar all []string\n\tfor i, mi := range defaultModelCache.allOrdered() {\n\t\tqueries := []string{createQueries[i]}\n\t\tfor _, idx := range indexes[mi.table] {\n\t\t\tqueries = append(queries, idx.SQL)\n\t\t}\n\t\tsql := strings.Join(queries, \"\\n\")\n\t\tall = append(all, sql)\n\t}\n\tfmt.Println(strings.Join(all, \"\\n\\n\"))\n\n\treturn nil\n}", "func RunPgMigrations() error {\n\tcfg := config.Get()\n\tif cfg.PgMigrationsPath == \"\" {\n\t\treturn nil\n\t}\n\tif cfg.PgURL == \"\" {\n\t\treturn errors.New(\"No cfg.PgURL provided\")\n\t}\n\tm, err := migrate.New(\n\t\tcfg.PgMigrationsPath,\n\t\tcfg.PgURL,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Run() {\n\tdb.Setup()\n\tlistener, ch = gou.StartDaemon()\n}", "func Migrate() {\n\tlog.Info(\"Executing migrations...\")\n\tDb.AutoMigrate(&models.Repository{}, &models.Week{}, &models.Contributor{})\n}", "func migrateNew() {\n\tif len(flag.Args()) == 0 {\n\t\tlog.Fatalf(\"ERROR: Migration's name not specified\\n\")\n\t\treturn\n\t}\n\twd, _ := os.Getwd()\n\tname := path.Join(wd, \"migrations\", fmt.Sprintf(\"%d_%s.sql\", time.Now().Unix(), flag.Arg(0)))\n\tfile, err := os.Create(name)\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t\treturn\n\t}\n\tfmt.Fprintf(file, \"-- +migrate Up\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Up' is executed when this migration is applied\\n\\n\\n\")\n\tfmt.Fprintf(file, \"-- +migrate Down\\n\")\n\tfmt.Fprintf(file, \"-- SQL in section 'Down' is executed when this migration is rolled back\\n\\n\\n\")\n\terr = file.Close()\n\tif err != nil {\n\t\tlog.Printf(\"ERROR: %s\\n\", err)\n\t} else {\n\t\tlog.Printf(\"INFO: File %s has been successfully created\\n\", name)\n\t}\n}", "func main() {\n\tdsn := newPostgresConf().dsn()\n\tdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})\n\tif err != nil {\n\t\tlog.Fatalf(\"failed to connect database %v\", err)\n\t}\n\tif err := db.AutoMigrate(&Country{}); err != nil {\n\t\tlog.Fatalf(\"failed to make migration: %v\", err)\n\t}\n\taddFixtures(db)\n}", "func PerformMigrations(migrationsFolder string) {\n\tm, err := migrate.New(\n\t\tmigrationsFolder,\n\t\tos.Getenv(\"DATABASE_URL\"))\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tif err := m.Up(); err != nil && err != migrate.ErrNoChange {\n\t\tlog.Fatal(err)\n\t}\n\tfmt.Println(\"Database migrations completed. Database should be up to date\")\n}", "func Migrate(tx *gorm.DB) error {\n\treturn tx.Exec(`\n\tCREATE OR REPLACE FUNCTION notifyPipelineRunStarted() RETURNS TRIGGER AS $_$\n\tBEGIN\n\t\tIF NEW.finished_at IS NULL THEN\n\t\t\tPERFORM pg_notify('pipeline_run_started', NEW.id::text);\n\t\tEND IF;\n\t\tRETURN NEW;\n\tEND\n\t$_$ LANGUAGE 'plpgsql';\n\t`).Error\n}", "func InitialMigration() {\r\n\tdb, err = gorm.Open(\"sqlite3\", \"collegiateCS.db\")\r\n\tif err != nil {\r\n\t\tfmt.Println(err.Error())\r\n\t\tpanic(\"Failed to connect to db\")\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\t//db.AutoMigrate(&dbStats{})\r\n\t//db.AutoMigrate(&dbPlayer{})\r\n\t//db.AutoMigrate(&dbRoster{})\r\n\t//db.AutoMigrate(&dbGame{})\r\n\t//db.AutoMigrate(&dbSet{})\r\n}", "func (cli *CLI) Run(args []string) int {\n\tvar (\n\t\tport string\n\t\tversion bool\n\t\tinit bool\n\t)\n\n\tflags := flag.NewFlagSet(Name, flag.ContinueOnError)\n\tflags.SetOutput(cli.errStream)\n\tflags.Usage = func() {\n\t\tfmt.Fprint(cli.errStream, helpText)\n\t}\n\tflags.StringVar(&port, \"port\", DefaultPort, \"\")\n\tflags.StringVar(&port, \"P\", DefaultPort, \"\")\n\tflags.BoolVar(&init, \"init\", false, \"\")\n\tflags.BoolVar(&init, \"I\", false, \"\")\n\tflags.BoolVar(&version, \"version\", false, \"\")\n\tflags.BoolVar(&version, \"v\", false, \"\")\n\n\tif err := flags.Parse(args[1:]); err != nil {\n\t\treturn 1\n\t}\n\n\tif version {\n\t\tfmt.Fprintf(cli.errStream, \"%s version %s, build %s \\n\", Name, Version, GitCommit)\n\t\treturn 0\n\t}\n\n\tlog.Println(\"Connecting postgres ...\")\n\tdb, err := db.New()\n\tif err != nil {\n\t\tlog.Printf(\"postgres initialize error: %v\\n\", err)\n\t\treturn 2\n\t}\n\n\tif init {\n\t\tlog.Println(\"Creating postgres schema ...\")\n\t\tif err := db.CreateSchema(); err != nil {\n\t\t\tlog.Printf(\"postgres initialize error: %v\\n\", err)\n\t\t\treturn 2\n\t\t}\n\t}\n\n\thandler := web.New(&web.Option{\n\t\tPort: port,\n\t\tDB: db,\n\t})\n\tgo handler.Run()\n\n\tsigch := make(chan os.Signal, 1)\n\tsignal.Notify(sigch, syscall.SIGTERM, syscall.SIGINT)\n\ts := <-sigch\n\tif err := handler.Shutdown(s); err != nil {\n\t\tlog.Println(err)\n\t\treturn 3\n\t}\n\n\treturn 0\n}", "func (task *SetupSchemaTask) run() error {\n\n\tconfig := task.config\n\n\tdefer func() {\n\t\ttask.client.Close()\n\t}()\n\n\tlog.Printf(\"Starting schema setup, config=%+v\\n\", config)\n\n\tif config.Overwrite {\n\t\tdropAllTablesTypes(task.client)\n\t}\n\n\tif !config.DisableVersioning {\n\t\tlog.Printf(\"Setting up version tables\\n\")\n\t\tif err := task.client.CreateSchemaVersionTables(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(config.SchemaFilePath) > 0 {\n\t\tstmts, err := ParseCQLFile(config.SchemaFilePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlog.Println(\"----- Creating types and tables -----\")\n\t\tfor _, stmt := range stmts {\n\t\t\tlog.Println(rmspaceRegex.ReplaceAllString(stmt, \" \"))\n\t\t\tif err := task.client.Exec(stmt); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tlog.Println(\"----- Done -----\")\n\t}\n\n\tif !config.DisableVersioning {\n\t\tlog.Printf(\"Setting initial schema version to %v\\n\", config.InitialVersion)\n\t\terr := task.client.UpdateSchemaVersion(config.InitialVersion, config.InitialVersion)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlog.Printf(\"Updating schema update log\\n\")\n\t\terr = task.client.WriteSchemaUpdateLog(\"0\", config.InitialVersion, \"\", \"initial version\")\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tlog.Println(\"Schema setup complete\")\n\n\treturn nil\n}", "func (c *Subcommand) Run() bool {\n\tdump := dumper.New(c.db)\n\terr := dump.Dump(config.DatabaseSchemaPath)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\treturn err == nil\n}", "func (m *MigrationService) Migrate(args []string) error {\n\n\tfolder, _ := m.getCurrentFolder()\n\tluaRunner := luascript.NewLGoLua()\n\tluaRunner.RunLua(folder)\n\treturn nil\n}", "func InitialMigration() {\r\n\r\n\tdb, err = gorm.Open(\"sqlite3\", \"website.db\")\r\n\tif err != nil {\r\n\t\tpanic(\"Failed to connect!\")\r\n\t}\r\n\tdefer db.Close()\r\n\r\n\tdb.AutoMigrate(&Website{}, &WebsiteHealthStatusHistory{})\r\n}", "func run(cfg config.Config, flags config.Flags) {\n\tdb.InitDb(cfg)\n\tburger.InitRepository(burger.NewMongoRepository(db.DB))\n\n\tif flags.Migrate {\n\t\tmigration.CreateCollections()\n\t}\n\n\tapi := http.Server{\n\t\tAddr: cfg.Web.Host + \":\" + cfg.Web.Port,\n\t\tHandler: routes.CreateHandlers(),\n\t\tReadTimeout: cfg.Web.Timeout.Read * time.Second,\n\t\tWriteTimeout: cfg.Web.Timeout.Write * time.Second,\n\t}\n\n\tif err := api.ListenAndServe(); err != nil {\n\t\tconfig.Logger.Println(\"ERROR\", err)\n\t}\n}", "func Run() {\n\tif config.GetString(\"app.environment\") == \"localhost\" {\n\t\tcount := int64(0)\n\t\tif err := database.Conn().Model(&model.User{}).Count(&count).Error; err != nil {\n\t\t\tpanic(err)\n\t\t}\n\n\t\tif count <= 0 {\n\t\t\tgoyave.Logger.Println(\"Running seeders...\")\n\t\t\tUser()\n\t\t\tArticle()\n\t\t}\n\t}\n}", "func runAllMigrations(db *sql.DB) {\n\tLogInfo(\"RUNNING ALL MIGRATIONS\\n\")\n\n\tcreateMigrationsTable(db)\n\n\tfilenamePattern := fmt.Sprintf(\"./*.sql\")\n\tfiles, err := filepath.Glob(filenamePattern)\n\tif err != nil {\n\t\tLogErr(\"%s\\n\", err)\n\t}\n\n\tfor _, filePath := range files {\n\t\tfilename := filepath.Base(filePath)\n\n\t\tif checkIfMigrated(filename, db) {\n\t\t\tLogNotice(\"SKIPPING %s\\n\", filename)\n\t\t\tcontinue\n\t\t}\n\n\t\tsqlQuery, fileErr := ioutil.ReadFile(fmt.Sprintf(\"./%s\", filename))\n\t\tif fileErr != nil {\n\t\t\tLogErr(\"%s\\n\", fileErr)\n\t\t}\n\n\t\texecQuery(db, string(sqlQuery))\n\t\texecQuery(db, \"INSERT INTO _migrations (migration) VALUES($1)\", filename)\n\t\tLogSuccess(\"%s MIGRATED\\n\", filename)\n\t}\n\n}", "func (d *PostgresDbDropper) Run() {\n\trun(d)\n}", "func Initialize(ctx context.Context, migrationDir string, db Database, queries QueryAdapter) error {\n\t// make sure migrations can persist\n\t_, err := db.ExecContext(ctx, queries.CreateTableSQL())\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\t// Get the migration with the highest ID number\n\trow := db.QueryRowContext(ctx, queries.SelectLatestMigrationSQL())\n\tif err := row.Err(); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tlatest := 0\n\n\tif err := row.Scan(&latest); err != nil {\n\t\tif err != sql.ErrNoRows {\n\t\t\treturn errors.WithStack(err)\n\t\t}\n\t}\n\n\t// Load up the migrations and run starting from the last known run migration\n\tmigs := fromDir(migrationDir)\n\tfor _, migration := range migs[:latest] {\n\t\tfmt.Printf(\"Already ran migration: %d\\n\", migration.Order)\n\t}\n\n\tfor _, migration := range migs[latest:] {\n\t\tfmt.Printf(\"Running migration %d\\n\", migration.Order)\n\t\tif _, err := db.ExecContext(ctx, migration.Up); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := db.ExecContext(ctx, queries.InsertMigrationSQL(), migration.Order); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (base *DatabaseImplementation) ExecuteMigration(schema string, command string) error {\n\t_, err1 := base.DB.Exec(base.mq.SetSchemaSQL(schema))\n\tif err1 != nil {\n\t\treturn err1\n\t}\n\t_, err2 := base.DB.Exec(command)\n\treturn err2\n\n}", "func (m *Backup) Run(filename string) error {\n\treturn nil\n}", "func migrate() {\n\n}", "func (f *Facade) Run(app func(*Facade)) {\n\tf.conf.Parse()\n\tf.db = db.New()\n\tif err := f.db.Open(f.dbURI, f.dbName); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tstop := make(chan os.Signal, 1)\n\tsignal.Notify(stop, os.Interrupt)\n\tgo app(f)\n\t<-stop\n\tif f.shutdown != nil {\n\t\tf.shutdown()\n\t}\n\tif err := f.db.Close(); err != nil {\n\t\tlog.Fatal(\"Não foi possível fechar a conexão com o banco de dados:\", err)\n\t}\n}", "func (m *MigrationRunner) Up(ctx context.Context) error {\n\treturn m.perform(ctx, \"up\")\n}", "func (g *Gjango) Run() {\n\tcmd.Execute(g.RouteServices)\n}", "func (mu *Command) RunDown() error {\n\tpop.SetLogger(mu.Log)\n\tconn := pop.Connections[mu.connectionName]\n\tif conn == nil {\n\t\treturn ErrCouldNotFindConnection\n\t}\n\n\tmig, err := pop.NewMigrationBox(mu.migrations, conn)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif mu.steps == 0 {\n\t\tmu.steps = 1\n\t}\n\n\treturn mig.Down(mu.steps)\n}", "func Run() {\n\tsrc.ReadConfig(\"config.json\")\n\terr := src.InitDatabase(\"./\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\terr = src.ReminderInit(\"./\")\n\tif err != nil {\n\t\tfmt.Println(err)\n\t}\n\n\tsrc.Start()\n\n\t<-make(chan struct{})\n\tdefer src.RemindClient.Close()\n\tdefer src.DB.Client.Close()\n}", "func initialMigration() {\n\tdb, err := gorm.Open(\"sqlite3\", \"test.db\")\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"failed to connect database\")\n\t}\n\tdefer db.Close()\n\n\t// Migrate the schema\n\tdb.AutoMigrate(&User{})\n}", "func (m *Backup) Run(filename string) error {\n\tcmd := exec.Command(\n\t\tm.Exec,\n\t\t\"--all-databases\",\n\t\t\"--lock-all-tables\",\n\t\t\"--host=127.0.0.1\",\n\t\tfmt.Sprintf(`--result-file=%s`, filename),\n\t)\n\treturn cmd.Run()\n}", "func (d *commandSyncDb) Run() error {\n\tvar drops []string\n\tvar err error\n\tif d.force {\n\t\tdrops, err = defaultModelCache.getDbDropSQL(d.al)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tdb := d.al.DB\n\n\tif d.force && len(drops) > 0 {\n\t\tfor i, mi := range defaultModelCache.allOrdered() {\n\t\t\tquery := drops[i]\n\t\t\tif !d.noInfo {\n\t\t\t\tfmt.Printf(\"drop table `%s`\\n\", mi.table)\n\t\t\t}\n\t\t\t_, err := db.Exec(query)\n\t\t\tif d.verbose {\n\t\t\t\tfmt.Printf(\" %s\\n\\n\", query)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\t\t}\n\t}\n\n\tcreateQueries, indexes, err := defaultModelCache.getDbCreateSQL(d.al)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttables, err := d.al.DbBaser.GetTables(db)\n\tif err != nil {\n\t\tif d.rtOnError {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t}\n\n\tctx := context.Background()\n\tfor i, mi := range defaultModelCache.allOrdered() {\n\n\t\tif !isApplicableTableForDB(mi.addrField, d.al.Name) {\n\t\t\tfmt.Printf(\"table `%s` is not applicable to database '%s'\\n\", mi.table, d.al.Name)\n\t\t\tcontinue\n\t\t}\n\n\t\tif tables[mi.table] {\n\t\t\tif !d.noInfo {\n\t\t\t\tfmt.Printf(\"table `%s` already exists, skip\\n\", mi.table)\n\t\t\t}\n\n\t\t\tvar fields []*fieldInfo\n\t\t\tcolumns, err := d.al.DbBaser.GetColumns(ctx, db, mi.table)\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\n\t\t\tfor _, fi := range mi.fields.fieldsDB {\n\t\t\t\tif _, ok := columns[fi.column]; !ok {\n\t\t\t\t\tfields = append(fields, fi)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, fi := range fields {\n\t\t\t\tquery := getColumnAddQuery(d.al, fi)\n\n\t\t\t\tif !d.noInfo {\n\t\t\t\t\tfmt.Printf(\"add column `%s` for table `%s`\\n\", fi.fullName, mi.table)\n\t\t\t\t}\n\n\t\t\t\t_, err := db.Exec(query)\n\t\t\t\tif d.verbose {\n\t\t\t\t\tfmt.Printf(\" %s\\n\", query)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tif d.rtOnError {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, idx := range indexes[mi.table] {\n\t\t\t\tif !d.al.DbBaser.IndexExists(ctx, db, idx.Table, idx.Name) {\n\t\t\t\t\tif !d.noInfo {\n\t\t\t\t\t\tfmt.Printf(\"create index `%s` for table `%s`\\n\", idx.Name, idx.Table)\n\t\t\t\t\t}\n\n\t\t\t\t\tquery := idx.SQL\n\t\t\t\t\t_, err := db.Exec(query)\n\t\t\t\t\tif d.verbose {\n\t\t\t\t\t\tfmt.Printf(\" %s\\n\", query)\n\t\t\t\t\t}\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tif d.rtOnError {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif !d.noInfo {\n\t\t\tfmt.Printf(\"create table `%s` \\n\", mi.table)\n\t\t}\n\n\t\tqueries := []string{createQueries[i]}\n\t\tfor _, idx := range indexes[mi.table] {\n\t\t\tqueries = append(queries, idx.SQL)\n\t\t}\n\n\t\tfor _, query := range queries {\n\t\t\t_, err := db.Exec(query)\n\t\t\tif d.verbose {\n\t\t\t\tquery = \" \" + strings.Join(strings.Split(query, \"\\n\"), \"\\n \")\n\t\t\t\tfmt.Println(query)\n\t\t\t}\n\t\t\tif err != nil {\n\t\t\t\tif d.rtOnError {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tfmt.Printf(\" %s\\n\", err.Error())\n\t\t\t}\n\t\t}\n\t\tif d.verbose {\n\t\t\tfmt.Println(\"\")\n\t\t}\n\t}\n\n\treturn nil\n}", "func Run(version string, args []string) {\n\terr := NewApp(version, time.Now()).Run(args)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}", "func Run(db DB, a ...string) (oldVersion, newVersion int64, err error) {\n\treturn DefaultCollection.Run(db, a...)\n}", "func Run() {\n\tcmd.Execute()\n}", "func RunSchemaUpdateTool(args []string) {\n\tconfig := parseSchemaUpadaterConfig(args)\n\tif config == nil {\n\t\treturn\n\t}\n\tupdateTask, err := NewSchemaUpdateTask(config)\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t}\n\tfmt.Printf(\"Running with Config=%+v\\n\\n\", config)\n\tupdateTask.Run()\n}", "func Run() bool {\n\tflag.Parse()\n\treturn *database\n}", "func (app *App) Run() {\n\terr := app.database.DB().Ping()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tlog.Printf(\"Server version %s running on %s\\n\", app.Version, app.server.Addr)\n\tif err := app.server.ListenAndServe(); err != nil {\n\t\tlog.Println(err)\n\t}\n}", "func (b *Builder) Run(p *Project) error {\n\tvar err error\n\tb.restarter.Invoke(func(ctx context.Context) {\n\t\terr = b.work(ctx, p)\n\t})\n\n\treturn err\n}", "func NewMigrationRunner(db *Database, migrations ...Migration) (*MigrationRunner, error) {\n\tconn, closeConn, err := db.Conn(context.Background())\n\tif err != nil {\n\t\tlog.\n\t\t\tError().\n\t\t\tErr(err).\n\t\t\tMsg(\"failed to get conn for creating migrations table\")\n\t\treturn nil, err\n\t}\n\tdefer closeConn()\n\n\terr = sqlitex.ExecScript(conn, strings.TrimSpace(`\n\t\tCREATE TABLE IF NOT EXISTS migrations(\n\t\t\tname TEXT NOT NULL,\n\t\t\tPRIMARY KEY (name)\n\t\t);\n\t`))\n\tif err != nil {\n\t\tlog.\n\t\t\tError().\n\t\t\tErr(err).\n\t\t\tMsg(\"failed to create migrations table\")\n\t\treturn nil, err\n\t}\n\n\treturn &MigrationRunner{\n\t\tdb: db,\n\t\tmigrations: migrations,\n\t}, nil\n}", "func (s *Step) Run(ctx context.Context, _ *Project) (int, error) {\n\t// For now, just route output to stdout.\n\targs := parseArgs(s.Args)\n\tcmd := exec.CommandContext(ctx, s.Command, *args...)\n\tcmd.Stdout = os.Stdout\n\tcmd.Stderr = os.Stdout\n\n\terr := cmd.Run()\n\tif err != nil {\n\t\tlog.Fatalf(\"Build command failed: %s\\n\", err.Error())\n\t\treturn 0, err\n\t}\n\n\treturn 0, nil\n}", "func (app *App) Run() {\n\tthings, err := app.store.ThingsGetAll()\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(\"failed to get all things from database: %s\", err.Error())\n\t}\n\tlog.Infof(\"find all things in database: %+v\", things)\n}", "func (h *Harness) Migrate(migrationName string) {\n\th.t.Helper()\n\th.t.Logf(\"Running migrations (target: %s)\", migrationName)\n\t_, err := migrate.Up(context.Background(), h.dbURL, migrationName)\n\tif err != nil {\n\t\th.t.Fatalf(\"failed to run migration: %v\", err)\n\t}\n}", "func Run() error {\n\treturn command.Execute()\n}", "func Migrate() error {\n\n\toldVersion, newVersion, err := migrations.Run(database.DB, \"init\")\n\toldVersion, newVersion, err = migrations.Run(database.DB)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif newVersion != oldVersion {\n\t\tlog.Printf(\"migrated from version %d to %d\\n\", oldVersion, newVersion)\n\t}\n\t// else {\n\t// \tlog.Printf(\"version is %d\\n\", oldVersion)\n\t// }\n\treturn nil\n}", "func Run() error {\n\tif options.ACLFile != \"\" {\n\t\ttableacl.Register(\"simpleacl\", &simpleacl.Factory{})\n\t\terr := tableacl.Init(\n\t\t\toptions.ACLFile,\n\t\t\tfunc() {},\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"fail to initialize Table ACL: %v\", err)\n\t\t}\n\n\t\tfmt.Printf(\"JSON ACL file %s looks good\\n\", options.ACLFile)\n\t}\n\n\tif options.StaticAuthFile != \"\" {\n\t\tmysql.RegisterAuthServerStaticFromParams(options.StaticAuthFile, \"\", 0)\n\n\t\tfmt.Printf(\"Static auth file %s looks good\\n\", options.StaticAuthFile)\n\t}\n\n\treturn nil\n}", "func (c *DeployCommand) Run(args []string) int {\n\n\tvar variables, addr, log string\n\tvar err error\n\tvar job *nomad.Job\n\tvar canary int\n\tvar forceCount bool\n\n\tflags := c.Meta.FlagSet(\"deploy\", FlagSetVars)\n\tflags.Usage = func() { c.UI.Output(c.Help()) }\n\n\tflags.StringVar(&addr, \"address\", \"\", \"\")\n\tflags.IntVar(&canary, \"canary-auto-promote\", 0, \"\")\n\tflags.StringVar(&log, \"log-level\", \"INFO\", \"\")\n\tflags.StringVar(&variables, \"var-file\", \"\", \"\")\n\tflags.BoolVar(&forceCount, \"force-count\", false, \"\")\n\n\tif err = flags.Parse(args); err != nil {\n\t\treturn 1\n\t}\n\n\targs = flags.Args()\n\n\tif len(args) != 1 {\n\t\tc.UI.Error(c.Help())\n\t\treturn 1\n\t}\n\n\tlogging.SetLevel(log)\n\n\tjob, err = levant.RenderJob(args[0], variables, &c.Meta.flagVars)\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"[ERROR] levant/command: %v\", err))\n\t\treturn 1\n\t}\n\n\tif canary > 0 {\n\t\tif err = c.checkCanaryAutoPromote(job, canary); err != nil {\n\t\t\tc.UI.Error(fmt.Sprintf(\"[ERROR] levant/command: %v\", err))\n\t\t\treturn 1\n\t\t}\n\n\t\tc.UI.Info(fmt.Sprintf(\"[INFO] levant/command: running canary-auto-update of %vs\", canary))\n\t}\n\n\tclient, err := levant.NewNomadClient(addr)\n\tif err != nil {\n\t\tc.UI.Error(fmt.Sprintf(\"[ERROR] levant/command: %v\", err))\n\t\treturn 1\n\t}\n\n\tsuccess := client.Deploy(job, canary, forceCount)\n\tif !success {\n\t\tc.UI.Error(fmt.Sprintf(\"[ERROR] levant/command: deployment of job %s failed\", *job.Name))\n\t\treturn 1\n\t}\n\n\tc.UI.Info(fmt.Sprintf(\"[INFO] levant/command: deployment of job %s successful\", *job.Name))\n\n\treturn 0\n}", "func (c *MigrateCommand) Exec(ctx context.Context, req *proto.ExecRequest, rsp *proto.ExecResponse) error {\n\t// rsp.Error could be set to return an error instead\n\t// the function error would only be used for service level issues\n\n\tc.db.AutoMigrate(\n\t\tmodels.CustomObject{},\n\t\tmodels.CustomField{},\n\t)\n\n\trsp.Result = []byte(\"数据库模式构建完毕\")\n\n\treturn nil\n}", "func (fmd *FakeMysqlDaemon) RunMysqlUpgrade(ctx context.Context) error {\n\treturn nil\n}", "func ExecuteMigrator(config *config.Config, action *string, createConnector func(*config.Config) db.Connector, createLoader func(*config.Config) loader.Loader) int {\n\n\tswitch *action {\n\tcase PrintConfigAction:\n\t\tlog.Printf(\"Configuration file ==>\\n%v\\n\", config)\n\t\treturn 0\n\tcase ListDiskMigrationsAction:\n\t\tdiskMigrations := LoadDiskMigrations(config, createLoader)\n\t\tlog.Printf(\"List of disk migrations ==>\\n%v\", types.MigrationArrayString(diskMigrations))\n\t\treturn 0\n\tcase ListDBMigrationsAction:\n\t\tdbMigrations := LoadDBMigrations(config, createConnector)\n\t\tlog.Printf(\"List of db migrations ==> \\n%v\", types.MigrationDBArrayString(dbMigrations))\n\t\treturn 0\n\tcase ListDBTenantsAction:\n\t\tdbTenants := LoadDBTenants(config, createConnector)\n\t\tlog.Printf(\"List of db tenants ==> \\n%v\", types.TenantArrayString(dbTenants))\n\t\treturn 0\n\tcase ApplyAction:\n\t\tmigrationsApplied := ApplyMigrations(config, createConnector, createLoader)\n\t\tlog.Printf(\"List of migrations applied ==>\\n%v\", types.MigrationArrayString(migrationsApplied))\n\t\treturn 0\n\tdefault:\n\t\tlog.Printf(\"Unknown action to run %q. For usage please run migrator with -h flag.\", *action)\n\t\treturn 1\n\t}\n}", "func (m *SqlxMigrate) Migrate() error {\n\terr := m.createMigrationTable()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, migration := range m.migrations {\n\t\tvar found string\n\t\terr := m.db.Get(&found, \"SELECT id FROM migrations WHERE id=?\", migration.ID)\n\t\tswitch err {\n\t\tcase sql.ErrNoRows:\n\t\t\tlog.Printf(\"Running migration: %v\\n\", migration.ID)\n\t\t\t// we need to run the migration so we continue to code below\n\t\tcase nil:\n\t\t\tlog.Printf(\"Skipping migration: %v\\n\", migration.ID)\n\t\t\tcontinue\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"looking up migration by id: %w\", err)\n\t\t}\n\t\terr = m.runMigration(migration)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func doDatabaseMigrations(db *WowDB, env *Env, blizzard Blizzard) {\n\n\tif ! db.HasTable(&Race{}) {\n\t\tlog.Debug(\"Migrating race\")\n\t\tdb.AutoMigrate(&Race{})\n\t\terr := UpdateRacesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update races: %v\", err)\n\t\t}\n\t}\n\n\tif ! db.HasTable(&ToonClass{}) {\n\t\tlog.Println(\"Migrating classes\")\n\t\tdb.AutoMigrate(&ToonClass{})\n\t\terr := UpdateClassesFromBlizzard(env, blizzard)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Could not update classes: %v\", err)\n\t\t}\n\t}\n\n\tdb.AutoMigrate(&Stat{})\n\tdb.AutoMigrate(&Toon{})\n\n\tif ! db.HasTable(&ClassColor{}) {\n\t\tdb.AutoMigrate(&ClassColor{})\n\t\tdb.Model(&ClassColor{}).AddForeignKey(\"toon_class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\t\tvar tColor = ClassColor{ToonClassID: 1, Color: \"#C79C63\"}\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 2\n\t\ttColor.Color = \"#F58CBA\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 3\n\t\ttColor.Color = \"#ABD473\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 4\n\t\ttColor.Color = \"#FFF569\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 5\n\t\ttColor.Color = \"#F0EBE0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 6\n\t\ttColor.Color = \"#C41F3B\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 7\n\t\ttColor.Color = \"#0070DE\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 8\n\t\ttColor.Color = \"#69CCF0\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 9\n\t\ttColor.Color = \"#9482C9\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 10\n\t\ttColor.Color = \"#00FF96\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 11\n\t\ttColor.Color = \"#FF7D0A\"\n\t\tdb.Create(&tColor)\n\t\ttColor.ID = 0\n\t\ttColor.ToonClassID = 12\n\t\ttColor.Color = \"#A330C9\"\n\t\tdb.Create(&tColor)\n\t}\n\n\tdb.Model(&Toon{}).AddForeignKey(\"race_id\", \"races(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Toon{}).AddForeignKey(\"class_id\", \"toon_classes(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddForeignKey(\"toon_id\", \"toons(id)\", \"RESTRICT\", \"RESTRICT\")\n\tdb.Model(&Stat{}).AddUniqueIndex(\"idx_toon_id_create_date\", \"toon_id\", \"insert_date\")\n}", "func (c *Command) Run() ([]string, error) {\n\tflags := map[string]string{\"pkg\": TargetPackage}\n\tgen := meta.NewGenerator(\n\t\t\"genapp.Generate\",\n\t\t[]*codegen.ImportSpec{codegen.SimpleImport(\"github.com/goadesign/goa/goagen/gen_app\")},\n\t\tflags,\n\t)\n\treturn gen.Generate()\n}", "func Run(args []string) (err error) {\n\tcli.VersionFlag = &cli.BoolFlag{\n\t\tName: \"version\",\n\t\tAliases: []string{\"v\"},\n\t\tUsage: \"Shows current cli version\",\n\t}\n\n\tapp.EnableBashCompletion = true\n\terr = app.Run(args)\n\treturn\n}", "func runImport(cmd *cobra.Command, args []string) {\n\t// Read the file\n\tconfig, err := toml.LoadFile(tomlFile)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while reading TOML content: %s\\n\", err.Error())\n\t}\n\n\t// Convert the tree to an array of maps\n\tarrayMap, err := util.TomlTreeToMap(config, tomlItemKey)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while converting TOML to array: %s\\n\", err.Error())\n\t}\n\n\t// Get a database\n\tdb, err := database.New(dbFile, false)\n\tif err != nil {\n\t\tlog.Fatalf(\"Error while connecting to the database: %s\\n\", err.Error())\n\t}\n\n\t// Load the data into the database\n\tfor _, item := range arrayMap {\n\t\terr = db.InsertContribution(item)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"Error while loading data into the database: %s\\n\", err.Error())\n\t\t}\n\t}\n}" ]
[ "0.776084", "0.74381644", "0.725198", "0.7004417", "0.6877605", "0.6868932", "0.68141776", "0.6804757", "0.67822593", "0.6750024", "0.67428255", "0.6715561", "0.6693653", "0.6674957", "0.66706026", "0.6635396", "0.6610724", "0.6606928", "0.6503097", "0.6481701", "0.6459692", "0.64476395", "0.63338774", "0.63011867", "0.6238227", "0.62274945", "0.62128544", "0.61794823", "0.6172271", "0.6159827", "0.6076443", "0.60342", "0.6023087", "0.6012781", "0.6001649", "0.59896976", "0.5988778", "0.5986467", "0.59743375", "0.59708625", "0.5969245", "0.59587234", "0.595627", "0.5874702", "0.58688515", "0.58678716", "0.5837384", "0.5827454", "0.58272976", "0.58234566", "0.5815526", "0.57984364", "0.57820183", "0.57800955", "0.57616955", "0.57494897", "0.57313454", "0.5726918", "0.57102364", "0.57032233", "0.5689875", "0.56616014", "0.5651484", "0.56479293", "0.562698", "0.5616118", "0.5614701", "0.5598667", "0.5574535", "0.5570741", "0.5570283", "0.5557759", "0.5556435", "0.5547131", "0.5546121", "0.55432177", "0.5525585", "0.5521839", "0.55071896", "0.55063677", "0.5494503", "0.54907787", "0.5473", "0.5466036", "0.5463864", "0.54443663", "0.54415965", "0.54324305", "0.5426499", "0.5416785", "0.54125327", "0.54092747", "0.5408006", "0.54070854", "0.5402814", "0.54003763", "0.5399857", "0.5397621", "0.5391521", "0.5386659", "0.5373557" ]
0.0
-1
Dir returns a path to the testdata directory.
func Dir() string { srcdir := os.Getenv("TEST_SRCDIR") return filepath.Join( srcdir, os.Getenv("TEST_WORKSPACE"), "go", "tools", "gazelle", "testdata", ) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func getTestDataDir(t *testing.T) string {\n\treturn filepath.Join(test.GetTestDir(t), \"testdata\")\n}", "func (f *Factorio) DataDir() string {\n\treturn f.datadir\n}", "func getTestAppDir(t *testing.T) string {\n\treturn filepath.Join(getTestDataDir(t), \"app\")\n}", "func (c *Config) TestdataPath() string {\n\treturn filepath.Join(c.StoragePath(), \"testdata\")\n}", "func (mgr *Manager) DataDir() string {\n\treturn mgr.dataDir\n}", "func (s *Settings) DataDir() string {\n\t// List is in reverse order of priority - last one will be preferred.\n\tcandidates := []string{\n\t\t`/opt/factorio`,\n\t\t`~/.factorio`,\n\t\t`~/factorio`,\n\t\t`~/Library/Application Support/factorio`,\n\t}\n\tif e := os.Getenv(\"APPDATA\"); e != \"\" {\n\t\tcandidates = append(candidates, filepath.Join(e, \"Factorio\"))\n\t}\n\n\tif s.datadir != \"\" {\n\t\tcandidates = []string{s.datadir}\n\t}\n\n\tmatch := \"\"\n\tfor _, c := range candidates {\n\t\ts, err := homedir.Expand(c)\n\t\tif err != nil {\n\t\t\tglog.Infof(\"Unable to expand %s: %v\", c, err)\n\t\t\tcontinue\n\t\t}\n\t\tinfo, err := os.Stat(s)\n\t\tif os.IsNotExist(err) {\n\t\t\tglog.Infof(\"Path %s does not exists, skipped\", s)\n\t\t\tcontinue\n\t\t}\n\t\tif !info.IsDir() {\n\t\t\tglog.Infof(\"Path %s is a file, skipped\", s)\n\t\t\tcontinue\n\t\t}\n\t\tglog.Infof(\"Found factorio data dir: %s\", s)\n\t\tmatch = s\n\t}\n\tif match == \"\" {\n\t\tglog.Infof(\"No Factorio data dir found\")\n\t\treturn \"\"\n\t}\n\tglog.Infof(\"Using Factorio data dir: %s\", match)\n\treturn match\n}", "func GetDataDir() string {\n\tvar dataDirectory string\n\tdefaultDataHome := os.Getenv(\"XDG_DATA_HOME\")\n\n\tif len(defaultDataHome) == 0 {\n\t\tdataDirectory = path.Join(os.Getenv(\"HOME\"), \".local\", \"share\")\n\t} else {\n\t\tdataDirectory = path.Join(defaultDataHome)\n\t}\n\n\tdataDirectory = path.Join(dataDirectory, APP_NAME)\n\treturn dataDirectory\n}", "func TestFileDir() string {\n\t_, file, _, ok := runtime.Caller(1)\n\tif ok {\n\t\treturn filepath.Dir(file)\n\t}\n\tpanic(\"cannot determine test file directory\")\n}", "func DataDirPath(prefix string) string {\n\treturn path.Join(prefix, dataDirName)\n}", "func (s *Scope) dataDir() (string, error) {\n\tvar rfid syscall.GUID\n\n\tswitch s.Type {\n\tcase System:\n\t\trfid = rfidProgramData\n\n\tcase User:\n\t\trfid = rfidLocalAppData\n\n\tcase CustomHome:\n\t\treturn s.CustomHome, nil\n\n\tdefault:\n\t\treturn \"\", ErrInvalidScope\n\t}\n\n\tpath, err := getFolderPath(rfid)\n\tif err != nil {\n\t\treturn \"\", ErrRetrievingPath\n\t}\n\n\tif path, err = filepath.Abs(path); err != nil {\n\t\treturn \"\", ErrRetrievingPath\n\t}\n\n\treturn filepath.Join(path, s.Vendor, s.App), nil\n}", "func (env *LocalTestEnv) Directory() string {\n\treturn env.TmpPath\n}", "func DataDirPath(envContainer EnvContainer) (string, error) {\n\treturn xdgDirPath(envContainer, \"XDG_DATA_HOME\", filepath.Join(\".local\", \"share\"))\n}", "func (td *OsmTestData) GetTestDirPath() string {\n\tabsPath, err := filepath.Abs(strings.Join([]string{td.TestDirBase, td.TestDirName}, \"/\"))\n\tif err != nil {\n\t\ttd.T.Errorf(\"Error getting TestDirAbsPath: %v\", err)\n\t}\n\treturn absPath\n}", "func (s *Scope) dataDir() (string, error) {\n\tswitch s.Type {\n\tcase System:\n\t\treturn defaultDataDirs[0], nil\n\n\tcase User:\n\t\tpath := os.Getenv(\"XDG_DATA_HOME\")\n\t\tif path == \"\" {\n\t\t\treturn expandUser(\"~/.local/share\"), nil\n\t\t}\n\t\treturn path, nil\n\n\tcase CustomHome:\n\t\treturn filepath.Join(s.CustomHome, \".local/share\"), nil\n\t}\n\n\treturn \"\", ErrInvalidScope\n}", "func Dir() string {\n\treturn configDir\n}", "func (i *TiFlashInstance) DataDir() string {\n\tif err := i.checkIncorrectDataDir(); err != nil {\n\t\tlog.Errorf(err.Error())\n\t}\n\tdataDir := reflect.ValueOf(i.InstanceSpec).FieldByName(\"DataDir\")\n\tif !dataDir.IsValid() {\n\t\treturn \"\"\n\t}\n\tvar dirs []string\n\tfor _, dir := range strings.Split(dataDir.String(), \",\") {\n\t\tif dir == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tif !strings.HasPrefix(dir, \"/\") {\n\t\t\tdirs = append(dirs, filepath.Join(i.DeployDir(), dir))\n\t\t} else {\n\t\t\tdirs = append(dirs, dir)\n\t\t}\n\t}\n\treturn strings.Join(dirs, \",\")\n}", "func TstAppDataDir(goos, appName string, roaming bool) string {\n\treturn appDataDir(goos, appName, roaming)\n}", "func (p *param) Dir() string {\n\treturn os.Getenv(\"HOME\") + \"/.config/teonet/teol0/\"\n}", "func AppDataDir() (string, error) {\n\tvar home string\n\tif runtime.GOOS == \"windows\" {\n\t\thome := os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t\tif home == \"\" {\n\t\t\thome = os.Getenv(\"USERPROFILE\")\n\t\t}\n\t} else {\n\t\thome = os.Getenv(\"HOME\")\n\t}\n\n\tif home == \"\" {\n\t\thome = os.Getenv(\"APPDATA\")\n\t\tif home == \"\" {\n\t\t\treturn \"\", sterr.New(\"unable to optain AppData directory path\")\n\t\t}\n\t} else {\n\t\thome = path.Join(home, \"AppData\", \"Roaming\")\n\t}\n\n\treturn home, nil\n}", "func (c *ConfHolder) Dir() string {\n\treturn os.Getenv(\"HOME\") + \"/.config/teonet/teoroom/\"\n}", "func initDataDir(dir string) string {\n\tif dir == \"\" {\n\t\tlogger.Error(\"data directory is nil\")\n\t}\n\n\thome := file.UserHome()\n\tif home == \"\" {\n\t\tlogger.Warning(\"Failed to get home directory\")\n\t\tdir = filepath.Join(\"./\", dir)\n\t} else {\n\t\tdir = filepath.Join(home, dir)\n\t}\n\n\tif err := os.MkdirAll(dir, os.FileMode(0700)); err != nil {\n\t\tlogger.Error(\"Failed to create directory %s: %v\", dir, err)\n\t}\n\treturn dir\n}", "func DataDirs() []string {\n\treturn []string{}\n}", "func Dir() string {\n\tdir, _ := os.Getwd()\n\treturn dir\n}", "func TstAppDataDir(goos, appName string, roaming bool) string {\n\treturn appDir(goos, appName, roaming)\n}", "func TestDir(dirs ...string) (string, error) {\n\tpath := filepath.Join(SiaTestingDir, filepath.Join(dirs...))\n\terr := os.RemoveAll(path)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn path, nil\n}", "func Dir() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\n\treturn filepath.Dir(filename)\n}", "func (d *Dir) DataPath() string {\n\treturn filepath.Clean(d.HomePath + \"/\" + FOSWIKI_SUBDIRS[\"DATA\"])\n}", "func (k *Kluster) Dir() string {\n\treturn filepath.Dir(k.path)\n}", "func (g *GlobalContext) Dir() string {\n\tpwd, err := os.Getwd()\n\n\tif err != nil {\n\t\tg.LogError(err)\n\t}\n\n\treturn pwd + \"/.secrets\"\n}", "func FindTestdataFolder(t *testing.T) string {\n\tpath := \"testdata\"\n\n\tfor i := 0; i < 3; i++ {\n\t\texists, err := fs.PathExists(path)\n\t\tcheckError(t, err)\n\t\tif exists {\n\t\t\treturn path\n\t\t}\n\t\tpath = filepath.Join(\"..\", path)\n\t}\n\n\tcheckError(t, errors.New(\"testdata folder not found\"))\n\treturn \"\"\n}", "func TestTestdataDirOnly(t *testing.T) {\n\tout := new(bytes.Buffer)\n\terr := listPath(out, \"testdata\", true, true, true)\n\tif err != nil {\n\t\tt.Errorf(\"unexpected error:%s\", err)\n\t}\n\tresult := out.String()\n\tif result != resultTestdataDirOnly {\n\t\tt.Errorf(\"bad result\\nexpected:\\n%v\\ngot:\\n%v\\n\", result, resultTestdataDirOnly)\n\t}\n}", "func AppDataDir(category DataCategory) (string, error) {\n\tprogName := filepath.Base(os.Args[0])\n\tprogExt := filepath.Ext(progName)\n\tprogName = progName[:len(progName)-len(progExt)]\n\n\tappDir, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\t// Sometimes defaults to a specific category. Adjust to root, then add\n\t// desired category.\n\tif filepath.Base(appDir) != \"AppData\" {\n\t\tappDir = filepath.Dir(appDir)\n\t}\n\tappDir = filepath.Join(appDir, category.String(), progName)\n\tos.MkdirAll(appDir, os.ModeDir)\n\treturn appDir, nil\n}", "func TestDataPath(elem ...string) string {\n\tps := []string{\n\t\tprojectRootPath(),\n\t\t\"_testdata\",\n\t}\n\tps = append(ps, elem...)\n\treturn filepath.Join(ps...)\n}", "func UserDataDir() string {\n\tdir := os.Getenv(\"USER_DATA_DIR\")\n\tif dir == \"\" {\n\t\treturn ExecDir\n\t}\n\n\treturn dir\n}", "func (s *Scope) configDir() (string, error) {\n\tp, err := s.dataDir()\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn filepath.Join(p, \"Config\"), nil\n}", "func (t *Tmpl) Dir() string {\n\treturn t.dir\n}", "func WorkDir() string { return workDir }", "func testDir(name string) string {\n\tdir := build.TempDir(name, filepath.Join(\"filesystem\"))\n\tif err := os.MkdirAll(dir, persist.DefaultDiskPermissionsTest); err != nil {\n\t\tpanic(err)\n\t}\n\treturn dir\n}", "func Dir() string {\n\tif ForceDir != \"\" {\n\t\treturn ForceDir\n\t}\n\tdir := os.Getenv(\"XDG_DATA_HOME\")\n\tif dir != \"\" {\n\t\treturn dir\n\t}\n\tusr, _ := user.Current()\n\tif usr != nil {\n\t\treturn filepath.Join(usr.HomeDir, \".local\", \"share\")\n\t}\n\treturn \"\"\n}", "func DataHomeDirectory() (dir string, e error) {\r\n\tdir, e = ConfigHomeDirectory()\r\n\tif s, ok := os.LookupEnv(\"LOCALAPPDATA\"); ok {\r\n\t\tdir, e = s, nil\r\n\t}\r\n\treturn\r\n}", "func GetTestAssetsDir() string {\n\n\twd := testutil.RunOnRootFolder()\n\twd = wd + \"/test_assets\"\n\n\t_, err := os.Stat(wd)\n\tif os.IsNotExist(err) {\n\t\tio.CheckErr(err)\n\t}\n\n\treturn wd\n}", "func AppDataDir(appName string, roaming bool) string {\n\treturn appDataDir(runtime.GOOS, appName, roaming)\n}", "func Dir() (string, error) {\n\tc, err := os.UserConfigDir()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn filepath.Join(c, appName), nil\n}", "func TempDir(t *testing.T) string {\n\tname, err := ioutil.TempDir(\"\", \"cuttlefishTestDir\")\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn name\n}", "func InitDataDir(dir string) (string, error) {\n\tdir, err := buildDataDir(dir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// check if dir already exist\n\tst, err := os.Stat(dir)\n\tif !os.IsNotExist(err) {\n\t\tif !st.IsDir() {\n\t\t\treturn \"\", fmt.Errorf(\"%s is not a directory\", dir)\n\t\t}\n\t\t// dir already exist\n\t\treturn dir, nil\n\t}\n\n\tif err := os.MkdirAll(dir, os.FileMode(0700)); err != nil {\n\t\tlogger.Errorf(\"Failed to create directory %s: %v\", dir, err)\n\t\treturn \"\", err\n\t}\n\n\tlogger.Infof(\"Created data directory %s\", dir)\n\treturn dir, nil\n}", "func Dir() string {\n\t// At first, Check the $HOME environment variable\n\tusrHome := os.Getenv(\"HOME\")\n\tif usrHome != \"\" {\n\t\treturn filepath.FromSlash(usrHome)\n\t}\n\n\t// TODO(zchee): In Windows OS, which of $HOME and these checks has priority?\n\t// Respect the USERPROFILE environment variable because Go stdlib uses it for default GOPATH in the \"go/build\" package.\n\tif usrHome = os.Getenv(\"USERPROFILE\"); usrHome == \"\" {\n\t\tusrHome = os.Getenv(\"HOMEDRIVE\") + os.Getenv(\"HOMEPATH\")\n\t}\n\n\treturn filepath.FromSlash(usrHome)\n}", "func TestBasedir() string {\n\treturn requireEnv(testBasedir)\n}", "func fileDir() string {\n\n\t_, filename, _, _ := runtime.Caller(0)\n\treturn path.Dir(filename)\n}", "func defaultDataDir() string {\n\t// Try to place the data folder in the user's home dir\n\thome := homeDir()\n\tif home != \"\" {\n\t\tif runtime.GOOS == \"darwin\" {\n\t\t\treturn filepath.Join(home, \"Library\", \"ft_ledger\")\n\t\t} else if runtime.GOOS == \"windows\" {\n\t\t\treturn filepath.Join(home, \"AppData\", \"Roaming\", \"ft_ledger\")\n\t\t} else {\n\t\t\treturn filepath.Join(home, \".ft_ledger\")\n\t\t}\n\t}\n\t// As we cannot guess a stable location, return empty and handle later\n\treturn \"\"\n}", "func baseDir() (string, error) {\n\tdirPath := filepath.Join(os.TempDir(), \"pod\", \"rpctest\")\n\te := os.MkdirAll(dirPath, 0755)\n\treturn dirPath, e\n}", "func DataDir(path string) Option {\n\tif s, err := os.Stat(path); err == nil && s.IsDir() {\n\t\treturn func(args *Options) {\n\t\t\targs.DataDir = path\n\t\t}\n\t}\n\n\treturn func(args *Options) {\n\t}\n}", "func Dir(path string) string {\n\treturn std.Dir(path)\n}", "func getDatafilePath() string {\n\thome, _ := homedir.Dir()\n\treturn fmt.Sprintf(\"%s/todo.json\", home)\n}", "func InitDir(base string) {\n\tif Dir == \"\" {\n\t\tvar err error\n\t\tDir, err = ioutil.TempDir(base, \"redis_test_\")\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t}\n}", "func ConfigDir() string {\n\treturn configDir\n}", "func MakeDataDir(ctx *cli.Context) string {\n\tif path := ctx.GlobalString(DataDirFlag.Name); path != \"\" {\n\t\t// TODO: choose a different location outside of the regular datadir.\n\t\tif ctx.GlobalBool(TestNetFlag.Name) {\n\t\t\treturn filepath.Join(path, \"testnet\")\n\t\t}\n\t\treturn path\n\t}\n\tFatalf(\"Cannot determine default data directory, please set manually (--datadir)\")\n\treturn \"\"\n}", "func GetDbDir() string {\n\treturn getEnv(\"ENM_DB_DIRECTORY\", \"/data/database\")\n}", "func (fs FileStorageSettings) Dir() string {\n\tpath := \"\"\n\tif fs.Type == FileStorageTypeLocal {\n\t\tpath = fs.Local.Path\n\t} else if fs.Type == FileStorageTypeS3 {\n\t\tpath = fs.S3.Key\n\t}\n\treturn filepath.Dir(path)\n}", "func (s *Scope) logDir() (string, error) {\n\tp, err := s.dataDir()\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn filepath.Join(p, \"Logs\"), nil\n}", "func k8sDataDirName() string {\n\treturn time.Now().Format(\"..2006_01_02_15_04_05.000000000\")\n}", "func UserConfigDir() (string, error)", "func GetDataPath() string {\n\tif env := os.Getenv(\"DATA_PATH\"); len(env) != 0 {\n\t\treturn env\n\t}\n\n\tif env := os.Getenv(\"GOPATH\"); env != \"\" {\n\t\tgopaths := strings.Split(env, \":\")\n\t\tfor _, gp := range gopaths {\n\t\t\tcheck := path.Join(gp, \"src\", DataPath)\n\t\t\tif _, err := os.Stat(check); err == nil {\n\t\t\t\treturn check\n\t\t\t}\n\t\t}\n\t}\n\n\tglog.Fatalf(\"Cannot find data path for %q\\n\", DataPath)\n\treturn \"\"\n}", "func TempDir() (string, error) {\n\tdir, err := ioutil.TempDir(\"\", \"git-get-repo-\")\n\tif err != nil {\n\t\treturn \"\", errors.Wrap(err, \"failed creating test repo directory\")\n\t}\n\n\treturn dir, nil\n}", "func TempDir() string", "func (s *Signatures) Dir() (dir string) {\n\tsignatures.Lock()\n\tdefer signatures.Unlock()\n\n\treturn signatures.dir\n}", "func (f *Factorio) ModsDir() string {\n\treturn filepath.Join(f.DataDir(), ModsDir)\n}", "func GetTestDataFilePath(testFile string) (string, error) {\n\ttestdataPath, err := filepath.Abs(\"../../testdata\")\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn filepath.Join(testdataPath, testFile), nil\n}", "func (s *Scope) cacheDir() (string, error) {\n\tp, err := s.dataDir()\n\tif err != nil {\n\t\treturn p, err\n\t}\n\n\treturn filepath.Join(p, \"Cache\"), nil\n}", "func saveTestDir() {\n\tnewName := fmt.Sprintf(\"%s-%d\", monkeyTestWorkingDir, rand.Uint64())\n\tplog.Infof(\"going to save the monkey test data dir to %s\", newName)\n\tif err := os.Rename(monkeyTestWorkingDir, newName); err != nil {\n\t\tpanic(err)\n\t}\n}", "func (s *Server) data_path() (path string) {\n\tpaths := STRINGS.Split(OS.Getenv(\"GOPATH\"), \";\")\n\tfor k := range paths {\n\t\tpath = paths[k] + \"/src/FKGoServer/FKGRpc_GeoOP/Res/GeoIP2-City.mmdb\"\n\t\t_, err := OS.Lstat(path)\n\t\tif err == nil {\n\t\t\treturn path\n\t\t}\n\t}\n\treturn\n}", "func DefaultDataDir() string {\n\t// Try to place the data folder in the user's home dir\n\thome := homeDir()\n\tif home != \"\" {\n\t\tif runtime.GOOS == \"darwin\" {\n\t\t\treturn filepath.Join(home, \"Library\", \"Linkchain\")\n\t\t} else if runtime.GOOS == \"windows\" {\n\t\t\treturn filepath.Join(home, \"AppData\", \"Roaming\", \"Linkchain\")\n\t\t} else {\n\t\t\treturn filepath.Join(home, \".linkchain\")\n\t\t}\n\t}\n\t// As we cannot guess a stable location, return empty and handle later\n\treturn \"\"\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func SelfDir() string {\n\treturn filepath.Dir(SelfPath())\n}", "func (m NoopMounter) Dir() string {\n\treturn \"\"\n}", "func mockConfigDir() (string, error) {\n\treturn \"/tmp/CONFIG/datamaps/\", nil\n}", "func (c *Config) DataPath() string {\n\treturn filepath.Join(c.Dir, \"data-default.csv\")\n}", "func GetDir() string {\n\t_, filename, _, _ := runtime.Caller(1)\n\treturn path.Dir(filename)\n}", "func DefaultDataDir() string {\n\t// Try to place the data folder in the user's home dir\n\thome := homeDir()\n\tif home != \"\" {\n\t\tswitch runtime.GOOS {\n\t\tcase \"darwin\":\n\t\t\treturn filepath.Join(home, \"Library\", \"Lachesis\")\n\t\tcase \"windows\":\n\t\t\t// We used to put everything in %HOME%\\AppData\\Roaming, but this caused\n\t\t\t// problems with non-typical setups. If this fallback location exists and\n\t\t\t// is non-empty, use it, otherwise DTRT and check %LOCALAPPDATA%.\n\t\t\tfallback := filepath.Join(home, \"AppData\", \"Roaming\", \"Lachesis\")\n\t\t\tappdata := windowsAppData()\n\t\t\tif appdata == \"\" || isNonEmptyDir(fallback) {\n\t\t\t\treturn fallback\n\t\t\t}\n\t\t\treturn filepath.Join(appdata, \"Lachesis\")\n\t\tdefault:\n\t\t\treturn filepath.Join(home, \".lachesis\")\n\t\t}\n\t}\n\t// As we cannot guess a stable location, return empty and handle later\n\treturn \"\"\n}", "func ConfigDir() string {\n\treturn filepath.Join(userSettingsDir, \"kopia\")\n}", "func (h testHelper) makeTestDir() (path string) {\n\tpath, err := ioutil.TempDir(\"\", \"TestDir\")\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t\n\t// Now populate it with interesting files.\n\t// - zero byte file\n\th.writeFile(\"0_byte_file\", path, makeRisingIntsSlice(0))\n\t\n\t// - one byte file, zero value\n\th.writeFile(\"1_byte_file_0_value\", path,\n\t\tmakeConstantSlice(1, 0))\n\n\t// - one byte file, 128 value\n\th.writeFile(\"1_byte_file_128_value\", path,\n\t\tmakeConstantSlice(1, 128))\n\n\t// - ascending ints file, 10 bytes\n\th.writeFile(\"10_byte_file_rising_ints\", path,\n\t\tmakeRisingIntsSlice(10))\n\n\t// - ascending ints file, 100 bytes\n\th.writeFile(\"100_byte_file_rising_ints\", path,\n\t\tmakeRisingIntsSlice(100))\n\n\t// - all zeros, 100 byte file\n\th.writeFile(\"100_byte_file_0_value\", path,\n\t\tmakeConstantSlice(100, 0))\n\t\n\t// - all 255, 100 byte file\n\th.writeFile(\"100_byte_file_255_value\", path,\n\t\tmakeConstantSlice(100, 255))\n\n\t// - Hello World! file\n\th.writeFile(\"hello_world_file_plain\", path,\n\t\tmakeStringSlice(\"Hello World!\"))\n\n\t// - Hello World!\\n file\n\th.writeFile(\"hello_world_file_nl\", path,\n\t\tmakeStringSlice(\"Hello World!\\n\"))\n\n\t// - Hello World!\\r\\n file\n\th.writeFile(\"hello_world_file_crnl\", path,\n\t\tmakeStringSlice(\"Hello World!\\r\\n\"))\n\n\treturn path\n}", "func PuppetLabsDir() (string, error) {\n\treturn \"/etc/puppetlabs\", nil\n}", "func Dir(path string) string {\n\td := filepath.Dir(path)\n\tif d == \".\" {\n\t\treturn \"\"\n\t}\n\treturn d\n}", "func TestDir() (string, func()) {\n\tdir, err := ioutil.TempDir(\"\", \"elvishtest.\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tdir, err = filepath.EvalSymlinks(dir)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn dir, func() {\n\t\terr := os.RemoveAll(dir)\n\t\tif err != nil {\n\t\t\tfmt.Fprintf(os.Stderr, \"failed to remove temp dir %s: %v\\n\", dir, err)\n\t\t}\n\t}\n}", "func (at AssetType) DirPath() string {\n\tinvPath := env.InvestigationsPath()\n\tswitch at {\n\tcase AssetTypeGCPAnalysis:\n\t\treturn filepath.Join(invPath, \"gcp-analyses\")\n\tcase AssetTypeIBMAnalysis:\n\t\treturn filepath.Join(invPath, \"ibm-analyses\")\n\tcase AssetTypeAudio:\n\t\treturn filepath.Join(invPath, \"audio\")\n\tcase AssetTypeRecognition:\n\t\treturn filepath.Join(invPath, \"recognitions\")\n\tcase AssetTypeTranscript:\n\t\treturn filepath.Join(invPath, \"transcripts\")\n\tcase AssetTypeVideo:\n\t\treturn filepath.Join(invPath, \"videos\")\n\tdefault:\n\t\treturn \"\"\n\t}\n}", "func Dir(file string) string {\n\treturn path.Dir(file)\n}", "func (t TestRepo) Workdir() string {\n\treturn filepath.Clean(t.repo.Workdir())\n}", "func (env *LocalTestEnv) LogDirectory() string {\n\treturn path.Join(env.TmpPath, \"logs\")\n}", "func GetDefaultDataDir(env string) string {\n\tif env == \"windows\" {\n\t\treturn filepath.Join(os.Getenv(\"APPDATA\"), \"GoCryptoTrader\")\n\t}\n\n\tusr, err := user.Current()\n\tif err == nil {\n\t\treturn filepath.Join(usr.HomeDir, \".gocryptotrader\")\n\t}\n\n\tdir, err := os.UserHomeDir()\n\tif err != nil {\n\t\tlog.Warnln(log.Global, \"Environment variable unset, defaulting to current directory\")\n\t\tdir = \".\"\n\t}\n\treturn filepath.Join(dir, \".gocryptotrader\")\n}", "func EnsureDataDir() (string, error) {\n\thome := os.Getenv(\"HOME\")\n\tif home == \"\" {\n\t\treturn \"\", ErrEmptyHOME\n\t}\n\thome = strings.TrimRight(home, \"/\")\n\tddir := home + \"/.elvish\"\n\treturn ddir, os.MkdirAll(ddir, 0700)\n}", "func (k *Kluster) StateDir() string {\n\treturn filepath.Join(k.Dir(), StateDirname)\n}", "func SetDataDir(s string) func(*Manager) error {\n\treturn func(c *Manager) error {\n\t\tc.datadir = s\n\t\treturn nil\n\t}\n}", "func (c AppConfig) CorpusDataDir() string {\n\treturn c.ProjectHome + \"/data/corpus\"\n}", "func dir(name string) string {\n\treturn filepath.Dir(filepath.Base(name))\n}", "func AppDir() string {\r\n\treturn filepath.Base(AppPath())\r\n}", "func baseProcDataDir() string {\n\treturn path.Join(dataDir, \"proc\")\n}", "func (t *Application) stateDir() (dir string, closer func() error, err error) {\n\tif *t.StateDir == \"\" {\n\t\treturn tempStateDir()\n\t}\n\treturn *t.StateDir, nil, nil\n}", "func NamespaceDirPath(prefix string, namespace ident.ID) string {\n\treturn path.Join(prefix, dataDirName, namespace.String())\n}", "func (s *BlockStorage) Dir() string {\n\treturn s.dir\n}", "func getDir(dirPath string) (*fs.Dir, error) {\n\tcmd := mybase.NewCommand(\"dumpertest\", \"\", \"\", nil)\n\tutil.AddGlobalOptions(cmd)\n\tworkspace.AddCommandOptions(cmd)\n\tcmd.AddArg(\"environment\", \"production\", false)\n\tcfg := &mybase.Config{\n\t\tCLI: &mybase.CommandLine{Command: cmd},\n\t}\n\treturn fs.ParseDir(dirPath, cfg)\n}" ]
[ "0.7761522", "0.7096223", "0.7052782", "0.70178235", "0.7012401", "0.699047", "0.6935886", "0.68590796", "0.6690725", "0.6661966", "0.6641725", "0.6637018", "0.6619594", "0.65434295", "0.65197843", "0.65072536", "0.6474937", "0.6426408", "0.640254", "0.6325526", "0.6311669", "0.6303682", "0.62988746", "0.6283979", "0.62523824", "0.6252061", "0.623628", "0.62259436", "0.6201903", "0.6201609", "0.61557406", "0.60943466", "0.6054582", "0.6052795", "0.6050991", "0.6044671", "0.6041933", "0.60255146", "0.6010846", "0.6009718", "0.60086113", "0.60074323", "0.6003748", "0.59940356", "0.5988361", "0.5987564", "0.59825015", "0.598192", "0.5966464", "0.5961824", "0.59462786", "0.5940381", "0.58982325", "0.5893732", "0.58714753", "0.5859969", "0.5854753", "0.58422065", "0.5841194", "0.5824779", "0.5806584", "0.5804746", "0.5793857", "0.5789659", "0.57879496", "0.5783261", "0.5756075", "0.5754737", "0.575169", "0.57466096", "0.5745274", "0.574458", "0.574458", "0.574458", "0.5732437", "0.5729465", "0.57246345", "0.5723991", "0.5719438", "0.56986296", "0.56965715", "0.56903553", "0.5673193", "0.56662154", "0.5656284", "0.56434035", "0.56390685", "0.56370974", "0.56297296", "0.5621599", "0.5607739", "0.5602966", "0.55923414", "0.55803907", "0.55631256", "0.5555363", "0.5552613", "0.5549273", "0.5543839", "0.55333906" ]
0.80407417
0
Create and retrieve google cloud storage client
func (gcs *GcsClient) CreateClient() error { ctx := context.Background() client, err := storage.NewClient(ctx) if err != nil { return fmt.Errorf("unable create client %s", err) } gcs.setContext(ctx) gcs.setClient(*client) return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func newGoogleStorageClient(config stow.Config) (*storage.Service, error) {\n\tjson, _ := config.Config(ConfigJSON)\n\tvar httpClient *http.Client\n\tscopes := []string{storage.DevstorageReadWriteScope}\n\tif s, ok := config.Config(ConfigScopes); ok && s != \"\" {\n\t\tscopes = strings.Split(s, \",\")\n\t}\n\tif json != \"\" {\n\t\tjwtConf, err := google.JWTConfigFromJSON([]byte(json), scopes...)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = jwtConf.Client(context.Background())\n\n\t} else {\n\t\tcreds, err := google.FindDefaultCredentials(context.Background(), strings.Join(scopes, \",\"))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thttpClient = oauth2.NewClient(context.Background(), creds.TokenSource)\n\t}\n\tservice, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn service, nil\n}", "func newGoogleStorageStore(config *GoogleStorageStoreConfig) (*googleStorageStore, error) {\n\tif config.Bucket == \"\" {\n\t\treturn nil, errors.New(\"bucket required\")\n\t}\n\n\tvar opts []option.ClientOption\n\tvar noAuth bool\n\tcredsPath := getGoogleCredsPath()\n\tif credsPath == \"\" {\n\t\tnoAuth = true\n\t\topts = append(opts, option.WithoutAuthentication())\n\t} else {\n\t\topts = append(opts, option.WithCredentialsFile(credsPath), option.WithScopes(storage.ScopeFullControl))\n\t}\n\n\tvar httpTransport http.Transport\n\tvar err error\n\tctx := context.WithValue(context.Background(), oauth2.HTTPClient, &http.Client{Transport: &httpTransport})\n\tgcpTransport, err := gcphttp.NewTransport(ctx, &httpTransport, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient := &http.Client{Transport: gcpTransport}\n\tclientOpt := option.WithHTTPClient(httpClient)\n\tclient, err := storage.NewClient(context.Background(), clientOpt)\n\tif err != nil {\n\t\thttpTransport.CloseIdleConnections()\n\t\tif noAuth {\n\t\t\treturn nil, errors.Wrap(err, 0)\n\t\t}\n\t\thttpClient.Transport, err = gcphttp.NewTransport(ctx, &httpTransport, option.WithoutAuthentication())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclient, err = storage.NewClient(context.Background(), clientOpt)\n\t\tif err != nil {\n\t\t\thttpTransport.CloseIdleConnections()\n\t\t\treturn nil, errors.Wrap(err, 0)\n\t\t}\n\t}\n\n\treturn &googleStorageStore{\n\t\tclient: client,\n\t\tbucket: client.Bucket(config.Bucket),\n\t\thttpTransport: &httpTransport,\n\t}, nil\n}", "func newClient() (*storage.Client, error) {\n\tctx := context.Background()\n\n\tbyteKey, err := gcloud.GetDecodedKey()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get gcp key, err: %w\", err)\n\t}\n\tclient, err := storage.NewClient(ctx, option.WithCredentialsJSON(byteKey))\n\tif err != nil {\n\t\tlog.Println(\"failed to login with GCP_KEY, trying with default application credentials...\")\n\t\tclient, err = storage.NewClient(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open Google Cloud Storage client: %w\", err)\n\t\t}\n\t}\n\n\treturn client, nil\n}", "func newHTTPStorageClient(ctx context.Context, opts ...storageOption) (storageClient, error) {\n\ts := initSettings(opts...)\n\to := s.clientOption\n\n\tvar creds *google.Credentials\n\t// In general, it is recommended to use raw.NewService instead of htransport.NewClient\n\t// since raw.NewService configures the correct default endpoints when initializing the\n\t// internal http client. However, in our case, \"NewRangeReader\" in reader.go needs to\n\t// access the http client directly to make requests, so we create the client manually\n\t// here so it can be re-used by both reader.go and raw.NewService. This means we need to\n\t// manually configure the default endpoint options on the http client. Furthermore, we\n\t// need to account for STORAGE_EMULATOR_HOST override when setting the default endpoints.\n\tif host := os.Getenv(\"STORAGE_EMULATOR_HOST\"); host == \"\" {\n\t\t// Prepend default options to avoid overriding options passed by the user.\n\t\to = append([]option.ClientOption{option.WithScopes(ScopeFullControl, \"https://www.googleapis.com/auth/cloud-platform\"), option.WithUserAgent(userAgent)}, o...)\n\n\t\to = append(o, internaloption.WithDefaultEndpoint(\"https://storage.googleapis.com/storage/v1/\"))\n\t\to = append(o, internaloption.WithDefaultMTLSEndpoint(\"https://storage.mtls.googleapis.com/storage/v1/\"))\n\n\t\t// Don't error out here. The user may have passed in their own HTTP\n\t\t// client which does not auth with ADC or other common conventions.\n\t\tc, err := transport.Creds(ctx, o...)\n\t\tif err == nil {\n\t\t\tcreds = c\n\t\t\to = append(o, internaloption.WithCredentials(creds))\n\t\t}\n\t} else {\n\t\tvar hostURL *url.URL\n\n\t\tif strings.Contains(host, \"://\") {\n\t\t\th, err := url.Parse(host)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\thostURL = h\n\t\t} else {\n\t\t\t// Add scheme for user if not supplied in STORAGE_EMULATOR_HOST\n\t\t\t// URL is only parsed correctly if it has a scheme, so we build it ourselves\n\t\t\thostURL = &url.URL{Scheme: \"http\", Host: host}\n\t\t}\n\n\t\thostURL.Path = \"storage/v1/\"\n\t\tendpoint := hostURL.String()\n\n\t\t// Append the emulator host as default endpoint for the user\n\t\to = append([]option.ClientOption{option.WithoutAuthentication()}, o...)\n\n\t\to = append(o, internaloption.WithDefaultEndpoint(endpoint))\n\t\to = append(o, internaloption.WithDefaultMTLSEndpoint(endpoint))\n\t}\n\ts.clientOption = o\n\n\t// htransport selects the correct endpoint among WithEndpoint (user override), WithDefaultEndpoint, and WithDefaultMTLSEndpoint.\n\thc, ep, err := htransport.NewClient(ctx, s.clientOption...)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"dialing: %v\", err)\n\t}\n\t// RawService should be created with the chosen endpoint to take account of user override.\n\trawService, err := raw.NewService(ctx, option.WithEndpoint(ep), option.WithHTTPClient(hc))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"storage client: %v\", err)\n\t}\n\t// Update readHost and scheme with the chosen endpoint.\n\tu, err := url.Parse(ep)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"supplied endpoint %q is not valid: %v\", ep, err)\n\t}\n\n\treturn &httpStorageClient{\n\t\tcreds: creds,\n\t\thc: hc,\n\t\treadHost: u.Host,\n\t\traw: rawService,\n\t\tscheme: u.Scheme,\n\t\tsettings: s,\n\t}, nil\n}", "func NewClient() {\n\tvar err error\n\tclient, err = storage.NewClient(ctx)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n}", "func GCS(cfg *config.StorageGCSConfig, loggerHandle logger.Logger) (stg Storage, err error) {\n\tloggerHandle.Debugf(\"GCS(cfg): %#v\", cfg)\n\n\tstg = &gcs{\n\t\tbucketName: cfg.Bucket,\n\t\tcredentialsJSON: cfg.CredentialsJSON,\n\t\tlog: loggerHandle,\n\t}\n\n\treturn\n}", "func RunCreateGoogleCloudStorage(cmd *cobra.Command, args []string) {\n\tlog := util.Logger()\n\tcreateCommon(cmd, args, nbv1.NSStoreTypeGoogleCloudStorage, func(namespaceStore *nbv1.NamespaceStore, secret *corev1.Secret) {\n\t\ttargetBucket := util.GetFlagStringOrPrompt(cmd, \"target-bucket\")\n\t\tsecretName, _ := cmd.Flags().GetString(\"secret-name\")\n\t\tmandatoryProperties := []string{\"GoogleServiceAccountPrivateKeyJson\"}\n\n\t\tif secretName == \"\" {\n\t\t\tprivateKeyJSONFile := util.GetFlagStringOrPrompt(cmd, \"private-key-json-file\")\n\t\t\tbytes, err := os.ReadFile(privateKeyJSONFile)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to read file %q: %v\", privateKeyJSONFile, err)\n\t\t\t}\n\t\t\tvar privateKeyJSON map[string]interface{}\n\t\t\terr = json.Unmarshal(bytes, &privateKeyJSON)\n\t\t\tif err != nil {\n\t\t\t\tlog.Fatalf(\"Failed to parse json file %q: %v\", privateKeyJSONFile, err)\n\t\t\t}\n\t\t\tsecret.StringData[\"GoogleServiceAccountPrivateKeyJson\"] = string(bytes)\n\t\t} else {\n\t\t\tutil.VerifyCredsInSecret(secretName, options.Namespace, mandatoryProperties)\n\t\t\tsecret.Name = secretName\n\t\t\tsecret.Namespace = options.Namespace\n\t\t}\n\n\t\tnamespaceStore.Spec.GoogleCloudStorage = &nbv1.GoogleCloudStorageSpec{\n\t\t\tTargetBucket: targetBucket,\n\t\t\tSecret: corev1.SecretReference{\n\t\t\t\tName: secret.Name,\n\t\t\t\tNamespace: secret.Namespace,\n\t\t\t},\n\t\t}\n\t})\n}", "func Init(bucket string) (*GCPStorage, error) {\n\tctx := context.TODO()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GCPStorage{client, bucket}, nil\n}", "func New(ctx context.Context, bucket string) (fs.Interface, error) {\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &gcs{\n\t\tbucket: client.Bucket(bucket),\n\t}, nil\n}", "func NewService(ctx context.Context) (*storage.Service, error) {\n\thttpClient, err := google.DefaultClient(ctx, storage.CloudPlatformScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient, err := storage.New(httpClient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient.UserAgent = UserAgent\n\treturn client, nil\n}", "func NewStorageAPI(g func(ctx context.Context) (*grpc.ClientConn, error)) *StorageAPI {\n\treturn &StorageAPI{g}\n}", "func NewStorage_Client(addresse string) *Storage_Client {\n\tclient := new(Storage_Client)\n\tclient.cc = getClientConnection(addresse)\n\tclient.c = storagepb.NewStorageServiceClient(client.cc)\n\treturn client\n}", "func New() (*Client, error) {\n\tstorageClient, err := newClient()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient := &Client{\n\t\tClient: *storageClient,\n\t}\n\tclient.SetRetryer()\n\n\treturn client, nil\n}", "func (g *gcs) Init(ctx context.Context) (err error) {\n\tg.context = context.Background()\n\n\tgcsClient, err := storage.NewClient(g.context, option.WithCredentialsFile(g.credentialsJSON))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tg.bucket = gcsClient.Bucket(g.bucketName)\n\tg.client = gcsClient\n\n\treturn\n}", "func CmdCreateGoogleCloudStorage() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tHidden: true, //TODO: remove once we want to expose it. \n\t\tUse: \"google-cloud-storage <namespace-store-name>\",\n\t\tShort: \"Create google-cloud-storage namespace store\",\n\t\tRun: RunCreateGoogleCloudStorage,\n\t}\n\tcmd.Flags().String(\n\t\t\"target-bucket\", \"\",\n\t\t\"The target bucket name on Google cloud storage\",\n\t)\n\tcmd.Flags().String(\n\t\t\"private-key-json-file\", \"\",\n\t\t`private-key-json-file is the path to the json file provided by google for service account authentication`,\n\t)\n\tcmd.Flags().String(\n\t\t\"secret-name\", \"\",\n\t\t`The name of a secret for authentication - should have GoogleServiceAccountPrivateKeyJson property`,\n\t)\n\treturn cmd\n}", "func NewClient() (storage.Client, error) {\n\treturn &fileClient{}, nil\n}", "func NewClient(ctx context.Context, projectID, bucket string) (*Client, error) {\n\tc, err := gcs.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Client{\n\t\tgcsClient: c,\n\t\tprojectID: projectID,\n\t\tbucket: bucket,\n\t}, nil\n}", "func newWithOptions(options ...option.ClientOption) buckets.Provider {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx, options...)\n\tif err != nil {\n\t\tlogs.Panicf(\"Failed to get GCS client: %v\", err)\n\t}\n\n\treturn &bucketProvider{client}\n}", "func NewStorage(cfg *api.Config, rootPath string, syncFrequency time.Duration) (storage.Interface, error) {\n\tcfg.WaitTime = syncFrequency\n\n\t// Get a new client\n\tclient, err := api.NewClient(cfg)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"creating consul client\")\n\t}\n\n\treturn &Client{\n\t\tv1: &v1client{\n\t\t\tupstreams: &upstreamsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/upstreams\", client),\n\t\t\t},\n\t\t\tvirtualHosts: &virtualHostsClient{\n\t\t\t\tbase: base.NewConsulStorageClient(rootPath+\"/virtualhosts\", client),\n\t\t\t},\n\t\t},\n\t}, nil\n}", "func NewGoogle() (*Storage, error) {\n\t// Google Drive Service\n\tctx := context.Background()\n\n\tb, err := ioutil.ReadFile(\"credentials/drive_client_secret.json\")\n\tif err != nil {\n\t\treturn nil, &Error{\"NewGoogle\", \"\", err}\n\t}\n\n\tconfig, err := google.ConfigFromJSON(b, drive.DriveScope)\n\tif err != nil {\n\t\treturn nil, &Error{\"NewGoogle\", \"\", err}\n\t}\n\tclient := auth.GetGoogleClient(ctx, config)\n\n\tsrv, err := drive.New(client)\n\tif err != nil {\n\t\treturn nil, &Error{\"NewGoogle\", \"\", err}\n\t}\n\treturn &Storage{Drive: DriverService{srv}}, nil\n}", "func (store Storage) GetClient() Client {\n\treturn Client{}\n}", "func NewGCSService(debugLog debugging, scopes ...string) (*GCSclient, error) {\n\tdebugLog.Println(\"Connecting to Google Cloud Storage ...\")\n\tvar opts []option.ClientOption\n\topts = append(opts, option.WithScopes(scopes...))\n\tc, err := storage.NewClient(context.Background(), opts...)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &GCSclient{c, debugLog}, nil\n}", "func (g *GCS) load() {\n\tctx, cancel := context.WithTimeout(context.Background(), time.Minute)\n\tdefer cancel()\n\n\tcos := []option.ClientOption{}\n\tif g.CredentialsJSON != \"\" {\n\t\tvar creds *google.Credentials\n\t\tif creds, g.loadError = google.CredentialsFromJSON(\n\t\t\tctx,\n\t\t\t[]byte(g.CredentialsJSON),\n\t\t); g.loadError != nil {\n\t\t\treturn\n\t\t}\n\n\t\tcos = append(cos, option.WithCredentials(creds))\n\t}\n\n\tvar client *storage.Client\n\tif client, g.loadError = storage.NewClient(\n\t\tctx,\n\t\tcos...,\n\t); g.loadError != nil {\n\t\treturn\n\t}\n\n\tg.bucket = client.Bucket(g.BucketName)\n}", "func NewGCPClient(keys, projectName string) (*GCPClient, error) {\n\tlog.Debugf(\"Connecting to GCP\")\n\tctx := context.Background()\n\tvar client *GCPClient\n\tif projectName == \"\" {\n\t\treturn nil, fmt.Errorf(\"the project name is not specified\")\n\t}\n\tif keys != \"\" {\n\t\tlog.Debugf(\"Using Keys %s\", keys)\n\t\tf, err := os.Open(keys)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tjsonKey, err := io.ReadAll(f)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tconfig, err := google.JWTConfigFromJSON(jsonKey,\n\t\t\tstorage.DevstorageReadWriteScope,\n\t\t\tcompute.ComputeScope,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tclient = &GCPClient{\n\t\t\tclient: config.Client(ctx),\n\t\t\tprojectName: projectName,\n\t\t}\n\t} else {\n\t\tlog.Debugf(\"Using Application Default credentials\")\n\t\tgc, err := google.DefaultClient(\n\t\t\tctx,\n\t\t\tstorage.DevstorageReadWriteScope,\n\t\t\tcompute.ComputeScope,\n\t\t)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclient = &GCPClient{\n\t\t\tclient: gc,\n\t\t\tprojectName: projectName,\n\t\t}\n\t}\n\n\tvar err error\n\tclient.compute, err = compute.NewService(ctx, option.WithHTTPClient(client.client))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tclient.storage, err = storage.NewService(ctx, option.WithHTTPClient(client.client))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debugf(\"Generating SSH Keypair\")\n\tclient.privKey, err = rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn client, nil\n}", "func NewGCSClient() FileStorage {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"falha ao criar client do GCS, erro %q\", err)\n\t}\n\treturn &GSCClient{\n\t\tclient: client,\n\t}\n}", "func NewStorageClient(cfg Config) (*server, error) {\n\tsession, err := cfg.session()\n\tif err != nil {\n\t\treturn nil, errors.WithStack(err)\n\t}\n\tlogger, _ := zap.NewProduction()\n\tclient := &server{\n\t\tCfg: cfg,\n\t\tSession: session,\n\t\tLogger: logger,\n\t}\n\treturn client, nil\n}", "func NewCloudStorageClient(bucket string) *CloudStorageClient {\n\treturn &CloudStorageClient{\n\t\tbucket: bucket,\n\t}\n}", "func newClient(conf config) (*storage.Client, error) {\n\tdb, err := storage.NewDBClient(conf.MongoURI, conf.DBName, conf.MongoMICol, conf.MongoAgCol)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating DB client: %q\", err)\n\t}\n\tdb.Collection(conf.MongoMICol)\n\tbc := storage.NewCloudClient(conf.SwiftUsername, conf.SwiftAPIKey, conf.SwiftAuthURL, conf.SwiftDomain, conf.SwiftContainer)\n\tclient, err := storage.NewClient(db, bc)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating storage.client: %q\", err)\n\t}\n\treturn client, nil\n}", "func configureCloud(res http.ResponseWriter, req *http.Request) (gcs *gcsPhotos) {\n\tctx := appengine.NewContext(req)\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Errorf(ctx, \"ERROR handler NewClient: \", err)\n\t\treturn\n\t}\n\tdefer client.Close()\n\t\n\tgcs = &gcsPhotos{\n\t\tctx: ctx,\n\t\tres: res,\n\t\tclient: client,\n\t\tbucket: client.Bucket(gcsBucket),\n\t}\n\treturn\n}", "func (s *Service) GSClient(c context.Context) (gs.Client, error) {\n\trt, err := s.AuthenticatedTransport(c, func(o *auth.Options) {\n\t\to.Scopes = gs.ReadWriteScopes\n\t})\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(c, \"Failed to create authenticated GS transport.\")\n\t\treturn nil, err\n\t}\n\n\tclient, err := gs.NewProdClient(c, rt)\n\tif err != nil {\n\t\tlog.WithError(err).Errorf(c, \"Failed to create Google Storage client.\")\n\t\treturn nil, err\n\t}\n\treturn client, nil\n}", "func FirebaseStorage() *storage.Client {\n\t//define storage bucket, calling from env\n\tconfig := &firebase.Config{\n\t\tStorageBucket: os.Getenv(\"STORAGE_BUCKET\"),\n\t}\n\t//we need cred to connect with firebase\n\topt := option.WithCredentialsFile(\"key.json\")\n\t//bond connection with firebase\n\tapp, err := firebase.NewApp(context.Background(), config, opt)\n\tif err != nil {\n\t\tlog.Fatalf(errors.ErrFailedInit.Error(), err)\n\t}\n\t// init firebase storage\n\tstorage, err := app.Storage(context.Background())\n\tif err != nil {\n\t\tlog.Fatalf(errors.ErrStorageinit.Error(), err)\n\t}\n\n\treturn storage\n}", "func GoogleCloudStorage(ctx context.Context, bucket, subdir string) (CacheFunc, error) {\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tbkt := client.Bucket(bucket)\n\treturn func(in chan *Request) chan *Request {\n\t\tout := make(chan *Request)\n\n\t\t// This function writes the data to the disk after it is\n\t\t// created, and is sent along with the request if the data is\n\t\t// not in the cache.\n\t\twriteFunc := func(req *Request) {\n\t\t\tif len(req.errs) > 0 {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tobj := bkt.Object(subdir + \"/\" + req.key() + FileExtension)\n\t\t\tw := obj.NewWriter(req.ctx)\n\t\t\tdefer w.Close()\n\t\t\tb, err := req.resultPayload.MarshalBinary()\n\t\t\tif err != nil {\n\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif _, err = w.Write(b); err != nil {\n\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tgo func() {\n\t\t\tfor req := range in {\n\t\t\t\tobj := bkt.Object(subdir + \"/\" + req.key() + FileExtension)\n\t\t\t\tf, err := obj.NewReader(req.ctx)\n\t\t\t\tif err != nil {\n\t\t\t\t\tif err == storage.ErrObjectNotExist {\n\t\t\t\t\t\treq.funcs = append(req.funcs, writeFunc)\n\t\t\t\t\t\tout <- req\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tb, err := ioutil.ReadAll(f)\n\t\t\t\tif err != nil {\n\t\t\t\t\t// We can't read the file.\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := req.resultPayload.UnmarshalBinary(b); err != nil {\n\t\t\t\t\t// There is some problem with the file.\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif err := f.Close(); err != nil {\n\t\t\t\t\treq.errs = append(req.errs, err)\n\t\t\t\t\treq.returnChan <- req\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Successfully retrieved the result. Now return it to the requester.\n\t\t\t\treq.returnChan <- req\n\t\t\t}\n\t\t}()\n\t\treturn out\n\t}, nil\n}", "func InitStorage(service string, bucket string) {\n\ttransferType = service\n\tbenchName = bucket\n\tawsAccessKey, ok := os.LookupEnv(\"AWS_ACCESS_KEY\")\n\tif ok {\n\t\tAKID = awsAccessKey\n\t}\n\tawsSecretKey, ok := os.LookupEnv(\"AWS_SECRET_KEY\")\n\tif ok {\n\t\tSECRET_KEY = awsSecretKey\n\t}\n\tAWS_S3_REGION = \"us-west-1\"\n\tawsRegion, ok := os.LookupEnv(\"AWS_REGION\")\n\tif ok {\n\t\tAWS_S3_REGION = awsRegion\n\t}\n\tif transferType == S3 {\n\t\tvar err error\n\t\ts3session, err = session.NewSession(&aws.Config{\n\t\t\tRegion: aws.String(AWS_S3_REGION),\n\t\t\tCredentials: credentials.NewStaticCredentials(AKID, SECRET_KEY, TOKEN),\n\t\t})\n\t\tif err != nil {\n\t\t\tlog.Fatalf(\"Failed establish s3 session: %s\", err)\n\t\t}\n\t} else if transferType == ELASTICACHE {\n\t\tredisClient = redis.NewClient(&redis.Options{\n\t\t\tAddr: benchName,\n\t\t\tPassword: \"\", // no password set\n\t\t\tDB: 0, // use default DB\n\t\t})\n\t}\n}", "func NewClient(config *triton.ClientConfig) (*StorageClient, error) {\n\t// TODO: Utilize config interface within the function itself\n\tclient, err := client.New(config.TritonURL, config.MantaURL, config.AccountName, config.Signers...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn newStorageClient(client), nil\n}", "func NewCloudStorageClient(ctxIn context.Context, tokenSourceProvider impersonate.TargetPrincipalForProjectProvider, targetProjectID string) (CloudStorageClient, error) {\n\tctx, span := trace.StartSpan(ctxIn, \"NewCloudStorageClient\")\n\tdefer span.End()\n\n\tif strings.EqualFold(targetProjectID, config.GCPProjectId.GetOrDefault(\"\")) {\n\t\treturn createCloudStorageClient(ctx)\n\t}\n\treturn createImpersonatedCloudStorageClient(ctx, tokenSourceProvider, targetProjectID)\n}", "func NewGCEClient() *gce.Cloud {\n\tvar configReader func() io.Reader\n\tif flags.F.ConfigFilePath != \"\" {\n\t\tklog.Infof(\"Reading config from path %q\", flags.F.ConfigFilePath)\n\t\tconfig, err := os.Open(flags.F.ConfigFilePath)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"%v\", err)\n\t\t}\n\t\tdefer config.Close()\n\n\t\tallConfig, err := io.ReadAll(config)\n\t\tif err != nil {\n\t\t\tklog.Fatalf(\"Error while reading config (%q): %v\", flags.F.ConfigFilePath, err)\n\t\t}\n\t\tklog.V(4).Infof(\"Cloudprovider config file contains: %q\", string(allConfig))\n\n\t\tconfigReader = generateConfigReaderFunc(allConfig)\n\t} else {\n\t\tklog.V(2).Infof(\"No cloudprovider config file provided, using default values.\")\n\t\tconfigReader = func() io.Reader { return nil }\n\t}\n\n\t// Creating the cloud interface involves resolving the metadata server to get\n\t// an oauth token. If this fails, the token provider assumes it's not on GCE.\n\t// No errors are thrown. So we need to keep retrying till it works because\n\t// we know we're on GCE.\n\tfor {\n\t\tprovider, err := cloudprovider.GetCloudProvider(\"gce\", configReader())\n\t\tif err == nil {\n\t\t\tcloud := provider.(*gce.Cloud)\n\t\t\t// Configure GCE rate limiting\n\t\t\trl, err := ratelimit.NewGCERateLimiter(flags.F.GCERateLimit.Values(), flags.F.GCEOperationPollInterval)\n\t\t\tif err != nil {\n\t\t\t\tklog.Fatalf(\"Error configuring rate limiting: %v\", err)\n\t\t\t}\n\t\t\tcloud.SetRateLimiter(rl)\n\t\t\t// If this controller is scheduled on a node without compute/rw\n\t\t\t// it won't be allowed to list backends. We can assume that the\n\t\t\t// user has no need for Ingress in this case. If they grant\n\t\t\t// permissions to the node they will have to restart the controller\n\t\t\t// manually to re-create the client.\n\t\t\t// TODO: why do we bail with success out if there is a permission error???\n\t\t\tif _, err = cloud.ListGlobalBackendServices(); err == nil || utils.IsHTTPErrorCode(err, http.StatusForbidden) {\n\t\t\t\treturn cloud\n\t\t\t}\n\t\t\tklog.Warningf(\"Failed to list backend services, retrying: %v\", err)\n\t\t} else {\n\t\t\tklog.Warningf(\"Failed to get cloud provider, retrying: %v\", err)\n\t\t}\n\t\ttime.Sleep(cloudClientRetryInterval)\n\t}\n}", "func getRemoteBackupGoogleStorage(r *Restore, conf *config.Config, outFile *os.File) {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Could not initialize connection with Google Cloud Storage!: %v\", err)\n\t}\n\trc, err := client.Bucket(conf.GCSBucket).Object(r.RestorePath).NewReader(ctx)\n\tlog.Printf(\"[INFO] Downloading %v%v from GCS\", string(conf.GCSBucket), r.RestorePath)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Could not download file from GCS!: %v\", err)\n\t}\n\tcontent, _ := ioutil.ReadAll(rc)\n\t_, err = outFile.Write(content)\n\tif err != nil {\n\t\tlog.Fatalf(\"[ERR] Could not save file: %v\", err)\n\t}\n\trc.Close()\n}", "func NewGDriveStorage(ctx context.Context, clientJSONFilepath string, localConfigPath string, basedir string, chunkSize int, logger *log.Logger) (*GDrive, error) {\n\n\tb, err := ioutil.ReadFile(clientJSONFilepath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// If modifying these scopes, delete your previously saved client_secret.json.\n\tconfig, err := google.ConfigFromJSON(b, drive.DriveScope, drive.DriveMetadataScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\thttpClient := getGDriveClient(ctx, config, localConfigPath, logger)\n\n\tsrv, err := drive.NewService(ctx, option.WithHTTPClient(httpClient))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstorage := &GDrive{service: srv, basedir: basedir, rootID: \"\", localConfigPath: localConfigPath, chunkSize: chunkSize, logger: logger}\n\terr = storage.setupRoot()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn storage, nil\n}", "func NewClient(logger log.Logger, googleAPIjsonkeypath, googleProjectID, googleAPIdatasetID, googleAPItableID string, remoteTimeout time.Duration) *BigqueryClient {\n\tctx := context.Background()\n\tbigQueryClientOptions := []option.ClientOption{}\n\tif googleAPIjsonkeypath != \"\" {\n\t\tjsonFile, err := os.Open(googleAPIjsonkeypath)\n\t\tif err != nil {\n\t\t\tlevel.Error(logger).Log(\"err\", err) //nolint:errcheck\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tbyteValue, _ := io.ReadAll(jsonFile)\n\n\t\tvar result map[string]interface{}\n\t\terr = json.Unmarshal([]byte(byteValue), &result)\n\t\tif err != nil {\n\t\t\tlevel.Error(logger).Log(\"err\", err) //nolint:errcheck\n\t\t\tos.Exit(1)\n\t\t}\n\n\t\tjsonFile.Close()\n\n\t\tif googleProjectID == \"\" {\n\t\t\tgoogleProjectID = fmt.Sprintf(\"%v\", result[\"project_id\"])\n\t\t}\n\t\tbigQueryClientOptions = append(bigQueryClientOptions, option.WithCredentialsFile(googleAPIjsonkeypath))\n\t}\n\n\tc, err := bigquery.NewClient(ctx, googleProjectID, bigQueryClientOptions...)\n\n\tif err != nil {\n\t\tlevel.Error(logger).Log(\"err\", err) //nolint:errcheck\n\t\tos.Exit(1)\n\t}\n\n\tif logger == nil {\n\t\tlogger = log.NewNopLogger()\n\t}\n\n\treturn &BigqueryClient{\n\t\tlogger: logger,\n\t\tclient: *c,\n\t\tdatasetID: googleAPIdatasetID,\n\t\ttableID: googleAPItableID,\n\t\ttimeout: remoteTimeout,\n\t\tignoredSamples: prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"storage_bigquery_ignored_samples_total\",\n\t\t\t\tHelp: \"The total number of samples not sent to BigQuery due to unsupported float values (Inf, -Inf, NaN).\",\n\t\t\t},\n\t\t),\n\t\trecordsFetched: prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"storage_bigquery_records_fetched\",\n\t\t\t\tHelp: \"Total number of records fetched\",\n\t\t\t},\n\t\t),\n\t\tbatchWriteDuration: prometheus.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tName: \"storage_bigquery_batch_write_duration_seconds\",\n\t\t\t\tHelp: \"The duration it takes to write a batch of samples to BigQuery.\",\n\t\t\t\tBuckets: prometheus.DefBuckets,\n\t\t\t},\n\t\t),\n\t\tsqlQueryCount: prometheus.NewCounter(\n\t\t\tprometheus.CounterOpts{\n\t\t\t\tName: \"storage_bigquery_sql_query_count_total\",\n\t\t\t\tHelp: \"Total number of sql_queries executed.\",\n\t\t\t},\n\t\t),\n\t\tsqlQueryDuration: prometheus.NewHistogram(\n\t\t\tprometheus.HistogramOpts{\n\t\t\t\tName: \"storage_bigquery_sql_query_duration_seconds\",\n\t\t\t\tHelp: \"Duration of the sql reads from BigQuery.\",\n\t\t\t},\n\t\t),\n\t}\n}", "func NewClient(googleJSON string) (*Client, error) {\n\tgdrive, err := gd.NewGoogleDrive(googleJSON)\n\tif err != nil {\n\t\tgdrive = &gd.GoogleDrive{}\n\t}\n\n\treturn &Client{googledrive: gdrive}, err\n}", "func NewClient(api client.KeysAPI) storage.Client {\n\treturn &Client{\n\t\tAPI: api,\n\t}\n}", "func New(o *storage.Opts) (storage.Storage, error) {\n\tconst op = \"cloud/storage/drive.New\"\n\tvar (\n\t\tt oauth2.Token\n\t\tok bool\n\t\terr error\n\t)\n\tt.AccessToken, ok = o.Opts[\"accessToken\"]\n\tif !ok {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Str(\"missing accessToken\"))\n\t}\n\tt.TokenType, ok = o.Opts[\"tokenType\"]\n\tif !ok {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Str(\"missing tokenType\"))\n\t}\n\tt.RefreshToken, ok = o.Opts[\"refreshToken\"]\n\tif !ok {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Str(\"missing refreshToken\"))\n\t}\n\tt.Expiry, err = time.Parse(time.RFC3339, o.Opts[\"expiry\"])\n\tif err != nil {\n\t\treturn nil, errors.E(op, errors.Invalid, errors.Errorf(\"invalid expiry %q: %v\", o.Opts[\"expiry\"], err))\n\t}\n\tctx := context.Background()\n\tclient := config.OAuth2.Client(ctx, &t)\n\tsvc, err := drive.New(client)\n\tif err != nil {\n\t\treturn nil, errors.E(op, errors.Internal, err)\n\t}\n\treturn &driveImpl{\n\t\tfiles: svc.Files,\n\t\tids: cache.NewLRU(lruSize),\n\t}, nil\n}", "func NewStorage(client *clientv3.Client, codec codec.Codec) storage.Store {\n\treturn &Storage{\n\t\tclient: client,\n\t\tcodec: codec,\n\t}\n}", "func NewStorage(namespace, name string) (*Storage, error) {\n\tif err := k8sutil.CreateCRD(name); err != nil {\n\t\treturn nil, err\n\t}\n\tcli := k8sutil.NewRESTClient()\n\treturn &Storage{\n\t\tNamespace: namespace,\n\t\tName: strings.ToLower(name),\n\t\trestcli: cli,\n\t}, nil\n}", "func main() {\n\tctx := context.Background()\n\n\t// For API packages whose import path is starting with \"cloud.google.com/go\",\n\t// such as cloud.google.com/go/storage in this case, if there are no credentials\n\t// provided, the client library will look for credentials in the environment.\n\tstorageClient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tit := storageClient.Buckets(ctx, \"project-id\")\n\tfor {\n\t\tbucketAttrs, err := it.Next()\n\t\tif err == iterator.Done {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tfmt.Println(bucketAttrs.Name)\n\t}\n\n\t// For packages whose import path is starting with \"google.golang.org/api\",\n\t// such as google.golang.org/api/cloudkms/v1, use NewService to create the client.\n\tkmsService, err := cloudkms.NewService(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t_ = kmsService\n}", "func NewGoogleInGoogle() (*Storage, error) {\n\t// Google Drive Service\n\tctx := context.Background()\n\n\toauthClient, err := google.DefaultClient(ctx, drive.DriveScope)\n\tif err != nil {\n\t\treturn nil, &Error{\"NewGoogleInGoogle\", \"\", err}\n\t}\n\tsrv, err := drive.New(oauthClient)\n\tif err != nil {\n\t\treturn nil, &Error{\"NewGoogleInGoogle\", \"\", err}\n\t}\n\treturn &Storage{Drive: DriverService{srv}}, nil\n}", "func (vk *VK) StorageGet(params Params) (response StorageGetResponse, err error) {\n\terr = vk.RequestUnmarshal(\"storage.get\", &response, params)\n\n\treturn\n}", "func NewStorageReadClient(c datatypes.Storage_ReadClient) *StorageReadClient {\n\treturn &StorageReadClient{c: c}\n}", "func (g *GCPStorage) Close() error {\n\treturn g.client.Close()\n}", "func InitStorage() *storage.BucketHandle {\n\tctx := context.Background()\n\tclient, err := storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Fatalf(\"Failed to create Storage client: %v\\n\", err)\n\t}\n\tbucket := client.Bucket(os.Getenv(envVarNames[evBucket]))\n\tattrs, err := bucket.Attrs(context.Background())\n\tif attrs == nil {\n\t\tlog.Fatalf(\"Bucket has not attributes...\\n\")\n\t}\n\tif err != nil {\n\t\tlog.Fatalf(\"Could not get Bucket information: %v\\n\", err)\n\t}\n\treturn bucket\n}", "func New(o *Options) *Storage {\n\ts := &Storage{}\n\tif o.GraphiteAddress != \"\" {\n\t\tc := graphite.NewClient(\n\t\t\to.GraphiteAddress, o.GraphiteTransport,\n\t\t\to.StorageTimeout, o.GraphitePrefix)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.OpentsdbURL != \"\" {\n\t\tc := opentsdb.NewClient(o.OpentsdbURL, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.InfluxdbURL != nil {\n\t\tconf := influx.Config{\n\t\t\tURL: *o.InfluxdbURL,\n\t\t\tUsername: o.InfluxdbUsername,\n\t\t\tPassword: o.InfluxdbPassword,\n\t\t\tTimeout: o.StorageTimeout,\n\t\t}\n\t\tc := influxdb.NewClient(conf, o.InfluxdbDatabase, o.InfluxdbRetentionPolicy)\n\t\tprometheus.MustRegister(c)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif o.GenericURL != \"\" {\n\t\theaders := http.Header{}\n\t\tif o.GenericHeaderName != \"\" {\n\t\t\theaders.Add(o.GenericHeaderName, o.GenericHeaderValue)\n\t\t}\n\t\tc := generic.NewClient(o.GenericURL, headers, o.StorageTimeout)\n\t\ts.queues = append(s.queues, NewStorageQueueManager(c, defaultConfig))\n\t}\n\tif len(s.queues) == 0 {\n\t\treturn nil\n\t}\n\treturn s\n}", "func NewClient(client *storage.Client) ConditionalClient {\n\treturn gcsClient{\n\t\tgcs: &realGCSClient{client, nil, nil},\n\t\tlocal: &localClient{nil, nil},\n\t}\n}", "func newK8SCloud(opts Options) (CloudProvider, error) {\n\n\tif opts.Name == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud name\")\n\t}\n\tif opts.Host == \"\" {\n\t\treturn nil, errors.New(\"K8SCloud: Invalid cloud host\")\n\t}\n\tif opts.K8SNamespace == \"\" {\n\t\topts.K8SNamespace = apiv1.NamespaceDefault\n\t}\n\n\tcloud := &K8SCloud{\n\t\tname: opts.Name,\n\t\thost: opts.Host,\n\t\tbearerToken: opts.K8SBearerToken,\n\t\tnamespace: opts.K8SNamespace,\n\t\tinsecure: opts.Insecure,\n\t}\n\tconfig := &rest.Config{\n\t\tHost: opts.Host,\n\t\tBearerToken: opts.K8SBearerToken,\n\t\tTLSClientConfig: rest.TLSClientConfig{\n\t\t\tInsecure: opts.Insecure,\n\t\t},\n\t}\n\tclientset, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcloud.client = clientset\n\treturn cloud, nil\n}", "func setupGCP(ctx *context.Context, bucket string) (*blob.Bucket, error) {\n\t// DefaultCredentials assumes a user has logged in with gcloud.\n\t// See here for more information:\n\t// https://cloud.google.com/docs/authentication/getting-started\n\tcreds, err := gcp.DefaultCredentials(*ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := gcp.NewHTTPClient(gcp.DefaultTransport(), gcp.CredentialsTokenSource(creds))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// The bucket name must be globally unique.\n\treturn gcsblob.OpenBucket(*ctx, bucket, c, nil)\n}", "func (gcs *GCS) Connect() error {\n\tvar err error\n\tvar clientOption option.ClientOption\n\n\tctx := context.Background()\n\n\tif gcs.Config.CredentialsJSON != \"\" {\n\t\tclientOption = option.WithCredentialsJSON([]byte(gcs.Config.CredentialsJSON))\n\t\tgcs.client, err = storage.NewClient(ctx, clientOption)\n\t} else if gcs.Config.CredentialsFile != \"\" {\n\t\tclientOption = option.WithCredentialsFile(gcs.Config.CredentialsFile)\n\t\tgcs.client, err = storage.NewClient(ctx, clientOption)\n\t} else {\n\t\tgcs.client, err = storage.NewClient(ctx)\n\t}\n\treturn err\n}", "func setupGCP(ctx context.Context, bucket string) (*blob.Bucket, error) {\n\t// DefaultCredentials assumes a user has logged in with gcloud.\n\t// See here for more information:\n\t// https://cloud.google.com/docs/authentication/getting-started\n\tcreds, err := gcp.DefaultCredentials(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc, err := gcp.NewHTTPClient(gcp.DefaultTransport(), gcp.CredentialsTokenSource(creds))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn gcsblob.OpenBucket(ctx, bucket, c)\n}", "func NewClient(t string) *gophercloud.ServiceClient {\n\tvar err error\n\tao, region, err := authMethod()\n\tif err != nil {\n\t\tfmt.Printf(\"Error retrieving authentication credentials: %s\\n\", err)\n\t}\n\tif ao.IdentityEndpoint == \"\" {\n\t\tao.IdentityEndpoint = rackspace.RackspaceUSIdentity\n\t}\n\tpc, err := rackspace.AuthenticatedClient(ao)\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating ProviderClient: %s\\n\", err)\n\t\tos.Exit(1)\n\t}\n\tvar sc *gophercloud.ServiceClient\n\tswitch t {\n\tcase \"compute\":\n\t\tsc, err = rackspace.NewComputeV2(pc, gophercloud.EndpointOpts{\n\t\t\tRegion: region,\n\t\t})\n\t\tbreak\n\tcase \"blockstorage\":\n\t\tsc, err = rackspace.NewBlockStorageV1(pc, gophercloud.EndpointOpts{\n\t\t\tRegion: region,\n\t\t})\n\t\tbreak\n\tcase \"networking\":\n\t\tsc, err = rackspace.NewNetworkV2(pc, gophercloud.EndpointOpts{\n\t\t\tRegion: region,\n\t\t})\n\t\tbreak\n\t}\n\tif err != nil {\n\t\tfmt.Printf(\"Error creating ServiceClient (%s): %s\\n\", err, t)\n\t\tos.Exit(1)\n\t}\n\t// sc.UserAgent.Prepend(\"rack/\" + util.Version)\n\treturn sc\n}", "func getGDriveClient(ctx context.Context, config *oauth2.Config, localConfigPath string, logger *log.Logger) *http.Client {\n\ttokenFile := filepath.Join(localConfigPath, gDriveTokenJSONFile)\n\ttok, err := gDriveTokenFromFile(tokenFile)\n\tif err != nil {\n\t\ttok = getGDriveTokenFromWeb(ctx, config, logger)\n\t\tsaveGDriveToken(tokenFile, tok, logger)\n\t}\n\n\treturn config.Client(ctx, tok)\n}", "func NewGoogleClient(ps *persist.PersistService, consumer_key string, consumer_secret string) *AuthClient { // scope? []string ?\n\treturn NewAuthClient(ps, \"google\", consumer_key, consumer_secret, \"https://www.google.com/accounts/OAuthGetRequestToken\", \"https://www.google.com/accounts/OAuthGetAccessToken\", \"https://www.google.com/accounts/OAuthAuthorizeToken\");\n\n}", "func (c SASClient) GetBlobService() BlobStorageClient {\n\treturn BlobStorageClient{c}\n}", "func New(ctx context.Context, cfg *config.GCSCli) (*GCSBlobstore, error) {\n\tif cfg == nil {\n\t\treturn nil, errors.New(\"expected non-nill config object\")\n\t}\n\n\tauthenticatedGCS, publicGCS, err := newStorageClients(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"creating storage client: %v\", err)\n\t}\n\n\treturn &GCSBlobstore{authenticatedGCS: authenticatedGCS, publicGCS: publicGCS, config: cfg}, nil\n}", "func newStorageLayer(disk string) (storage StorageAPI, err error) {\n\tif !strings.ContainsRune(disk, ':') || filepath.VolumeName(disk) != \"\" {\n\t\t// Initialize filesystem storage API.\n\t\treturn newPosix(disk)\n\t}\n\t// Initialize rpc client storage API.\n\treturn newRPCClient(disk)\n}", "func (client Client) StorageAccounts() storage.AccountsClient {\n\tif client.accounts == nil {\n\t\tclnt := storage.NewAccountsClientWithBaseURI(client.baseURI, client.subscriptionID)\n\t\tclnt.Authorizer = client.Authorizer\n\t\tclnt.RequestInspector = client.RequestInspector\n\t\tclnt.ResponseInspector = client.ResponseInspector\n\t\tclient.accounts = &clnt\t\t\n\t}\t\n\treturn *client.accounts\n}", "func NewStorageService(conf *myconf.Config) (*StorageService, error) {\n\tbranch := util.GetRequiredEnv(\"BRANCH\")\n\tvar svc *minio.Client\n\tvar err error\n\tif branch != \"production\" {\n\t\tcredentials, err := myaws.NewSession().Config.Credentials.Get()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithRegion(\n\t\t\tendPoint,\n\t\t\tcredentials.AccessKeyID,\n\t\t\tcredentials.SecretAccessKey,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\tiam := minioCreds.NewIAM(\"\")\n\t\tendPoint := \"s3.amazonaws.com\"\n\t\tuseSSL := true\n\t\tsvc, err = minio.NewWithCredentials(\n\t\t\tendPoint,\n\t\t\tiam,\n\t\t\tuseSSL,\n\t\t\tmyaws.AWSRegion,\n\t\t)\n\t\tif err != nil {\n\t\t\tmylog.Log.WithError(err).Error(util.Trace(\"\"))\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// svc.TraceOn(nil)\n\treturn &StorageService{\n\t\tbucket: conf.AWSUploadBucket,\n\t\tsvc: svc,\n\t}, nil\n}", "func NewClient(target string) (PortsStorageClient, error) {\n\tc := new(portsStorageClient)\n\tvar conn *grpc.ClientConn\n\tconn, err := grpc.Dial(target, grpc.WithInsecure())\n\tif err != nil {\n\t\tlog.Fatalf(\"could not connect: %s\", err)\n\t\treturn nil, err\n\t}\n\n\tc.conn = conn\n\tc.client = storage.NewStorageServiceClient(conn)\n\n\treturn c, nil\n}", "func GetStorageClientFromFile(keyFile string) (*storage.Client, context.Context, error) {\n\tvar client *storage.Client\n\tvar err error\n\n\tctx := context.Background()\n\n\tif keyFile == \"\" {\n\t\tclient, err = storage.NewClient(ctx)\n\t} else {\n\t\tclient, err = storage.NewClient(ctx, option.WithCredentialsFile(keyFile))\n\t}\n\n\tif err != nil {\n\t\treturn client, ctx, fmt.Errorf(\"creating storage client: %w\", err)\n\t}\n\n\treturn client, ctx, nil\n}", "func GetStorageProvider() datastore.Store {\n\treturn storageAPI\n}", "func NewGCSLock(bucket string, object string, opts ...Option) (*GCSLock, error) {\n\tl := &GCSLock{\n\t\tlogger: zap.L(),\n\n\t\tbucket: bucket,\n\t\tobject: object,\n\t\tbaseURL: url.URL{\n\t\t\tScheme: \"https\",\n\t\t\tHost: \"storage.googleapis.com\",\n\t\t},\n\n\t\tbackOffGenerator: DefaultBackOffGenerator(),\n\t\tlockFileMetadata: DefaultLockFileMetadataGenerator(),\n\t}\n\n\tfor _, opt := range opts {\n\t\topt(l)\n\t}\n\n\tl.logger = l.logger.With(zap.String(\"bucket\", bucket), zap.String(\"object\", object))\n\n\tif l.httpClient == nil {\n\t\thttpClient, err := DefaultGoogleHTTPClient(context.Background(), _googleAuthScopeDevStorageFullControl)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"failed to create default google http client\")\n\t\t}\n\t\tl.httpClient = httpClient\n\t}\n\n\treturn l, nil\n}", "func newGoogleCloudStorageSources(c *SourcesV1alpha1Client, namespace string) *googleCloudStorageSources {\n\treturn &googleCloudStorageSources{\n\t\tclient: c.RESTClient(),\n\t\tns: namespace,\n\t}\n}", "func getContainerClient(credential idrv.CredentialInfo) (context.Context, *container.Service, error) {\n\n\t// GCP 는 ClientSecret에\n\tgcpType := \"service_account\"\n\tdata := make(map[string]string)\n\n\tdata[\"type\"] = gcpType\n\tdata[\"private_key\"] = credential.PrivateKey\n\tdata[\"client_email\"] = credential.ClientEmail\n\n\tfmt.Println(\"################## data ##################\")\n\t//fmt.Println(\"data to json : \", data)\n\tfmt.Println(\"################## data ##################\")\n\n\tres, _ := json.Marshal(data)\n\tauthURL := \"https://www.googleapis.com/auth/cloud-platform\"\n\n\tconf, err := goo.JWTConfigFromJSON(res, authURL)\n\n\tif err != nil {\n\n\t\treturn nil, nil, err\n\t}\n\n\tclient := conf.Client(o2.NoContext)\n\n\tcontainerClient, err := container.New(client)\n\n\tctx := context.Background()\n\n\treturn ctx, containerClient, nil\n}", "func newStorage(account *account, prov provider.Account, cfg *config.Storage) (*storage, error) {\n\tlog.Debug(\"Initializing Storage\")\n\n\t// Validate the config.Storage object.\n\tif cfg.Buckets == nil {\n\t\treturn nil, fmt.Errorf(\"The buckets element is missing from the storage configuration\")\n\t}\n\n\ts := &storage{\n\t\tResources: resource.NewResources(),\n\t\tStorage: cfg,\n\t\taccount: account,\n\t}\n\n\tvar err error\n\ts.providerStorage, err = prov.NewStorage(cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ts.buckets, err = newBuckets(s, prov, cfg.Buckets)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ts.Append(s.buckets)\n\treturn s, nil\n}", "func WithGCS(dl Downloader) func(*Loader) {\n\treturn func(l *Loader) {\n\t\tl.clients[\"gs\"] = dl\n\t\tl.clients[\"gcs\"] = dl\n\t}\n}", "func authClient(cacheFile, code string) (*http.Client, error) {\n\tconfig := &oauth.Config{\n\t\tClientId: clientId,\n\t\tClientSecret: clientSecret,\n\t\tScope: storage.DevstorageFull_controlScope,\n\t\tAuthURL: \"https://accounts.google.com/o/oauth2/auth\",\n\t\tTokenURL: \"https://accounts.google.com/o/oauth2/token\",\n\t\tTokenCache: oauth.CacheFile(cacheFile),\n\t\tRedirectURL: \"urn:ietf:wg:oauth:2.0:oob\",\n\t}\n\n\ttransport := &oauth.Transport{\n\t\tConfig: config,\n\t\tTransport: http.DefaultTransport,\n\t}\n\n\ttoken, err := config.TokenCache.Token()\n\tif err != nil {\n\t\tif code == \"\" {\n\t\t\turl := config.AuthCodeURL(\"\")\n\t\t\treturn nil, fmt.Errorf(\"Visit URL to get a code then run again with -code=YOUR_CODE\\n%s\", url)\n\t\t}\n\n\t\t// Exchange auth code for access token\n\t\ttoken, err = transport.Exchange(code)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tlog.Printf(\"Token is cached in %v\\n\", config.TokenCache)\n\t}\n\ttransport.Token = token\n\n\treturn transport.Client(), nil\n}", "func NewCloudStorage(devservers []string,\n\ttlwServer, dutName, dutServer, buildArtifactsURL, swarmingTaskID, buildBucketID string) *CloudStorage {\n\treturn &CloudStorage{\n\t\tnewClient: func(ctx context.Context) (devserver.Client, error) {\n\t\t\treturn newClientForURLs(ctx, devservers, tlwServer, dutName, dutServer, swarmingTaskID, buildBucketID)\n\t\t},\n\t\tbuildArtifactsURL: buildArtifactsURL,\n\t}\n}", "func GetStorage(ctx *Context, storageType string, storageConfig interface{}) (Storage, error) {\n\tLog(INFO, ctx, \"System.GetStorage\", \"storageType\", storageType, \"storageConfig\", storageConfig)\n\n\tswitch storageType {\n\tcase \"none\":\n\t\treturn NewNoStorage(ctx)\n\n\tcase \"memory\", \"mem\":\n\t\treturn NewMemStorage(ctx)\n\n\tcase \"cassandra\":\n\t\tnodes := storageConfig\n\t\tvar ns []string\n\t\tvar configStr string\n\n\t\tswitch vv := nodes.(type) {\n\t\tcase []interface{}:\n\t\t\tns = make([]string, 0, len(vv))\n\t\t\tfor _, n := range vv {\n\t\t\t\tns = append(ns, n.(string))\n\t\t\t}\n\t\t\tLog(INFO, ctx, \"core.GetStorage\", \"nodes\", ns)\n\t\t\tconfigStr = strings.Join(ns, \",\")\n\t\tcase string:\n\t\t\tconfigStr = nodes.(string)\n\t\tcase []string:\n\t\t\tconfigStr = strings.Join(nodes.([]string), \",\")\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"bad type for nodes %v (%T); should be []interface{}.\", nodes, nodes)\n\t\t}\n\t\tconfig, err := cassandra.ParseConfig(configStr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn cassandra.NewStorage(ctx, *config)\n\n\tcase \"bolt\":\n\t\tfilename := storageConfig\n\t\tswitch s := filename.(type) {\n\t\tcase string:\n\t\t\treturn bolt.NewStorage(ctx, s)\n\t\tdefault:\n\t\t\treturn nil,\n\t\t\t\tfmt.Errorf(\"Bad type for filenames %v (%T); should be a string\", filename, filename)\n\t\t}\n\n\tcase \"dynamodb\":\n\t\tregion := storageConfig\n\t\tswitch vv := region.(type) {\n\t\tcase string:\n\t\t\tconfig, err := dynamodb.ParseConfig(vv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\treturn dynamodb.GetStorage(ctx, *config)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"Bad type for DynamoDB region %v (%T); should be string.\",\n\t\t\t\tstorageConfig,\n\t\t\t\tstorageConfig)\n\t\t}\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"Unknown storage '%s'\", storageType)\n\t}\n\n}", "func (gc gcsClient) Open(ctx context.Context, path Path) (io.ReadCloser, *storage.ReaderObjectAttrs, error) {\n\tclient := gc.clientFromPath(path)\n\treturn client.Open(ctx, path)\n}", "func New(ctx context.Context, local bool) (*store, error) {\n\tts, err := google.DefaultTokenSource(ctx, auth.ScopeFullControl)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Problem setting up client OAuth: %s\", err)\n\t}\n\tclient := httputils.DefaultClientConfig().WithTokenSource(ts).With2xxOnly().Client()\n\tstorageClient, err := storage.NewClient(context.Background(), option.WithHTTPClient(client))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Problem creating storage client: %s\", err)\n\t}\n\tcache, err := lru.New(LRU_CACHE_SIZE)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Failed creating cache: %s\", err)\n\t}\n\treturn &store{\n\t\tbucket: storageClient.Bucket(FIDDLE_STORAGE_BUCKET),\n\t\tcache: cache,\n\t}, nil\n}", "func (d *driver) CreateStorage(cr *opapi.ImageRegistry, modified *bool) error {\n\tsvc, err := d.getSVC()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tic, err := util.GetInstallConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcv, err := util.GetClusterVersionConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor i := 0; i < 5000; i++ {\n\t\tif len(d.Config.Bucket) == 0 {\n\t\t\td.Config.Bucket = fmt.Sprintf(\"%s-%s-%s-%s\", clusterconfig.StoragePrefix, d.Config.Region, strings.Replace(string(cv.Spec.ClusterID), \"-\", \"\", -1), strings.Replace(string(uuid.NewUUID()), \"-\", \"\", -1))[0:62]\n\t\t}\n\n\t\t_, err := svc.CreateBucket(&s3.CreateBucketInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tswitch aerr.Code() {\n\t\t\t\tcase s3.ErrCodeBucketAlreadyExists:\n\t\t\t\t\tif cr.Spec.Storage.S3.Bucket != \"\" {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\td.Config.Bucket = \"\"\n\t\t\t\t\tcontinue\n\t\t\t\tdefault:\n\t\t\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tbreak\n\t}\n\n\tif len(cr.Spec.Storage.S3.Bucket) == 0 && len(d.Config.Bucket) == 0 {\n\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, \"Unable to Generate Unique Bucket Name\", \"\", modified)\n\t\treturn fmt.Errorf(\"unable to generate a unique s3 bucket name\")\n\t}\n\n\t// Wait until the bucket exists\n\tif err := svc.WaitUntilBucketExists(&s3.HeadBucketInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t}); err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t}\n\n\t\treturn err\n\t}\n\n\t// Tag the bucket with the openshiftClusterID\n\t// along with any user defined tags from the cluster configuration\n\tif ic.Platform.AWS != nil {\n\t\tvar tagSet []*s3.Tag\n\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(\"openshiftClusterID\"), Value: aws.String(string(cv.Spec.ClusterID))})\n\t\tfor k, v := range ic.Platform.AWS.UserTags {\n\t\t\ttagSet = append(tagSet, &s3.Tag{Key: aws.String(k), Value: aws.String(v)})\n\t\t}\n\n\t\t_, err := svc.PutBucketTagging(&s3.PutBucketTaggingInput{\n\t\t\tBucket: aws.String(d.Config.Bucket),\n\t\t\tTagging: &s3.Tagging{\n\t\t\t\tTagSet: tagSet,\n\t\t\t},\n\t\t})\n\t\tif err != nil {\n\t\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t\t} else {\n\t\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t\t}\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageTagged, operatorapi.ConditionTrue, \"Tagging Successful\", \"UserTags were successfully applied to the S3 bucket\", modified)\n\t\t}\n\t}\n\n\t// Enable default encryption on the bucket\n\t_, err = svc.PutBucketEncryption(&s3.PutBucketEncryptionInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tServerSideEncryptionConfiguration: &s3.ServerSideEncryptionConfiguration{\n\t\t\tRules: []*s3.ServerSideEncryptionRule{\n\t\t\t\t{\n\t\t\t\t\tApplyServerSideEncryptionByDefault: &s3.ServerSideEncryptionByDefault{\n\t\t\t\t\t\tSSEAlgorithm: aws.String(s3.ServerSideEncryptionAes256),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageEncrypted, operatorapi.ConditionTrue, \"Encryption Successful\", \"Default encryption was successfully enabled on the S3 bucket\", modified)\n\t}\n\n\t// Enable default incomplete multipart upload cleanup after one (1) day\n\t_, err = svc.PutBucketLifecycleConfiguration(&s3.PutBucketLifecycleConfigurationInput{\n\t\tBucket: aws.String(d.Config.Bucket),\n\t\tLifecycleConfiguration: &s3.BucketLifecycleConfiguration{\n\t\t\tRules: []*s3.LifecycleRule{\n\t\t\t\t{\n\t\t\t\t\tID: aws.String(\"cleanup-incomplete-multipart-registry-uploads\"),\n\t\t\t\t\tStatus: aws.String(\"Enabled\"),\n\t\t\t\t\tFilter: &s3.LifecycleRuleFilter{\n\t\t\t\t\t\tPrefix: aws.String(\"\"),\n\t\t\t\t\t},\n\t\t\t\t\tAbortIncompleteMultipartUpload: &s3.AbortIncompleteMultipartUpload{\n\t\t\t\t\t\tDaysAfterInitiation: aws.Int64(1),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, aerr.Code(), aerr.Error(), modified)\n\t\t} else {\n\t\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionFalse, \"Unknown Error Occurred\", err.Error(), modified)\n\t\t}\n\t} else {\n\t\tutil.UpdateCondition(cr, opapi.StorageIncompleteUploadCleanupEnabled, operatorapi.ConditionTrue, \"Enable Cleanup Successful\", \"Default cleanup of incomplete multipart uploads after one (1) day was successfully enabled\", modified)\n\t}\n\n\tcr.Status.Storage.State.S3 = d.Config\n\tcr.Status.Storage.Managed = true\n\n\tutil.UpdateCondition(cr, opapi.StorageExists, operatorapi.ConditionTrue, \"Creation Successful\", \"S3 bucket was successfully created\", modified)\n\n\treturn nil\n}", "func NewClient(kclient k8s.Client) (*Client, error) {\n\tctx := context.Background()\n\tsecret := &corev1.Secret{}\n\terr := kclient.Get(\n\t\tctx,\n\t\ttypes.NamespacedName{\n\t\t\tName: config.GCPSecretName,\n\t\t\tNamespace: config.OperatorNamespace,\n\t\t},\n\t\tsecret)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't get Secret with credentials %w\", err)\n\t}\n\tserviceAccountJSON, ok := secret.Data[\"service_account.json\"]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"access credentials missing service account\")\n\t}\n\n\t// initialize actual client\n\tc, err := newClient(ctx, serviceAccountJSON)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't create GCP client %s\", err)\n\t}\n\n\t// enchant the client with params required\n\tregion, err := getClusterRegion(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.region = region\n\n\tmasterList, err := baseutils.GetMasterMachines(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.masterList = masterList\n\tinfrastructureName, err := baseutils.GetClusterName(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.clusterName = infrastructureName\n\tbaseDomain, err := baseutils.GetClusterBaseDomain(kclient)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.baseDomain = baseDomain\n\n\treturn c, nil\n}", "func newCloudlyckeClient() *http.Client {\n\treturn &http.Client{}\n}", "func newFactory() func(config *client.Config) (client.Client, *probe.Error) {\n\tclientCache := make(map[uint32]minio.CloudStorageAPI)\n\tmutex := &sync.Mutex{}\n\n\t// Return New function.\n\treturn func(config *client.Config) (client.Client, *probe.Error) {\n\t\tu := client.NewURL(config.HostURL)\n\t\ttransport := http.DefaultTransport\n\t\tif config.Debug == true {\n\t\t\tif config.Signature == \"S3v4\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV4(), http.DefaultTransport)\n\t\t\t}\n\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\ttransport = httptracer.GetNewTraceTransport(NewTraceV2(), http.DefaultTransport)\n\t\t\t}\n\t\t}\n\n\t\t// New S3 configuration.\n\t\ts3Conf := minio.Config{\n\t\t\tAccessKeyID: config.AccessKey,\n\t\t\tSecretAccessKey: config.SecretKey,\n\t\t\tTransport: transport,\n\t\t\tEndpoint: u.Scheme + u.SchemeSeparator + u.Host,\n\t\t\tSignature: func() minio.SignatureType {\n\t\t\t\tif config.Signature == \"S3v2\" {\n\t\t\t\t\treturn minio.SignatureV2\n\t\t\t\t}\n\t\t\t\treturn minio.SignatureV4\n\t\t\t}(),\n\t\t}\n\n\t\ts3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)\n\n\t\t// Generate a hash out of s3Conf.\n\t\tconfHash := fnv.New32a()\n\t\tconfHash.Write([]byte(s3Conf.Endpoint + s3Conf.AccessKeyID + s3Conf.SecretAccessKey))\n\t\tconfSum := confHash.Sum32()\n\n\t\t// Lookup previous cache by hash.\n\t\tmutex.Lock()\n\t\tdefer mutex.Unlock()\n\t\tvar api minio.CloudStorageAPI\n\t\tfound := false\n\t\tif api, found = clientCache[confSum]; !found {\n\t\t\t// Not found. Instantiate a new minio client.\n\t\t\tvar e error\n\t\t\tapi, e = minio.New(s3Conf)\n\t\t\tif e != nil {\n\t\t\t\treturn nil, probe.NewError(e)\n\t\t\t}\n\t\t\t// Cache the new minio client with hash of config as key.\n\t\t\tclientCache[confSum] = api\n\t\t}\n\n\t\ts3Clnt := &s3Client{\n\t\t\tmu: new(sync.Mutex),\n\t\t\tapi: api,\n\t\t\thostURL: u,\n\t\t\tvirtualStyle: isVirtualHostStyle(u.Host),\n\t\t}\n\t\treturn s3Clnt, nil\n\t}\n}", "func getClient(auth *BasicAuth, storage Storage, w *Response) Client {\n\tclient, err := storage.GetClient(auth.Username)\n\tif err != nil {\n\t\tw.SetError(E_SERVER_ERROR, \"\")\n\t\tw.InternalError = err\n\t\treturn nil\n\t}\n\tif client == nil {\n\t\tw.SetError(E_UNAUTHORIZED_CLIENT, \"\")\n\t\treturn nil\n\t}\n\n\tif !CheckClientSecret(client, auth.Password) {\n\t\tw.SetError(E_UNAUTHORIZED_CLIENT, \"\")\n\t\treturn nil\n\t}\n\n\tif client.GetRedirectUri() == \"\" {\n\t\tw.SetError(E_UNAUTHORIZED_CLIENT, \"\")\n\t\treturn nil\n\t}\n\treturn client\n}", "func NewStorageTargetsClient(subscriptionID string, credential azcore.TokenCredential, options *arm.ClientOptions) (*StorageTargetsClient, error) {\n\tcl, err := arm.NewClient(moduleName+\".StorageTargetsClient\", moduleVersion, credential, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tclient := &StorageTargetsClient{\n\t\tsubscriptionID: subscriptionID,\n\t\tinternal: cl,\n\t}\n\treturn client, nil\n}", "func NewHTTPClient(ctx context.Context, clientSecretKeyFile []byte, tokenFilepath string) (*http.Client, error) {\n\tconfig, err := google.ConfigFromJSON(clientSecretKeyFile, builderAPIScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttokenCacheFilename := \"\"\n\tif tokenFilepath == \"\" {\n\t\ttokenCacheFilename, err = tokenCacheFile()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else {\n\t\ttokenCacheFilename = tokenFilepath\n\t}\n\tif !exists(tokenCacheFilename) {\n\t\tlog.Infoln(\"Could not locate OAuth2 token\")\n\t\treturn nil, errors.New(`command requires authentication. try to run \"gactions login\" first`)\n\t}\n\ttok, err := tokenFromFile(tokenCacheFilename)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn config.Client(ctx, tok), nil\n}", "func (ds *Datastore) client() *awsS3.S3 {\n\tif ds.s3 != nil {\n\t\treturn ds.s3\n\t}\n\n\tds.s3 = awsS3.New(session.New(&aws.Config{\n\t\tRegion: aws.String(ds.Region),\n\t\tCredentials: credentials.NewStaticCredentials(ds.accessKey, ds.accessSecret, ds.accessToken),\n\t}))\n\treturn ds.s3\n}", "func datastoreClient(ctx context.Context) (*datastore.Client, error) {\n\tid, err := metadata.ProjectID()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn datastore.NewClient(ctx, id)\n}", "func New(bucket string) (*Storage, error) {\n\tif bucket == \"\" {\n\t\treturn nil, errors.New(\"a bucket is required to create a storage\")\n\t}\n\n\tsess, err := session.NewSession()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Storage{\n\t\tsvc: s3.New(sess),\n\t\tuploader: s3manager.NewUploader(sess),\n\t\tdownloader: s3manager.NewDownloader(sess),\n\t\tBucket: bucket,\n\t}, nil\n}", "func NewGCSUploader(t testing.TB) *GCSUploader {\n\tmock := &GCSUploader{}\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}", "func getCloudCostClient() dbclient.CloudCostClient {\n\tvar cloudCost dbclient.CloudCostClient\n\n\tif strings.EqualFold(*cloud, \"azure\") {\n\t\tlog.Println(\"Initializing Azure client...\")\n\t\tazureClient := initAzureClient()\n\t\tcloudCost = &azureCloudCost{UsageExplorer: &azureClient}\n\t} else if strings.EqualFold(*cloud, \"aws\") {\n\t\tlog.Println(\"Initializing AWS client...\")\n\t\tawsClient := initAwsClient()\n\t\tcloudCost = &awsCloudCost{Client: &awsClient}\n\t} else {\n\t\tlog.Fatalf(\"Cloud provider \\\"%v\\\" is not supported\", *cloud)\n\t}\n\treturn cloudCost\n}", "func NewServiceClient(service string, opts *clientconfig.ClientOpts, transport *http.Transport, endpointType string) (*gophercloud.ServiceClient, error) {\n\tcloud := new(clientconfig.Cloud)\n\n\t// If no opts were passed in, create an empty ClientOpts.\n\tif opts == nil {\n\t\topts = new(clientconfig.ClientOpts)\n\t}\n\n\t// Determine if a clouds.yaml entry should be retrieved.\n\t// Start by figuring out the cloud name.\n\t// First check if one was explicitly specified in opts.\n\tvar cloudName string\n\tif opts.Cloud != \"\" {\n\t\tcloudName = opts.Cloud\n\t}\n\n\t// Next see if a cloud name was specified as an environment variable.\n\tenvPrefix := \"OS_\"\n\tif opts.EnvPrefix != \"\" {\n\t\tenvPrefix = opts.EnvPrefix\n\t}\n\n\tif v := os.Getenv(envPrefix + \"CLOUD\"); v != \"\" {\n\t\tcloudName = v\n\t}\n\n\t// If a cloud name was determined, try to look it up in clouds.yaml.\n\tif cloudName != \"\" {\n\t\t// Get the requested cloud.\n\t\tvar err error\n\t\tcloud, err = clientconfig.GetCloudFromYAML(opts)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Get a Provider Client\n\tpClient, err := AuthenticatedClient(opts, transport)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Determine the region to use.\n\t// First, check if the REGION_NAME environment variable is set.\n\tvar region string\n\tif v := os.Getenv(envPrefix + \"REGION_NAME\"); v != \"\" {\n\t\tregion = v\n\t}\n\n\t// Next, check if the cloud entry sets a region.\n\tif v := cloud.RegionName; v != \"\" {\n\t\tregion = v\n\t}\n\n\t// Finally, see if one was specified in the ClientOpts.\n\t// If so, this takes precedence.\n\tif v := opts.RegionName; v != \"\" {\n\t\tregion = v\n\t}\n\n\teo := gophercloud.EndpointOpts{\n\t\tRegion: region,\n\t\tAvailability: GetEndpointType(endpointType),\n\t}\n\n\t// Keep a map of the EndpointOpts for each service\n\tif endpointOpts == nil {\n\t\tendpointOpts = make(map[string]gophercloud.EndpointOpts)\n\t}\n\tendpointOpts[service] = eo\n\n\tswitch service {\n\tcase \"baremetal\":\n\t\treturn openstack.NewBareMetalV1(pClient, eo)\n\tcase \"clustering\":\n\t\treturn openstack.NewClusteringV1(pClient, eo)\n\tcase \"compute\":\n\t\treturn openstack.NewComputeV2(pClient, eo)\n\tcase \"container\":\n\t\treturn openstack.NewContainerV1(pClient, eo)\n\tcase \"container-infra\":\n\t\treturn openstack.NewContainerInfraV1(pClient, eo)\n\tcase \"database\":\n\t\treturn openstack.NewDBV1(pClient, eo)\n\tcase \"dns\":\n\t\treturn openstack.NewDNSV2(pClient, eo)\n\tcase \"gnocchi\":\n\t\treturn gnocchi.NewGnocchiV1(pClient, eo)\n\tcase \"identity\":\n\t\tidentityVersion := \"3\"\n\t\tif v := cloud.IdentityAPIVersion; v != \"\" {\n\t\t\tidentityVersion = v\n\t\t}\n\n\t\tswitch identityVersion {\n\t\tcase \"v2\", \"2\", \"2.0\":\n\t\t\treturn openstack.NewIdentityV2(pClient, eo)\n\t\tcase \"v3\", \"3\":\n\t\t\treturn openstack.NewIdentityV3(pClient, eo)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid identity API version\")\n\t\t}\n\tcase \"image\":\n\t\treturn openstack.NewImageServiceV2(pClient, eo)\n\tcase \"load-balancer\":\n\t\treturn openstack.NewLoadBalancerV2(pClient, eo)\n\tcase \"network\":\n\t\treturn openstack.NewNetworkV2(pClient, eo)\n\tcase \"object-store\":\n\t\treturn openstack.NewObjectStorageV1(pClient, eo)\n\tcase \"orchestration\":\n\t\treturn openstack.NewOrchestrationV1(pClient, eo)\n\tcase \"placement\":\n\t\treturn openstack.NewPlacementV1(pClient, eo)\n\tcase \"sharev2\":\n\t\treturn openstack.NewSharedFileSystemV2(pClient, eo)\n\tcase \"volume\":\n\t\tvolumeVersion := \"3\"\n\t\tif v := cloud.VolumeAPIVersion; v != \"\" {\n\t\t\tvolumeVersion = v\n\t\t}\n\n\t\tswitch volumeVersion {\n\t\tcase \"v1\", \"1\":\n\t\t\treturn openstack.NewBlockStorageV1(pClient, eo)\n\t\tcase \"v2\", \"2\":\n\t\t\treturn openstack.NewBlockStorageV2(pClient, eo)\n\t\tcase \"v3\", \"3\":\n\t\t\treturn openstack.NewBlockStorageV3(pClient, eo)\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"invalid volume API version\")\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"unable to create a service client for %s\", service)\n}", "func (c *Creator) New() (filestorage.FileStorage, error) {\n\tfs := New(c.apiKey, c.secret)\n\treturn fs, fs.SetBucket(c.defaultBucket)\n}", "func newMemClient(t *testing.T) drive.Client {\n\tc, err := drive.NewClient(drive.Config{Provider: \"memory\"})\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\treturn c\n}", "func GetStorageAPI(env cmds.Environment) *storage.API {\n\tce := env.(*Env)\n\treturn ce.storageAPI\n}", "func newStorage() *storage {\n\tr := make(map[string][]byte)\n\treturn &storage{\n\t\trepository: r,\n\t}\n}", "func initializeClient(ctx context.Context) (*compute.InstancesService, error) {\n\t// initialize google credentials from a custom environment variable\n\t// environment variables are not a secure way to share credentials to our application\n\t// and are only used here for the sake of convenience\n\t// we will store the content of our Google Developers Console client_credentials.json\n\t// as the value for GOOGLE_CREDENTIALS_JSON\n\tcredsJson := []byte(os.Getenv(\"GOOGLE_CREDENTIALS_JSON\"))\n\tcreds, err := google.CredentialsFromJSON(ctx, credsJson, compute.ComputeScope)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttoken := option.WithTokenSource(creds.TokenSource)\n\tsvc, err := compute.NewService(ctx, token)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tinstancesClient := compute.NewInstancesService(svc)\n\n\treturn instancesClient, nil\n}", "func (a *googlecloudstorageAdapter) Start(ctx context.Context) error {\n\ta.logger.Info(\"Starting Google Cloud Storage Adapter\")\n\treturn a.ceClient.StartReceiver(ctx, a.dispatch)\n}", "func NewGCPClient(config config.ConfigView, outputs terraform.Outputs, workingdir workingdir.IClient, stdout, stderr io.Writer, provider iaas.Provider, boshCLI boshcli.ICLI, versionFile []byte) (IClient, error) {\n\treturn &GCPClient{\n\t\tconfig: config,\n\t\toutputs: outputs,\n\t\tworkingdir: workingdir,\n\t\tstdout: stdout,\n\t\tstderr: stderr,\n\t\tprovider: provider,\n\t\tboshCLI: boshCLI,\n\t\tversionFile: versionFile,\n\t}, nil\n}", "func MakeHTTPStorage(\n\tbase string, settings *cluster.Settings, ioConf base.ExternalIODirConfig,\n) (cloud.ExternalStorage, error) {\n\tif base == \"\" {\n\t\treturn nil, errors.Errorf(\"HTTP storage requested but prefix path not provided\")\n\t}\n\n\tclient, err := makeHTTPClient(settings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\turi, err := url.Parse(base)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &httpStorage{\n\t\tbase: uri,\n\t\tclient: client,\n\t\thosts: strings.Split(uri.Host, \",\"),\n\t\tsettings: settings,\n\t\tioConf: ioConf,\n\t}, nil\n}", "func New(cfg config.StorageConfig) (*PgClient, *errors.Error) {\n\tctx, cancel := context.WithTimeout(context.Background(), cfg.GetTimeout())\n\tdefer cancel()\n\tpool, err := pg.Connect(ctx, cfg.GetConnStr())\n\tif err != nil {\n\t\treturn nil, errors.New(errors.InvalidConfigError, fmt.Sprintf(\"failed to connect pg: %v\", err))\n\t}\n\tDB := &PgClient{\n\t\tpool,\n\t\tcfg.GetTimeout(),\n\t}\n\treturn DB, nil\n}", "func NewClient(config *sdk.Config, credential *auth.Credential) *Client {\n\tvar handler sdk.RequestHandler = func(c *sdk.Client, req request.Common) (request.Common, error) {\n\t\terr := req.SetProjectId(PickResourceID(req.GetProjectId()))\n\t\treturn req, err\n\t}\n\tvar (\n\t\tuaccountClient = *uaccount.NewClient(config, credential)\n\t\tuhostClient = *uhost.NewClient(config, credential)\n\t\tunetClient = *unet.NewClient(config, credential)\n\t\tvpcClient = *vpc.NewClient(config, credential)\n\t\tudpnClient = *udpn.NewClient(config, credential)\n\t\tpathxClient = *pathx.NewClient(config, credential)\n\t\tudiskClient = *udisk.NewClient(config, credential)\n\t\tulbClient = *ulb.NewClient(config, credential)\n\t\tudbClient = *udb.NewClient(config, credential)\n\t\tumemClient = *umem.NewClient(config, credential)\n\t\tuphostClient = *uphost.NewClient(config, credential)\n\t\tpuhostClient = *puhost.NewClient(config, credential)\n\t\tpudbClient = *pudb.NewClient(config, credential)\n\t\tpumemClient = *pumem.NewClient(config, credential)\n\t\tppathxClient = *ppathx.NewClient(config, credential)\n\t)\n\n\tuaccountClient.Client.AddRequestHandler(handler)\n\tuhostClient.Client.AddRequestHandler(handler)\n\tunetClient.Client.AddRequestHandler(handler)\n\tvpcClient.Client.AddRequestHandler(handler)\n\tudpnClient.Client.AddRequestHandler(handler)\n\tpathxClient.Client.AddRequestHandler(handler)\n\tudiskClient.Client.AddRequestHandler(handler)\n\tulbClient.Client.AddRequestHandler(handler)\n\tudbClient.Client.AddRequestHandler(handler)\n\tumemClient.Client.AddRequestHandler(handler)\n\tuphostClient.Client.AddRequestHandler(handler)\n\tpuhostClient.Client.AddRequestHandler(handler)\n\tpudbClient.Client.AddRequestHandler(handler)\n\tpumemClient.Client.AddRequestHandler(handler)\n\tppathxClient.Client.AddRequestHandler(handler)\n\n\treturn &Client{\n\t\tuaccountClient,\n\t\tuhostClient,\n\t\tunetClient,\n\t\tvpcClient,\n\t\tudpnClient,\n\t\tpathxClient,\n\t\tudiskClient,\n\t\tulbClient,\n\t\tudbClient,\n\t\tumemClient,\n\t\tuphostClient,\n\t\tpuhostClient,\n\t\tpudbClient,\n\t\tpumemClient,\n\t\tppathxClient,\n\t}\n}" ]
[ "0.78624064", "0.7411373", "0.7383838", "0.7003476", "0.6808502", "0.6747555", "0.6728989", "0.67132545", "0.6611251", "0.6563249", "0.6547336", "0.6534237", "0.6530237", "0.65247536", "0.6501186", "0.64915437", "0.6470304", "0.64636487", "0.6445072", "0.64061564", "0.6383637", "0.6375237", "0.6330608", "0.62822974", "0.625803", "0.624611", "0.6206267", "0.6165597", "0.6144419", "0.6132393", "0.6121144", "0.6113594", "0.6109763", "0.6067885", "0.6047911", "0.60118353", "0.60045755", "0.6001241", "0.59950775", "0.59879524", "0.5982538", "0.5980881", "0.5977108", "0.5953381", "0.5938042", "0.5936961", "0.5926583", "0.59007996", "0.588538", "0.5871412", "0.5844173", "0.5843118", "0.57950133", "0.5759796", "0.57540196", "0.57452565", "0.5717539", "0.5687792", "0.568585", "0.56856656", "0.5676881", "0.5665165", "0.5648101", "0.56446844", "0.5643332", "0.5641008", "0.5633776", "0.5621566", "0.5615623", "0.5607198", "0.5597095", "0.5590947", "0.5585997", "0.5572643", "0.5567778", "0.55556476", "0.55504155", "0.5537642", "0.5526133", "0.55177695", "0.5513252", "0.55088365", "0.5504216", "0.5501903", "0.5480563", "0.5479976", "0.5473157", "0.54616624", "0.5452689", "0.54485613", "0.54475415", "0.5444194", "0.5443476", "0.54420984", "0.5435195", "0.543071", "0.5430262", "0.5427472", "0.54258275", "0.54226416" ]
0.55995315
70
Create a Workflow with one WorkflowBatch. The Protojobs are organized as follows (arrows point from top to bottom). 1 / \ 2 3 \ / 4 There are 2 workers. Each RDD has segments on both workers.
func MockDiamondWorkflow(hd *hood.Hood) *Workflow { workflow := MockWorkflow(hd) j1 := MockProtojob(hd, workflow) j2 := MockProtojob(hd, workflow) j3 := MockProtojob(hd, workflow) j4 := MockProtojob(hd, workflow) e1 := MockWorkflowEdge(hd, j1, j2) e2 := MockWorkflowEdge(hd, j1, j3) e3 := MockWorkflowEdge(hd, j2, j4) e4 := MockWorkflowEdge(hd, j3, j4) workflowBatch := MockWorkflowBatch(hd, workflow) rdd1 := MockRdd(hd, workflowBatch, j1) rdd2 := MockRdd(hd, workflowBatch, j2) rdd3 := MockRdd(hd, workflowBatch, j3) rdd4 := MockRdd(hd, workflowBatch, j4) MockRddEdge(hd, rdd1, rdd2, e1) MockRddEdge(hd, rdd1, rdd3, e2) MockRddEdge(hd, rdd2, rdd4, e3) MockRddEdge(hd, rdd3, rdd4, e4) w1 := MockWorker(hd) w2 := MockWorker(hd) // Place a segment for every rdd on every worker rdds := []*Rdd{rdd1, rdd2, rdd3, rdd4} workers := []*Worker{w1, w2} for _, rdd := range rdds { for _, worker := range workers { MockSegment(hd, rdd, worker) } } return workflow }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (workflow *Workflow) MakeBatch(hd *hood.Hood, start int64) *WorkflowBatch {\n\t// Create workflowBatch object\n\tbatch := &WorkflowBatch{\n\t\tWorkflowId: int64(workflow.Id),\n\t\tStartTime: start,\n\t}\n\tsaveOrPanic(hd, batch)\n\n\t// Create rdd objects\n\tpjToRdd := make(map[int64]int64)\n\trdds := make([]Rdd, 0)\n\tfor _, protojob := range workflow.GetProtojobs(hd) {\n\t\trdd := Rdd{\n\t\t\tWorkflowBatchId: int64(batch.Id),\n\t\t\tProtojobId: int64(protojob.Id),\n\t\t}\n\t\trdds = append(rdds, rdd)\n\t}\n\tsaveAllOrPanic(hd, &rdds)\n\tfor _, rdd := range rdds {\n\t\tpjToRdd[rdd.ProtojobId] = int64(rdd.Id)\n\t}\n\n\t// Create edges\n\tedges := make([]RddEdge, 0)\n\tfor _, workflowEdge := range workflow.GetWorkflowEdges(hd) {\n\t\t// Source rdd might be delayed\n\t\tif workflowEdge.Delay > 0 {\n\t\t\tsource_rdd := GetRddByStartTime(hd, workflowEdge.SourceJobId, start-int64(workflowEdge.Delay)*workflow.Duration)\n\t\t\tif source_rdd != nil {\n\t\t\t\trddEdge := RddEdge{\n\t\t\t\t\tSourceRddId: int64(source_rdd.Id),\n\t\t\t\t\tDestRddId: pjToRdd[workflowEdge.DestJobId],\n\t\t\t\t\tWorkflowEdgeId: int64(workflowEdge.Id),\n\t\t\t\t}\n\t\t\t\tedges = append(edges, rddEdge)\n\t\t\t}\n\t\t} else {\n\t\t\trddEdge := RddEdge{\n\t\t\t\tSourceRddId: pjToRdd[workflowEdge.SourceJobId],\n\t\t\t\tDestRddId: pjToRdd[workflowEdge.DestJobId],\n\t\t\t\tWorkflowEdgeId: int64(workflowEdge.Id),\n\t\t\t}\n\t\t\tedges = append(edges, rddEdge)\n\t\t}\n\t}\n\tsaveAllOrPanic(hd, &edges)\n\n\treturn batch\n}", "func NewBatch() *Batch {\n\treturn &Batch{}\n}", "func NewBatch() Batch {\n\treturn Batch{}\n}", "func New() Batch {\n\treturn make(Batch, 0)\n}", "func NewBatch(ctx context.Context, ds DAGService, opts ...BatchOption) *Batch {\n\tctx, cancel := context.WithCancel(ctx)\n\tbopts := defaultBatchOptions\n\tfor _, o := range opts {\n\t\to(&bopts)\n\t}\n\treturn &Batch{\n\t\tds: ds,\n\t\tctx: ctx,\n\t\tcancel: cancel,\n\t\tcommitResults: make(chan error, ParallelBatchCommits),\n\t\topts: bopts,\n\t}\n}", "func (svc *batchService) Create(id, owner []byte, normalisedBalance *big.Int, depth uint8) error {\n\tb := &postage.Batch{\n\t\tID: id,\n\t\tOwner: owner,\n\t\tValue: big.NewInt(0),\n\t\tStart: svc.storer.GetChainState().Block,\n\t\tDepth: depth,\n\t}\n\n\terr := svc.storer.Put(b, normalisedBalance, depth)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"put: %w\", err)\n\t}\n\n\tsvc.logger.Debugf(\"batch service: created batch id %s\", hex.EncodeToString(b.ID))\n\treturn nil\n}", "func New(ctx context.Context, flushHandler Func, flushMaxSize int, flushMaxWait time.Duration, workerSize int) *Batch {\n\tinstance := &Batch{\n\t\titems: make(map[string]TaskArgs),\n\t\tdoFn: flushHandler,\n\t\tmutex: &sync.RWMutex{},\n\n\t\tmaxSize: flushMaxSize,\n\t\tmaxWait: flushMaxWait,\n\n\t\tflushTasks: make(chan map[string]TaskArgs, workerSize),\n\t\tisRun: false,\n\n\t\tforceFlushChan: make(chan interface{}),\n\t\tinsertChan: make(chan TaskArgs),\n\t\tstopChan: make(chan bool),\n\t}\n\n\tinstance.setFlushWorker(ctx, workerSize)\n\tinstance.isRun = true\n\tgo instance.run()\n\treturn instance\n}", "func (ai *AppInteractor) CreateBatch(apps []domain.App) ([]string, error) {\n\treturn ai.AppRepository.CreateBatch(apps)\n}", "func initCheckpoint(keyspace string, vtworkers, excludeTables, sourceShards, destinationShards []string, minHealthyRdonlyTablets, splitCmd, splitDiffCmd, splitDiffDestTabletType string, useConsistentSnapshot string) (*workflowpb.WorkflowCheckpoint, error) {\n\ttasks := make(map[string]*workflowpb.Task)\n\tinitTasks(tasks, phaseCopySchema, destinationShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"source_shard\": sourceShards[0],\n\t\t\t\"destination_shard\": shard,\n\t\t\t\"exclude_tables\": strings.Join(excludeTables, \",\"),\n\t\t}\n\t})\n\tinitTasks(tasks, phaseClone, sourceShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"source_shard\": shard,\n\t\t\t\"min_healthy_rdonly_tablets\": minHealthyRdonlyTablets,\n\t\t\t\"split_cmd\": splitCmd,\n\t\t\t\"vtworker\": vtworkers[i],\n\t\t\t\"use_consistent_snapshot\": useConsistentSnapshot,\n\t\t\t\"exclude_tables\": strings.Join(excludeTables, \",\"),\n\t\t}\n\t})\n\tinitTasks(tasks, phaseWaitForFilteredReplication, destinationShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"destination_shard\": shard,\n\t\t}\n\t})\n\n\tswitch splitDiffCmd {\n\tcase \"SplitDiff\":\n\t\tinitTasks(tasks, phaseDiff, destinationShards, func(i int, shard string) map[string]string {\n\t\t\treturn map[string]string{\n\t\t\t\t\"keyspace\": keyspace,\n\t\t\t\t\"destination_shard\": shard,\n\t\t\t\t\"dest_tablet_type\": splitDiffDestTabletType,\n\t\t\t\t\"split_diff_cmd\": splitDiffCmd,\n\t\t\t\t\"vtworker\": vtworkers[i],\n\t\t\t\t\"use_consistent_snapshot\": useConsistentSnapshot,\n\t\t\t\t\"exclude_tables\": strings.Join(excludeTables, \",\"),\n\t\t\t}\n\t\t})\n\tcase \"MultiSplitDiff\":\n\t\tinitTasks(tasks, phaseDiff, sourceShards, func(i int, shard string) map[string]string {\n\t\t\treturn map[string]string{\n\t\t\t\t\"keyspace\": keyspace,\n\t\t\t\t\"source_shard\": shard,\n\t\t\t\t\"dest_tablet_type\": splitDiffDestTabletType,\n\t\t\t\t\"split_diff_cmd\": splitDiffCmd,\n\t\t\t\t\"vtworker\": vtworkers[i],\n\t\t\t\t\"use_consistent_snapshot\": useConsistentSnapshot,\n\t\t\t\t\"exclude_tables\": strings.Join(excludeTables, \",\"),\n\t\t\t}\n\t\t})\n\t}\n\n\tinitTasks(tasks, phaseMigrateRdonly, sourceShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"source_shard\": shard,\n\t\t\t\"served_type\": topodatapb.TabletType_RDONLY.String(),\n\t\t}\n\t})\n\tinitTasks(tasks, phaseMigrateReplica, sourceShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"source_shard\": shard,\n\t\t\t\"served_type\": topodatapb.TabletType_REPLICA.String(),\n\t\t}\n\t})\n\tinitTasks(tasks, phaseMigrateMaster, sourceShards, func(i int, shard string) map[string]string {\n\t\treturn map[string]string{\n\t\t\t\"keyspace\": keyspace,\n\t\t\t\"source_shard\": shard,\n\t\t\t\"served_type\": topodatapb.TabletType_MASTER.String(),\n\t\t}\n\t})\n\n\treturn &workflowpb.WorkflowCheckpoint{\n\t\tCodeVersion: codeVersion,\n\t\tTasks: tasks,\n\t\tSettings: map[string]string{\n\t\t\t\"source_shards\": strings.Join(sourceShards, \",\"),\n\t\t\t\"destination_shards\": strings.Join(destinationShards, \",\"),\n\t\t\t\"split_diff_cmd\": splitDiffCmd,\n\t\t},\n\t}, nil\n}", "func (batch *BatchTEL) Create() error {\n\t// generates sequence numbers and batch control\n\tif err := batch.build(); err != nil {\n\t\treturn err\n\t}\n\n\treturn batch.Validate()\n}", "func (db *FlatDatabase) NewBatch() *FlatBatch {\n\treturn &FlatBatch{db: db}\n}", "func (c *Client) NewBatch() *Batch {\n\treturn &Batch{\n\t\tc: c,\n\t}\n}", "func createBatch(xs []*storobj.Object) indexedBatch {\n\tvar bi indexedBatch\n\tbi.Data = xs\n\tbi.Index = make([]int, len(xs))\n\tfor i := 0; i < len(xs); i++ {\n\t\tbi.Index[i] = i\n\t}\n\treturn bi\n}", "func NewBatch(batchSize int) *Batch {\n\treturn &Batch{\n\t\tmaxSize: batchSize,\n\t\tmutex: &sync.Mutex{},\n\t}\n}", "func newBatch(t *testing.T, flgs []bool, ts []types.Type, proc *process.Process, rows int64) *batch.Batch {\n\treturn testutil.NewBatch(ts, false, int(rows), proc.Mp())\n}", "func (db *TriasDB) NewBatch() Batch {\n\tdb.mtx.Lock()\n\tdefer db.mtx.Unlock()\n\n\tpanic(\"TriasDB.NewBatch not yet implemented\")\n}", "func NewBatch(a *TMStore) *Batch {\n\treturn &Batch{bufferedbatch.NewBatch(a), a}\n}", "func TestLinearFlow(t *testing.T) {\n\trequire := require.New(t)\n\n\tt.Run(`Given a workflow with two sequential jobs,\n\twhen the work runs,\n\tthen all works well`, func(t *testing.T) {\n\n\t\t// Create the workflow workers\n\t\tjob1 := func(ctx context.Context, postman main.Postman) {\n\t\t\tv, err := postman.Receive(ctx)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif v != nil {\n\t\t\t\tfor !postman.Send(ctx, *v) {\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tw1In := make(chan main.Param)\n\t\tw1 := main.NewWorker(\n\t\t\tnil,\n\t\t\tjob1,\n\t\t\tmain.NameWOpt(\"w1\"),\n\t\t\tmain.AddOrphanInWOpt(w1In),\n\t\t\tmain.ErrHndFuncWOpt(errHndFunc),\n\t\t\tmain.AddInfoFuncWOpt(main.Infof),\n\t\t)\n\n\t\toutGraphChan := make(chan main.Param)\n\t\tjob2 := func(ctx context.Context, postman main.Postman) {\n\t\t\tv, err := postman.Receive(ctx)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Println(err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif v != nil {\n\t\t\t\toutGraphChan <- *v\n\t\t\t}\n\t\t}\n\t\tw2 := main.NewWorker(\n\t\t\t[]*main.Worker{&w1},\n\t\t\tjob2,\n\t\t\tmain.NameWOpt(\"w2\"),\n\t\t\tmain.ErrHndFuncWOpt(errHndFunc),\n\t\t\tmain.AddInfoFuncWOpt(main.Infof),\n\t\t)\n\n\t\t// Create the workflow and add the workers\n\t\tctx, cancelFunc := context.WithCancel(context.Background())\n\t\tflow := main.NewFlow(ctx, main.AddInfoFuncFOpt(main.Infof))\n\t\tflow.AddWorker(w1)\n\t\tflow.AddWorker(w2)\n\n\t\t// Start workflow workers\n\t\tflow.Run()\n\n\t\t// Fixture data to feed the workflow\n\t\tvalues := []main.Param{\n\t\t\t{Value: float64(10)},\n\t\t\t{Value: float64(32)},\n\t\t\t{Value: math.MaxFloat64},\n\t\t\t{Value: float64(999999)},\n\t\t\t{Value: float64(-45)},\n\t\t\t{Value: float64(100)},\n\t\t}\n\n\t\t// This goroutine implements a consumer for the workflow output\n\t\tvar (\n\t\t\tallValuesReceivedChan = make(chan struct{})\n\t\t\treceivedValues []main.Param\n\t\t)\n\t\tgo func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ctx.Done():\n\t\t\t\t\treturn\n\t\t\t\tcase p, ok := <-outGraphChan:\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\treturn\n\t\t\t\t\t}\n\t\t\t\t\treceivedValues = append(receivedValues, p)\n\t\t\t\t\tif len(receivedValues) == len(values) {\n\t\t\t\t\t\tclose(allValuesReceivedChan)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}()\n\n\t\t// Feed the workflow\n\t\tfor _, value := range values {\n\t\t\tw1In <- value\n\t\t}\n\n\t\t// Wait for all fixtures processed\n\t\t<-allValuesReceivedChan\n\n\t\t// Finish the workflow\n\t\tcancelFunc()\n\t\tflow.Kill()\n\n\t\trequire.Equal(values, receivedValues)\n\t})\n}", "func NewWorkflow(steps []*Step) *Workflow {\n\tstepsMap := make(map[string]*Step, len(steps))\n\tworkflow := Workflow{stepsMap}\n\n\treturn workflow.AddStep(steps...)\n}", "func (m *Manager) Create(ctx context.Context, factoryName string, args []string) (string, error) {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t// Find the factory.\n\tfactory, ok := factories[factoryName]\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"no factory named %v is registered\", factoryName)\n\t}\n\n\tuuid, err := gouuid.NewUUID()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Create the initial workflowpb.Workflow object.\n\tw := &workflowpb.Workflow{\n\t\tUuid: uuid.String(),\n\t\tCreateTime: time.Now().UnixNano(),\n\t\tFactoryName: factoryName,\n\t\tState: workflowpb.WorkflowState_NotStarted,\n\t}\n\n\t// Let the factory parse the parameters and initialize the\n\t// object.\n\tif err := factory.Init(m, w, args); err != nil {\n\t\treturn \"\", err\n\t}\n\trw, err := m.instantiateWorkflow(w)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// Now save the workflow in the topo server.\n\trw.wi, err = m.ts.CreateWorkflow(ctx, w)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\t// And we're done.\n\tlog.Infof(\"Created workflow %s (%s, %s)\", w.Uuid, factoryName, w.Name)\n\treturn w.Uuid, nil\n}", "func (db *LDB) NewBatch() Batch {\n return &LDBBatch{\n db: db.db,\n batch: new(leveldb.Batch),\n }\n}", "func (b *CreateBatchesFromFiltersWorker) Process(message *workers.Msg) {\n\tarr, err := message.Args().Array()\n\tcheckErr(b.Logger, err)\n\tjobID := arr[0]\n\tid, err := uuid.FromString(jobID.(string))\n\tcheckErr(b.Logger, err)\n\tl := b.Logger.With(\n\t\tzap.Int(\"dbPageSize\", b.DBPageSize),\n\t\tzap.String(\"jobID\", id.String()),\n\t)\n\tl.Info(\"starting create_batches_using_filters_worker\")\n\tjob := &model.Job{\n\t\tID: id,\n\t}\n\terr = b.MarathonDB.DB.Model(job).Column(\"job.*\", \"App\").Where(\"job.id = ?\", job.ID).Select()\n\tcheckErr(l, err)\n\tif job.Status == stoppedJobStatus {\n\t\tl.Info(\"stopped job create_batches_using_filters_worker\")\n\t\treturn\n\t}\n\tcsvBuffer := &bytes.Buffer{}\n\tcsvWriter := io.Writer(csvBuffer)\n\terr = b.createBatchesFromFilters(job, &csvWriter)\n\tcheckErr(l, err)\n\tcsvBytes := csvBuffer.Bytes()\n\tb.sendCSVToS3AndCreateCreateBatchesJob(&csvBytes, job)\n\tl.Info(\"finished create_batches_using_filters_worker\")\n}", "func NewBatch(lines []string) span.Batcher {\n\tbatch := span.Batcher{\n\t\tApply: func(s interface{}) (span.Importer, error) {\n\t\t\tdoc := new(Document)\n\t\t\terr := json.Unmarshal([]byte(s.(string)), doc)\n\t\t\tif err != nil {\n\t\t\t\treturn doc, err\n\t\t\t}\n\t\t\treturn doc, nil\n\t\t}, Items: make([]interface{}, len(lines))}\n\tfor i, line := range lines {\n\t\tbatch.Items[i] = line\n\t}\n\treturn batch\n}", "func NewWorkflow(option WorkflowOption) (*Workflow, error) {\n\tblobsDir := filepath.Join(option.TargetDir, \"blobs\")\n\tif err := os.RemoveAll(blobsDir); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Remove blob directory\")\n\t}\n\tif err := os.MkdirAll(blobsDir, 0755); err != nil {\n\t\treturn nil, errors.Wrap(err, \"Create blob directory\")\n\t}\n\n\tbackendConfig := fmt.Sprintf(`{\"dir\": \"%s\"}`, blobsDir)\n\tbuilder := NewBuilder(option.NydusImagePath)\n\n\tdebugJSONPath := filepath.Join(option.TargetDir, \"output.json\")\n\n\tif option.PrefetchDir == \"\" {\n\t\toption.PrefetchDir = \"/\"\n\t}\n\n\treturn &Workflow{\n\t\tWorkflowOption: option,\n\t\tblobsDir: blobsDir,\n\t\tbackendConfig: backendConfig,\n\t\tbuilder: builder,\n\t\tdebugJSONPath: debugJSONPath,\n\t}, nil\n}", "func (db *memorydb) NewBatch() storage.Batch {\n\treturn &mbatch{\n\t\tmemorydb: db,\n\t}\n}", "func (c *Client) CreateBatch(data *CreateBatchParams) (*xendit.BatchDisbursement, *xendit.Error) {\n\treturn c.CreateBatchWithContext(context.Background(), data)\n}", "func NewBatch(docs []*Document) span.Batcher {\n\tbatch := span.Batcher{\n\t\tApply: func(s interface{}) (span.Importer, error) {\n\t\t\treturn s.(span.Importer), nil\n\t\t}, Items: make([]interface{}, len(docs))}\n\tfor i, doc := range docs {\n\t\tbatch.Items[i] = doc\n\t}\n\treturn batch\n}", "func New(c remoteworkflowapi.Config) *WorkflowAPI {\n\n\treturn &WorkflowAPI{\n\t\tc: c,\n\t}\n\n}", "func ToBatch(data []byte) *Batch {\n\treturn (*Batch)(unsafe.Pointer(&data[0]))\n}", "func (d TinkDB) CreateWorkflow(ctx context.Context, wf Workflow, data string, id uuid.UUID) error {\n\ttx, err := d.instance.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"BEGIN transaction\")\n\t}\n\n\terr = insertActionList(ctx, d.instance, data, id, tx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create workflow\")\n\n\t}\n\terr = insertInWorkflow(ctx, d.instance, wf, tx)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"failed to create workflow\")\n\n\t}\n\terr = tx.Commit()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"COMMIT\")\n\t}\n\treturn nil\n}", "func NewBatchStrategy(serializer Serializer, batchWait time.Duration) Strategy {\n\treturn &batchStrategy{\n\t\tbuffer: NewMessageBuffer(maxBatchSize, maxContentSize),\n\t\tserializer: serializer,\n\t\tbatchWait: batchWait,\n\t}\n}", "func (d DB) CreateWorkflow(ctx context.Context, wf db.Workflow, data string, id uuid.UUID) error {\n\treturn nil\n}", "func FirstWorkflow(context *endly.Context) *model.Process {\n\tvar processes = processes(context)\n\treturn processes.FirstWorkflow()\n}", "func NewBatch(text *string) *Batch {\n\tbatch := Batch{text: text}\n\tbatch.BatchAnnotate([]AnnotationRule{annotateBuffer, annotateLines, annotateWords})\n\treturn &batch\n}", "func NewBatch(b engine.Batch, spans *SpanSet) engine.Batch {\n\treturn &spanSetBatch{\n\t\tmakeSpanSetReadWriter(b, spans),\n\t\tb,\n\t\tspans,\n\t}\n}", "func newBatch(evts []*evtsapi.Event, offset *events.Offset) (events.Batch, error) {\n\tif offset == nil {\n\t\treturn nil, fmt.Errorf(\"cannot create a batch with nil offset\")\n\t}\n\treturn &batch{evts: evts, offset: offset}, nil\n}", "func (db *Database) NewBatch() database.Batch {\n\treturn &batch{db: db}\n}", "func (w *WorkflowInstance) Create(trs *db.Transaction) error {\n\tid, err := db.InsertStructTx(trs.Tx, constants.TableCoreBPMInstances, w)\n\tif err != nil {\n\t\treturn customerror.New(http.StatusInternalServerError, \"workflow instance create\", err.Error())\n\t}\n\tw.ID = id\n\treturn nil\n}", "func (self *StateStore) NewBatch() {\n\tself.store.NewBatch()\n}", "func (db *Database) NewBatch() database.Batch {\n\tb := grocksdb.NewWriteBatch()\n\truntime.SetFinalizer(b, func(b *grocksdb.WriteBatch) {\n\t\tb.Destroy()\n\t})\n\treturn &batch{\n\t\tbatch: b,\n\t\tdb: db,\n\t}\n}", "func (*Factory) Instantiate(m *workflow.Manager, w *workflowpb.Workflow, rootNode *workflow.Node) (workflow.Workflow, error) {\n\trootNode.Message = \"This is a workflow to execute horizontal resharding automatically.\"\n\n\tcheckpoint := &workflowpb.WorkflowCheckpoint{}\n\tif err := proto.Unmarshal(w.Data, checkpoint); err != nil {\n\t\treturn nil, err\n\t}\n\n\tphaseEnableApprovals := make(map[string]bool)\n\tfor _, phase := range parsePhaseEnableApprovals(checkpoint.Settings[\"phase_enable_approvals\"]) {\n\t\tphaseEnableApprovals[phase] = true\n\t}\n\n\thw := &horizontalReshardingWorkflow{\n\t\tcheckpoint: checkpoint,\n\t\trootUINode: rootNode,\n\t\tlogger: logutil.NewMemoryLogger(),\n\t\twr: wrangler.New(logutil.NewConsoleLogger(), m.TopoServer(), tmclient.NewTabletManagerClient()),\n\t\ttopoServer: m.TopoServer(),\n\t\tmanager: m,\n\t\tphaseEnableApprovals: phaseEnableApprovals,\n\t}\n\tcopySchemaUINode := &workflow.Node{\n\t\tName: \"CopySchemaShard\",\n\t\tPathName: string(phaseCopySchema),\n\t}\n\tcloneUINode := &workflow.Node{\n\t\tName: \"SplitClone\",\n\t\tPathName: string(phaseClone),\n\t}\n\twaitForFilteredReplicationUINode := &workflow.Node{\n\t\tName: \"WaitForFilteredReplication\",\n\t\tPathName: string(phaseWaitForFilteredReplication),\n\t}\n\n\tdiffUINode := &workflow.Node{\n\t\tName: checkpoint.Settings[\"split_diff_cmd\"],\n\t\tPathName: string(phaseDiff),\n\t}\n\n\tmigrateRdonlyUINode := &workflow.Node{\n\t\tName: \"MigrateServedTypeRDONLY\",\n\t\tPathName: string(phaseMigrateRdonly),\n\t}\n\tmigrateReplicaUINode := &workflow.Node{\n\t\tName: \"MigrateServedTypeREPLICA\",\n\t\tPathName: string(phaseMigrateReplica),\n\t}\n\tmigrateMasterUINode := &workflow.Node{\n\t\tName: \"MigrateServedTypeMASTER\",\n\t\tPathName: string(phaseMigrateMaster),\n\t}\n\n\thw.rootUINode.Children = []*workflow.Node{\n\t\tcopySchemaUINode,\n\t\tcloneUINode,\n\t\twaitForFilteredReplicationUINode,\n\t\tdiffUINode,\n\t\tmigrateRdonlyUINode,\n\t\tmigrateReplicaUINode,\n\t\tmigrateMasterUINode,\n\t}\n\n\tsourceShards := strings.Split(hw.checkpoint.Settings[\"source_shards\"], \",\")\n\tdestinationShards := strings.Split(hw.checkpoint.Settings[\"destination_shards\"], \",\")\n\n\tif err := createUINodes(hw.rootUINode, phaseCopySchema, destinationShards); err != nil {\n\t\treturn hw, err\n\t}\n\tif err := createUINodes(hw.rootUINode, phaseClone, sourceShards); err != nil {\n\t\treturn hw, err\n\t}\n\tif err := createUINodes(hw.rootUINode, phaseWaitForFilteredReplication, destinationShards); err != nil {\n\t\treturn hw, err\n\t}\n\tvar shardsToUseForDiff []string\n\n\tswitch hw.checkpoint.Settings[\"split_diff_cmd\"] {\n\tcase \"SplitDiff\":\n\t\tshardsToUseForDiff = destinationShards\n\tcase \"MultiSplitDiff\":\n\t\tshardsToUseForDiff = sourceShards\n\t}\n\n\tif err := createUINodes(hw.rootUINode, phaseDiff, shardsToUseForDiff); err != nil {\n\t\treturn hw, err\n\t}\n\n\tif err := createUINodes(hw.rootUINode, phaseMigrateRdonly, sourceShards); err != nil {\n\t\treturn hw, err\n\t}\n\tif err := createUINodes(hw.rootUINode, phaseMigrateReplica, sourceShards); err != nil {\n\t\treturn hw, err\n\t}\n\tif err := createUINodes(hw.rootUINode, phaseMigrateMaster, sourceShards); err != nil {\n\t\treturn hw, err\n\t}\n\n\treturn hw, nil\n}", "func (m *Manager) Start(ctx context.Context, uuid string) error {\n\tm.mu.Lock()\n\tdefer m.mu.Unlock()\n\n\t// Check the manager is running.\n\tif m.ctx == nil {\n\t\treturn fmt.Errorf(\"manager not running\")\n\t}\n\n\trw, ok := m.workflows[uuid]\n\tif !ok {\n\t\treturn fmt.Errorf(\"cannot find workflow %v in the workflow list\", uuid)\n\t}\n\n\tif rw.wi.State != workflowpb.WorkflowState_NotStarted {\n\t\treturn fmt.Errorf(\"workflow with uuid %v is in state %v\", uuid, rw.wi.State)\n\t}\n\n\t// Change its state in the topo server. Note we do that first,\n\t// so if the running part fails, we will retry next time.\n\trw.wi.State = workflowpb.WorkflowState_Running\n\trw.wi.StartTime = time.Now().Unix()\n\tif err := m.ts.SaveWorkflow(ctx, rw.wi); err != nil {\n\t\treturn err\n\t}\n\n\trw.rootNode.State = workflowpb.WorkflowState_Running\n\trw.rootNode.BroadcastChanges(false /* updateChildren */)\n\n\tm.runWorkflow(rw)\n\treturn nil\n}", "func NewBatchWriter(persister persist.CheckpointPersister, writer io.Writer) (*batchWriter, error) {\n\treturn &batchWriter{\n\t\tpersister: persister,\n\t\twriter: writer,\n\t\tbatchSize: batchSize,\n\t\tbatch: make([]string, 0, batchSize),\n\t\tpersistRecords: make([]*persistRecord, 0, batchSize),\n\t}, nil\n}", "func (acb *ActivityCreateBulk) Save(ctx context.Context) ([]*Activity, error) {\n\tspecs := make([]*sqlgraph.CreateSpec, len(acb.builders))\n\tnodes := make([]*Activity, len(acb.builders))\n\tmutators := make([]Mutator, len(acb.builders))\n\tfor i := range acb.builders {\n\t\tfunc(i int, root context.Context) {\n\t\t\tbuilder := acb.builders[i]\n\t\t\tvar mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {\n\t\t\t\tmutation, ok := m.(*ActivityMutation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unexpected mutation type %T\", m)\n\t\t\t\t}\n\t\t\t\tif err := builder.check(); err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tbuilder.mutation = mutation\n\t\t\t\tnodes[i], specs[i] = builder.createSpec()\n\t\t\t\tvar err error\n\t\t\t\tif i < len(mutators)-1 {\n\t\t\t\t\t_, err = mutators[i+1].Mutate(root, acb.builders[i+1].mutation)\n\t\t\t\t} else {\n\t\t\t\t\t// Invoke the actual operation on the latest mutation in the chain.\n\t\t\t\t\tif err = sqlgraph.BatchCreate(ctx, acb.driver, &sqlgraph.BatchCreateSpec{Nodes: specs}); err != nil {\n\t\t\t\t\t\tif cerr, ok := isSQLConstraintError(err); ok {\n\t\t\t\t\t\t\terr = cerr\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmutation.done = true\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tid := specs[i].ID.Value.(int64)\n\t\t\t\tnodes[i].ID = int(id)\n\t\t\t\treturn nodes[i], nil\n\t\t\t})\n\t\t\tfor i := len(builder.hooks) - 1; i >= 0; i-- {\n\t\t\t\tmut = builder.hooks[i](mut)\n\t\t\t}\n\t\t\tmutators[i] = mut\n\t\t}(i, ctx)\n\t}\n\tif len(mutators) > 0 {\n\t\tif _, err := mutators[0].Mutate(ctx, acb.builders[0].mutation); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\treturn nodes, nil\n}", "func CreateBatch(sprites map[string]*pixel.Sprite, pic pixel.Picture) (*pixel.Batch, []pixel.Rect) {\n\tbatch := pixel.NewBatch(&pixel.TrianglesData{}, pic)\n\tcollisions := []pixel.Rect{}\n\n\tDrawRiver(batch)\n\n\tassetsF, err := bindata.Asset(assetPlacementPath)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tcsvFile := csv.NewReader(bytes.NewReader(assetsF))\n\tfor {\n\t\tasset, err := csvFile.Read()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatal(err)\n\t\t}\n\t\tname := asset[0]\n\t\tvX, _ := strconv.ParseFloat(asset[1], 64)\n\t\tvY, _ := strconv.ParseFloat(asset[2], 64)\n\t\tcollides := asset[3] == \"true\"\n\n\t\tv := pixel.V(vX, vY)\n\t\tsprites[name].Draw(batch, pixel.IM.Moved(v))\n\n\t\tif collides {\n\t\t\tr := TranslateRect(sprites[name], v)\n\t\t\tcollisions = append(collisions, r)\n\t\t}\n\t}\n\n\treturn batch, collisions\n}", "func (this *AccountStore) NewBatch() {\n\tthis.store.NewBatch()\n}", "func (store *Engine) CreateWorkflow(workflow *Workflow) (string, error) {\n\tvar id struct {\n\t\tID string `json:\"id\"`\n\t}\n\n\t_, err := store.api.\n\t\tURL(\"/workflow-engine/api/v1/workflows\").\n\t\tPost(&workflow, &id)\n\n\treturn id.ID, err\n}", "func NewBatch(docs []doc.Metadata, opts ...BatchOption) Batch {\n\tb := Batch{Docs: docs}\n\n\tfor _, opt := range opts {\n\t\tb = opt.apply(b)\n\t}\n\n\treturn b\n}", "func New(stateStore storage.StateStorer, storer postage.Storer, logger logging.Logger, listener postage.Listener) Interface {\n\treturn &batchService{stateStore, storer, logger, listener}\n}", "func (r *ProjectsNotesService) BatchCreate(parent string, batchcreatenotesrequest *BatchCreateNotesRequest) *ProjectsNotesBatchCreateCall {\n\tc := &ProjectsNotesBatchCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.batchcreatenotesrequest = batchcreatenotesrequest\n\treturn c\n}", "func (s *Session) NewBatch(typ gocql.BatchType) *Batch {\n\tb := s.Session.NewBatch(typ)\n\treturn wrapBatch(b, s.hosts, s.opts...)\n}", "func NewCreateBatchesFromFiltersWorker(config *viper.Viper, logger zap.Logger, workers *Worker) *CreateBatchesFromFiltersWorker {\n\tb := &CreateBatchesFromFiltersWorker{\n\t\tConfig: config,\n\t\tLogger: logger.With(zap.String(\"worker\", \"CreateBatchesFromFiltersWorker\")),\n\t\tWorkers: workers,\n\t}\n\tb.configure()\n\tb.Logger.Debug(\"Configured CreateBatchesFromFiltersWorker successfully\")\n\treturn b\n}", "func (m *Model) NewProc(ctx nn.Context) nn.Processor {\n\tprocLayers := make([]nn.Processor, len(m.Layers))\n\tfor i, layer := range m.Layers {\n\t\tprocLayers[i] = layer.NewProc(ctx)\n\t}\n\treturn &Processor{\n\t\tBaseProcessor: nn.BaseProcessor{\n\t\t\tModel: m,\n\t\t\tMode: ctx.Mode,\n\t\t\tGraph: ctx.Graph,\n\t\t\tFullSeqProcessing: requiresFullSeq(procLayers),\n\t\t},\n\t\tLayers: procLayers,\n\t}\n}", "func CreateWorkers(n int) ([]raft.FSM) {\n workers := make([]*WorkerFSM, n)\n for i := range workers {\n workers[i] = &WorkerFSM{\n KeyValMap: make(map[string]string),\n counter: 0,\n }\n }\n fsms := make([]raft.FSM, n)\n for i, w := range workers {\n fsms[i] = w\n }\n return fsms\n}", "func NewWorkflow(ctx *pulumi.Context,\n\tname string, args *WorkflowArgs, opts ...pulumi.ResourceOption) (*Workflow, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.WorkflowId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'WorkflowId'\")\n\t}\n\treplaceOnChanges := pulumi.ReplaceOnChanges([]string{\n\t\t\"location\",\n\t\t\"project\",\n\t\t\"workflowId\",\n\t})\n\topts = append(opts, replaceOnChanges)\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Workflow\n\terr := ctx.RegisterResource(\"google-native:workflows/v1beta:Workflow\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (r *Repository) CreateInBatch(db *gorm.DB, i interface{}, batchSize int) error {\n\treturn db.Omit(clause.Associations).CreateInBatches(i, batchSize).Error\n}", "func (c *Collection) NewBatch(ctx context.Context) (*Batch, error) {\n\ttr := transaction.New(ctx)\n\n\tret := new(Batch)\n\tret.c = c\n\tret.tr = tr\n\n\treturn ret, nil\n}", "func (r *AccountsUserLinksService) BatchCreate(parent string, googleanalyticsadminv1alphabatchcreateuserlinksrequest *GoogleAnalyticsAdminV1alphaBatchCreateUserLinksRequest) *AccountsUserLinksBatchCreateCall {\n\tc := &AccountsUserLinksBatchCreateCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.googleanalyticsadminv1alphabatchcreateuserlinksrequest = googleanalyticsadminv1alphabatchcreateuserlinksrequest\n\treturn c\n}", "func (s *TestBase) CreateWorkflowExecutionManyTasks(domainID string, workflowExecution workflow.WorkflowExecution,\n\ttaskList string, executionContext []byte, nextEventID int64, lastProcessedEventID int64,\n\tdecisionScheduleIDs []int64, activityScheduleIDs []int64) (*p.CreateWorkflowExecutionResponse, error) {\n\n\ttransferTasks := []p.Task{}\n\tfor _, decisionScheduleID := range decisionScheduleIDs {\n\t\ttransferTasks = append(transferTasks,\n\t\t\t&p.DecisionTask{\n\t\t\t\tTaskID: s.GetNextSequenceNumber(),\n\t\t\t\tDomainID: domainID,\n\t\t\t\tTaskList: taskList,\n\t\t\t\tScheduleID: int64(decisionScheduleID),\n\t\t\t})\n\t}\n\n\tfor _, activityScheduleID := range activityScheduleIDs {\n\t\ttransferTasks = append(transferTasks,\n\t\t\t&p.ActivityTask{\n\t\t\t\tTaskID: s.GetNextSequenceNumber(),\n\t\t\t\tDomainID: domainID,\n\t\t\t\tTaskList: taskList,\n\t\t\t\tScheduleID: int64(activityScheduleID),\n\t\t\t})\n\t}\n\n\tresponse, err := s.ExecutionManager.CreateWorkflowExecution(&p.CreateWorkflowExecutionRequest{\n\t\tNewWorkflowSnapshot: p.WorkflowSnapshot{\n\t\t\tExecutionInfo: &p.WorkflowExecutionInfo{\n\t\t\t\tCreateRequestID: uuid.New(),\n\t\t\t\tDomainID: domainID,\n\t\t\t\tWorkflowID: workflowExecution.GetWorkflowId(),\n\t\t\t\tRunID: workflowExecution.GetRunId(),\n\t\t\t\tTaskList: taskList,\n\t\t\t\tExecutionContext: executionContext,\n\t\t\t\tState: p.WorkflowStateRunning,\n\t\t\t\tCloseStatus: p.WorkflowCloseStatusNone,\n\t\t\t\tLastFirstEventID: common.FirstEventID,\n\t\t\t\tNextEventID: nextEventID,\n\t\t\t\tLastProcessedEvent: lastProcessedEventID,\n\t\t\t\tDecisionScheduleID: common.EmptyEventID,\n\t\t\t\tDecisionStartedID: common.EmptyEventID,\n\t\t\t\tDecisionTimeout: 1,\n\t\t\t},\n\t\t\tExecutionStats: &p.ExecutionStats{},\n\t\t\tTransferTasks: transferTasks,\n\t\t},\n\t\tRangeID: s.ShardInfo.RangeID,\n\t})\n\n\treturn response, err\n}", "func (h *Handler) CreateJobs(data []string) {\n\tbatchSize := 3\n\n\tfor start := 0; start < len(data); start += batchSize {\n\t\tend := start + batchSize\n\n\t\tif end > len(data) {\n\t\t\tend = len(data) - 1\n\t\t}\n\t\tjobs <- data[start:end]\n\t}\n\tclose(jobs)\n}", "func (c *Client) CreateBatchPrediction(ctx context.Context, params *CreateBatchPredictionInput, optFns ...func(*Options)) (*CreateBatchPredictionOutput, error) {\n\tif params == nil {\n\t\tparams = &CreateBatchPredictionInput{}\n\t}\n\n\tresult, metadata, err := c.invokeOperation(ctx, \"CreateBatchPrediction\", params, optFns, addOperationCreateBatchPredictionMiddlewares)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tout := result.(*CreateBatchPredictionOutput)\n\tout.ResultMetadata = metadata\n\treturn out, nil\n}", "func Example_splitToBatch() {\n\tconf := NewConfig()\n\n\tconf.Input.Type = input.TypeKafka\n\tconf.Input.Kafka.Addresses = []string{\n\t\t\"localhost:9092\",\n\t}\n\tconf.Input.Kafka.Topic = \"example_topic_one\"\n\n\tconf.Output.Type = output.TypeKafka\n\tconf.Output.Kafka.Addresses = []string{\n\t\t\"localhost:9092\",\n\t}\n\tconf.Output.Kafka.Topic = \"example_topic_two\"\n\n\ts, err := New(conf, OptAddProcessors(func() (types.Processor, error) {\n\t\treturn SplitToBatch{}, nil\n\t}))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tdefer s.Stop(time.Second)\n\n\tsigChan := make(chan os.Signal, 1)\n\tsignal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)\n\n\t// Wait for termination signal\n\t<-sigChan\n\n\tlog.Println(\"Received SIGTERM, the service is closing.\")\n}", "func (rdd *Rdd) CreateSegments(hd *hood.Hood) ([]*Segment, []*SegmentCopy) {\n\tpj := rdd.GetProtojob(hd)\n\tsegments := make([]*Segment, pj.NumSegments)\n\tsegmentCopies := make([]*SegmentCopy, pj.NumSegments*pj.Copies)\n\tfor i := 0; i < pj.NumSegments; i++ {\n\t\ts := &Segment{\n\t\t\tRddId: int64(rdd.Id),\n\t\t\tWorkerId: 0,\n\t\t\tStatus: 0,\n\t\t\tIndex: i,\n\t\t}\n\t\tsaveOrPanic(hd, s)\n\t\tsegments[i] = s\n\t\tfor j := 0; j < pj.Copies; j++ {\n\t\t\tc := &SegmentCopy{\n\t\t\t\tSegmentId: int64(s.Id),\n\t\t\t\tWorkerId: 0,\n\t\t\t\tStatus: 0,\n\t\t\t}\n\t\t\tsaveOrPanic(hd, c)\n\t\t\tsegmentCopies[i*pj.Copies+j] = c\n\t\t}\n\t}\n\treturn segments, segmentCopies\n}", "func New(store *store.MemoryStore) *Scheduler {\n\treturn &Scheduler{\n\t\tstore: store,\n\t\tunassignedTasks: make(map[string]*api.Task),\n\t\tpendingPreassignedTasks: make(map[string]*api.Task),\n\t\tpreassignedTasks: make(map[string]struct{}),\n\t\tallTasks: make(map[string]*api.Task),\n\t\tstopChan: make(chan struct{}),\n\t\tdoneChan: make(chan struct{}),\n\t\tpipeline: NewPipeline(),\n\t\tvolumes: newVolumeSet(),\n\t}\n}", "func SubmitWorkflow(sqlProgram string, modelDir string, session *pb.Session) *pipe.Reader {\n\tlogger := log.WithFields(log.Fields{\n\t\t\"requestID\": log.UUID(),\n\t\t\"user\": session.UserId,\n\t\t\"submitter\": session.Submitter,\n\t\t\"event\": \"submitWorkflow\",\n\t})\n\tif os.Getenv(\"SQLFLOW_WORKFLOW_LOGVIEW_ENDPOINT\") == \"\" {\n\t\tlogger.Fatalf(\"should set SQLFLOW_WORKFLOW_LOGVIEW_ENDPOINT if enable argo mode.\")\n\t}\n\trd, wr := pipe.Pipe()\n\tstartTime := time.Now()\n\tgo func() {\n\t\tdefer wr.Close()\n\t\twfID, e := workflow.Run(getWorkflowBackend(), sqlProgram, session, logger)\n\t\tdefer logger.Infof(\"submitted, workflowID:%s, spent:%.f, SQL:%s, error:%v\", wfID, time.Since(startTime).Seconds(), sqlProgram, e)\n\t\tif e != nil {\n\t\t\tif e := wr.Write(e); e != nil {\n\t\t\t\tlogger.Errorf(\"piping: %v\", e)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\tif e := wr.Write(pb.Job{Id: wfID}); e != nil {\n\t\t\tlogger.Errorf(\"piping: %v\", e)\n\t\t\treturn\n\t\t}\n\t}()\n\treturn rd\n}", "func (m *Model) NewProc(ctx nn.Context) nn.Processor {\n\tg := ctx.Graph\n\tlength := m.NumOfFeatures\n\twx := make([]ag.Node, length)\n\tbx := make([]ag.Node, length)\n\tif m.KeepFeaturesParamsFixed {\n\t\tfor i := 0; i < length; i++ {\n\t\t\twx[i] = g.NewWrapNoGrad(m.Wz[i])\n\t\t\tbx[i] = g.NewWrapNoGrad(m.Bz[i])\n\t\t}\n\t} else {\n\t\tfor i := 0; i < length; i++ {\n\t\t\twx[i] = g.NewWrap(m.Wz[i])\n\t\t\tbx[i] = g.NewWrap(m.Bz[i])\n\t\t}\n\t}\n\tvar wh, bh ag.Node\n\tif m.KeepEnhancedNodesParamsFixed {\n\t\twh = g.NewWrapNoGrad(m.Wh)\n\t\tbh = g.NewWrapNoGrad(m.Bh)\n\t} else {\n\t\twh = g.NewWrap(m.Wh)\n\t\tbh = g.NewWrap(m.Bh)\n\t}\n\treturn &Processor{\n\t\tBaseProcessor: nn.BaseProcessor{\n\t\t\tModel: m,\n\t\t\tMode: ctx.Mode,\n\t\t\tGraph: ctx.Graph,\n\t\t\tFullSeqProcessing: false,\n\t\t},\n\t\tConfig: m.Config,\n\t\twz: wx,\n\t\tbz: bx,\n\t\twh: wh,\n\t\tbh: bh,\n\t\tw: g.NewWrap(m.W),\n\t\tb: g.NewWrap(m.B),\n\t}\n}", "func NewWorkflow(ctx *pulumi.Context,\n\tname string, args *WorkflowArgs, opts ...pulumi.ResourceOption) (*Workflow, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.WorkflowId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'WorkflowId'\")\n\t}\n\tvar resource Workflow\n\terr := ctx.RegisterResource(\"google-native:workflows/v1beta:Workflow\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func newBatchJobPool(ctx context.Context, o ObjectLayer, workers int) *BatchJobPool {\n\tjpool := &BatchJobPool{\n\t\tctx: ctx,\n\t\tobjLayer: o,\n\t\tjobCh: make(chan *BatchJobRequest, 10000),\n\t\tworkerKillCh: make(chan struct{}, workers),\n\t}\n\tjpool.ResizeWorkers(workers)\n\tjpool.resume()\n\treturn jpool\n}", "func (d *WorkFlowDefinition) Create() {\n\td.nodes = make(map[string]WorkFlowNodeInterface)\n\td.edges = make(map[string][]string)\n\td.joinFork = make(map[string]string)\n}", "func (d *WorkFlowDefinition) Create() {\n\td.nodes = make(map[string]WorkFlowNodeInterface)\n\td.edges = make(map[string][]string)\n\td.joinFork = make(map[string]string)\n}", "func NewWorkflow() *Workflow {\n\treturn &Workflow{current: NEW, handlers: make(map[Step]Method), routes: make(map[Event]Step)}\n}", "func New(closers ...io.Closer) *BatchCloser {\n\tbc := &BatchCloser{}\n\tbc.Add(closers...)\n\treturn bc\n}", "func (t *VerticalSplitTask) Run(parameters map[string]string) ([]*automationpb.TaskContainer, string, error) {\n\t// Required parameters.\n\t// Example: source_keyspace\n\tsourceKeyspace := parameters[\"source_keyspace\"]\n\t// Example: destination_keyspace\n\tdestKeyspace := parameters[\"dest_keyspace\"]\n\t// Example: 10-20\n\tshards := strings.Split(parameters[\"shard_list\"], \",\")\n\t// Example: table1,table2\n\ttables := parameters[\"tables\"]\n\t// Example: localhost:15000\n\tvtctldEndpoint := parameters[\"vtctld_endpoint\"]\n\t// Example: localhost:15001\n\tvtworkerEndpoint := parameters[\"vtworker_endpoint\"]\n\n\t// Optional parameters.\n\t// Example: 1\n\tminHealthyRdonlyTablets := parameters[\"min_healthy_rdonly_tablets\"]\n\n\tvar newTasks []*automationpb.TaskContainer\n\tcopySchemaTasks := NewTaskContainer()\n\tfor _, shard := range shards {\n\t\tAddTask(copySchemaTasks, \"CopySchemaShardTask\", map[string]string{\n\t\t\t\"source_keyspace_and_shard\": topoproto.KeyspaceShardString(sourceKeyspace, shard),\n\t\t\t\"dest_keyspace_and_shard\": topoproto.KeyspaceShardString(destKeyspace, shard),\n\t\t\t\"vtctld_endpoint\": vtctldEndpoint,\n\t\t\t\"tables\": tables,\n\t\t})\n\t}\n\tnewTasks = append(newTasks, copySchemaTasks)\n\n\tvSplitCloneTasks := NewTaskContainer()\n\tfor _, shard := range shards {\n\t\t// TODO(mberlin): Add a semaphore as argument to limit the parallism.\n\t\tAddTask(vSplitCloneTasks, \"VerticalSplitCloneTask\", map[string]string{\n\t\t\t\"dest_keyspace\": destKeyspace,\n\t\t\t\"shard\": shard,\n\t\t\t\"tables\": tables,\n\t\t\t\"vtworker_endpoint\": vtworkerEndpoint,\n\t\t\t\"min_healthy_rdonly_tablets\": minHealthyRdonlyTablets,\n\t\t})\n\t}\n\tnewTasks = append(newTasks, vSplitCloneTasks)\n\n\t// TODO(mberlin): When the framework supports nesting tasks, these wait tasks should be run before each SplitDiff.\n\twaitTasks := NewTaskContainer()\n\tfor _, shard := range shards {\n\t\tAddTask(waitTasks, \"WaitForFilteredReplicationTask\", map[string]string{\n\t\t\t\"keyspace\": destKeyspace,\n\t\t\t\"shard\": shard,\n\t\t\t\"max_delay\": \"30s\",\n\t\t\t\"vtctld_endpoint\": vtctldEndpoint,\n\t\t})\n\t}\n\tnewTasks = append(newTasks, waitTasks)\n\n\t// TODO(mberlin): Run all SplitDiffTasks in parallel which do not use overlapping source shards for the comparison.\n\tfor _, shard := range shards {\n\t\tvSplitDiffTask := NewTaskContainer()\n\t\tAddTask(vSplitDiffTask, \"VerticalSplitDiffTask\", map[string]string{\n\t\t\t\"dest_keyspace\": destKeyspace,\n\t\t\t\"shard\": shard,\n\t\t\t\"vtworker_endpoint\": vtworkerEndpoint,\n\t\t\t\"min_healthy_rdonly_tablets\": minHealthyRdonlyTablets,\n\t\t})\n\t\tnewTasks = append(newTasks, vSplitDiffTask)\n\t}\n\n\tfor _, servedType := range []string{\"rdonly\", \"replica\", \"master\"} {\n\t\tmigrateServedTypesTasks := NewTaskContainer()\n\t\tfor _, shard := range shards {\n\t\t\tAddTask(migrateServedTypesTasks, \"MigrateServedFromTask\", map[string]string{\n\t\t\t\t\"dest_keyspace\": destKeyspace,\n\t\t\t\t\"shard\": shard,\n\t\t\t\t\"type\": servedType,\n\t\t\t\t\"vtctld_endpoint\": vtctldEndpoint,\n\t\t\t})\n\t\t}\n\t\tnewTasks = append(newTasks, migrateServedTypesTasks)\n\t}\n\n\treturn newTasks, \"\", nil\n}", "func (wc *workflowClient) StartWorkflow(\n\tctx context.Context,\n\toptions StartWorkflowOptions,\n\tworkflowFunc interface{},\n\targs ...interface{},\n) (*WorkflowExecution, error) {\n\tworkflowID := options.ID\n\tif len(workflowID) == 0 {\n\t\tworkflowID = uuid.NewRandom().String()\n\t}\n\n\tif options.TaskList == \"\" {\n\t\treturn nil, errors.New(\"missing TaskList\")\n\t}\n\n\texecutionTimeout := common.Int32Ceil(options.ExecutionStartToCloseTimeout.Seconds())\n\tif executionTimeout <= 0 {\n\t\treturn nil, errors.New(\"missing or invalid ExecutionStartToCloseTimeout\")\n\t}\n\n\tdecisionTaskTimeout := common.Int32Ceil(options.DecisionTaskStartToCloseTimeout.Seconds())\n\tif decisionTaskTimeout < 0 {\n\t\treturn nil, errors.New(\"negative DecisionTaskStartToCloseTimeout provided\")\n\t}\n\tif decisionTaskTimeout == 0 {\n\t\tdecisionTaskTimeout = defaultDecisionTaskTimeoutInSecs\n\t}\n\n\t// Validate type and its arguments.\n\tworkflowType, input, err := getValidatedWorkflowFunction(workflowFunc, args, wc.dataConverter, wc.registry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmemo, err := getWorkflowMemo(options.Memo, wc.dataConverter)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsearchAttr, err := serializeSearchAttributes(options.SearchAttributes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdelayStartSeconds := common.Int32Ceil(options.DelayStart.Seconds())\n\tif delayStartSeconds < 0 {\n\t\treturn nil, errors.New(\"Invalid DelayStart option\")\n\t}\n\n\tjitterStartSeconds := common.Int32Ceil(options.JitterStart.Seconds())\n\tif jitterStartSeconds < 0 {\n\t\treturn nil, errors.New(\"Invalid JitterStart option\")\n\t}\n\n\t// create a workflow start span and attach it to the context object.\n\t// N.B. we need to finish this immediately as jaeger does not give us a way\n\t// to recreate a span given a span context - which means we will run into\n\t// issues during replay. we work around this by creating and ending the\n\t// workflow start span and passing in that context to the workflow. So\n\t// everything beginning with the StartWorkflowExecutionRequest will be\n\t// parented by the created start workflow span.\n\tctx, span := createOpenTracingWorkflowSpan(ctx, wc.tracer, time.Now(), fmt.Sprintf(\"StartWorkflow-%s\", workflowType.Name), workflowID)\n\tspan.Finish()\n\n\t// get workflow headers from the context\n\theader := wc.getWorkflowHeader(ctx)\n\n\t// run propagators to extract information about tracing and other stuff, store in headers field\n\tstartRequest := &s.StartWorkflowExecutionRequest{\n\t\tDomain: common.StringPtr(wc.domain),\n\t\tRequestId: common.StringPtr(uuid.New()),\n\t\tWorkflowId: common.StringPtr(workflowID),\n\t\tWorkflowType: workflowTypePtr(*workflowType),\n\t\tTaskList: common.TaskListPtr(s.TaskList{Name: common.StringPtr(options.TaskList)}),\n\t\tInput: input,\n\t\tExecutionStartToCloseTimeoutSeconds: common.Int32Ptr(executionTimeout),\n\t\tTaskStartToCloseTimeoutSeconds: common.Int32Ptr(decisionTaskTimeout),\n\t\tIdentity: common.StringPtr(wc.identity),\n\t\tWorkflowIdReusePolicy: options.WorkflowIDReusePolicy.toThriftPtr(),\n\t\tRetryPolicy: convertRetryPolicy(options.RetryPolicy),\n\t\tCronSchedule: common.StringPtr(options.CronSchedule),\n\t\tMemo: memo,\n\t\tSearchAttributes: searchAttr,\n\t\tHeader: header,\n\t\tDelayStartSeconds: common.Int32Ptr(delayStartSeconds),\n\t\tJitterStartSeconds: common.Int32Ptr(jitterStartSeconds),\n\t}\n\n\tvar response *s.StartWorkflowExecutionResponse\n\n\t// Start creating workflow request.\n\terr = backoff.Retry(ctx,\n\t\tfunc() error {\n\t\t\ttchCtx, cancel, opt := newChannelContext(ctx, wc.featureFlags)\n\t\t\tdefer cancel()\n\n\t\t\tvar err1 error\n\t\t\tresponse, err1 = wc.workflowService.StartWorkflowExecution(tchCtx, startRequest, opt...)\n\t\t\treturn err1\n\t\t}, createDynamicServiceRetryPolicy(ctx), isServiceTransientError)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif wc.metricsScope != nil {\n\t\tscope := wc.metricsScope.GetTaggedScope(tagTaskList, options.TaskList, tagWorkflowType, workflowType.Name)\n\t\tscope.Counter(metrics.WorkflowStartCounter).Inc(1)\n\t}\n\n\texecutionInfo := &WorkflowExecution{\n\t\tID: workflowID,\n\t\tRunID: response.GetRunId()}\n\treturn executionInfo, nil\n}", "func New(\n\tprocessor goduck.BatchProcessor,\n\tmaxBatchSize int,\n\tmaxTimeout time.Duration,\n\tstream goduck.Stream,\n) *BatchEngine {\n\tengine := &BatchEngine{\n\t\tstream: stream,\n\t\tbatchProcessor: processor,\n\t\tmaxBatchSize: maxBatchSize,\n\t\tmaxTimeout: maxTimeout,\n\t\tprocessorError: nil,\n\t}\n\treturn engine\n}", "func generateWorkFlow(ctx *Context) error {\n\trootCtx, err := getRootContext()\n\tif err != nil {\n\t\treturn err\n\t}\n\texamples, err := rootCtx.GetExamples()\n\tif err != nil {\n\t\treturn err\n\t}\n\tmodules, err := rootCtx.GetModules()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn workflow.Generate(ctx.GithubWorkflowsDir(), examples, modules)\n}", "func StartWorker(mapFunc MapFunc, reduceFunc ReduceFunc, master string) error {\n\tos.Mkdir(\"/tmp/squinn\", 1777)\n\ttasks_run := 0\n\tfor {\n\t\tlogf(\"===============================\")\n\t\tlogf(\" Starting new task.\")\n\t\tlogf(\"===============================\")\n\t\t/*\n\t\t * Call master, asking for work\n\t\t */\n\n\t\tvar resp Response\n\t\tvar req Request\n\t\terr := call(master, \"GetWork\", req, &resp)\n\t\tif err != nil {\n\t\t\tfailure(\"GetWork\")\n\t\t\ttasks_run++\n\t\t\tcontinue\n\t\t}\n\t\t/*\n\t\tif resp.Message == WORK_DONE {\n\t\t\tlog.Println(\"GetWork - Finished Working\")\n\t\t\tresp.Type =\n\t\t\tbreak\n\t\t}\n\t\t*/\n\t\t//for resp.Message == WAIT {\n\t\tfor resp.Type == TYPE_WAIT {\n\t\t\ttime.Sleep(1e9)\n\t\t\terr = call(master, \"GetWork\", req, &resp)\n\t\t\tif err != nil {\n\t\t\t\tfailure(\"GetWork\")\n\t\t\t\ttasks_run++\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t/*\n\t\t\tif resp.Message == WORK_DONE {\n\t\t\t\tlog.Println(\"GetWork - Finished Working\")\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t*/\n\t\t}\n\t\twork := resp.Work\n\t\toutput := resp.Output\n\t\tvar myAddress string\n\n\t\t/*\n\t\t * Do work\n\t\t */\n\t\t// Walks through the assigned sql records\n\t\t// Call the given mapper function\n\t\t// Receive from the output channel in a go routine\n\t\t// Feed them to the reducer through its own sql files\n\t\t// Close the sql files\n\n\t\tif resp.Type == TYPE_MAP {\n\t\t\tlogf(\"MAP ID: %d\", work.WorkerID)\n\t\t\tlog.Printf(\"Range: %d-%d\", work.Offset, work.Offset+work.Size)\n\t\t\tlog.Print(\"Running Map function on input data...\")\n\t\t\t// Load data\n\t\t\tdb, err := sql.Open(\"sqlite3\", work.Filename)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tfailure(\"sql.Open\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer db.Close()\n\n\n\t\t\t// Query\n\t\t\trows, err := db.Query(fmt.Sprintf(\"select key, value from %s limit %d offset %d;\", work.Table, work.Size, work.Offset))\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tfailure(\"sql.Query1\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tfor rows.Next() {\n\t\t\t\tvar key string\n\t\t\t\tvar value string\n\t\t\t\trows.Scan(&key, &value)\n\n\t\t\t\t// TODO: TURN OFF JOURNALING\n\t\t\t\t//out.DB.Exec(\"pragma synchronous = off\");\n\t\t\t\t//out.DB.Exec(\"pragma journal_mode = off\")\n\n\t\t\t\t//TODO: CREATE INDEXES ON EACH DB SO ORDER BY WORKS FASTER\n\n\t\t\t\t// Temp storage\n\t\t\t\t// Each time the map function emits a key/value pair, you should figure out which reduce task that pair will go to.\n\t\t\t\treducer := big.NewInt(0)\n\t\t\t\treducer.Mod(hash(key), big.NewInt(int64(work.R)))\n\t\t\t\t//db_tmp, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"/tmp/map_output/%d/map_out_%d.sql\", work.WorkerID, reducer.Int64())) //TODO: Directories don't work\n\t\t\t\tdb_tmp, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"/tmp/squinn/map_%d_out_%d.sql\", work.WorkerID, reducer.Int64()))\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tfailure(fmt.Sprintf(\"sql.Open - /tmp/map_output/%d/map_out_%d.sql\", work.WorkerID, reducer.Int64()))\n\t\t\t\t\treturn err\n\t\t\t\t}\n\n\n\t\t\t\t// Prepare tmp database\n\t\t\t\tsqls := []string{\n\t\t\t\t\t\"create table if not exists data (key text not null, value text not null)\",\n\t\t\t\t\t\"create index if not exists data_key on data (key asc, value asc);\",\n\t\t\t\t\t\"pragma synchronous = off;\",\n\t\t\t\t\t\"pragma journal_mode = off;\",\n\t\t\t\t}\n\t\t\t\tfor _, sql := range sqls {\n\t\t\t\t\t_, err = db_tmp.Exec(sql)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfailure(\"sql.Exec3\")\n\t\t\t\t\t\tfmt.Printf(\"%q: %s\\n\", err, sql)\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\n\t\t\t\t//type MapFunc func(key, value string, output chan<- Pair) error\n\t\t\t\toutChan := make(chan Pair)\n\t\t\t\tgo func() {\n\t\t\t\t\terr = mapFunc(key, value, outChan)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfailure(\"mapFunc\")\n\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t\t//return err\n\t\t\t\t\t}\n\t\t\t\t}()\n\n\n\t\t\t\t// Get the output from the map function's output channel\n\t\t\t\t//var pairs []Pair\n\t\t\t\tpair := <-outChan\n\t\t\t\tfor pair.Key != \"\" {\n\t\t\t\t\tkey, value = pair.Key, pair.Value\n\t\t\t\t\t// Write the data locally\n\t\t\t\t\tsql := fmt.Sprintf(\"insert into data values ('%s', '%s');\", key, value)\n\t\t\t\t\t_, err = db_tmp.Exec(sql)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfailure(\"sql.Exec4\")\n\t\t\t\t\t\tfmt.Printf(\"map_%d_out_%d.sql\\n\", work.WorkerID, reducer.Int64())\n\t\t\t\t\t\tfmt.Println(key, value)\n\t\t\t\t\t\tlog.Printf(\"%q: %s\\n\", err, sql)\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\t//log.Println(key, value)\n\t\t\t\t\tpair = <-outChan\n\t\t\t\t}\n\t\t\t\tdb_tmp.Close()\n\t\t\t}\n\n\t\t\tmyAddress = net.JoinHostPort(GetLocalAddress(), fmt.Sprintf(\"%d\", 4000+work.WorkerID))\n\t\t\t// Serve the files so each reducer can get them\n\t\t\t// /tmp/map_output/%d/tmp_map_out_%d.sql\n\t\t\tgo func(address string) {\n\t\t\t\t// (4000 + work.WorkerID)\n\t\t\t\t//http.Handle(\"/map_out_files/\", http.FileServer(http.Dir(fmt.Sprintf(\"/tmp/map_output/%d\", work.WorkerID)))) //TODO: Directories don't work\n\t\t\t\t//fileServer := http.FileServer(http.Dir(\"/Homework/3410/mapreduce/\"))\n\t\t\t\tfileServer := http.FileServer(http.Dir(\"/tmp/squinn/\"))\n\t\t\t\tlog.Println(\"Listening on \" + address)\n\t\t\t\tlog.Fatal(http.ListenAndServe(address, fileServer))\n\t\t\t}(myAddress)\n\t\t} else if resp.Type == TYPE_REDUCE {\n\t\t\tlogf(\"REDUCE ID: %d\", work.WorkerID)\n\t\t\t//type ReduceFunc func(key string, values <-chan string, output chan<- Pair) error\n\t\t\t// Load each input file one at a time (copied from each map task)\n\t\t\tvar filenames []string\n\t\t\tfor i, mapper := range work.MapAddresses {\n\t\t\t\t//res, err := http.Get(fmt.Sprintf(\"%d:/tmp/map_output/%d/map_out_%d.sql\", 4000+i, i, work.WorkerID)) //TODO: Directories don't work\n\t\t\t\t//map_file := fmt.Sprintf(\"http://localhost:%d/map_%d_out_%d.sql\", 4000+i, i, work.WorkerID)\n\t\t\t\tmap_file := fmt.Sprintf(\"http://%s/map_%d_out_%d.sql\", mapper, i, work.WorkerID)\n\n\t\t\t\tres, err := http.Get(map_file)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"http.Get\")\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tfile, err := ioutil.ReadAll(res.Body)\n\t\t\t\tres.Body.Close()\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"ioutil.ReadAll\")\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\n\t\t\t\tfilename := fmt.Sprintf(\"/tmp/squinn/map_out_%d_mapper_%d.sql\", work.WorkerID, i)\n\t\t\t\tfilenames = append(filenames, filename)\n\n\t\t\t\terr = ioutil.WriteFile(filename, file, 0777)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"file.Write\")\n\t\t\t\t\tlog.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Combine all the rows into a single input file\n\t\t\tsqls := []string{\n\t\t\t\t\"create table if not exists data (key text not null, value text not null)\",\n\t\t\t\t\"create index if not exists data_key on data (key asc, value asc);\",\n\t\t\t\t\"pragma synchronous = off;\",\n\t\t\t\t\"pragma journal_mode = off;\",\n\t\t\t}\n\n\t\t\tfor _, file := range filenames {\n\t\t\t\tdb, err := sql.Open(\"sqlite3\", file)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdefer db.Close()\n\n\t\t\t\trows, err := db.Query(\"select key, value from data;\",)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tdefer rows.Close()\n\n\t\t\t\tfor rows.Next() {\n\t\t\t\t\tvar key string\n\t\t\t\t\tvar value string\n\t\t\t\t\trows.Scan(&key, &value)\n\t\t\t\t\tsqls = append(sqls, fmt.Sprintf(\"insert into data values ('%s', '%s');\", key, value))\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treduce_db, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"/tmp/squinn/reduce_aggregate_%d.sql\", work.WorkerID))\n\t\t\tfor _, sql := range sqls {\n\t\t\t\t_, err = reduce_db.Exec(sql)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"%q: %s\\n\", err, sql)\n\t\t\t\t}\n\t\t\t}\n\t\t\treduce_db.Close()\n\n\t\t\treduce_db, err = sql.Open(\"sqlite3\", fmt.Sprintf(\"/tmp/squinn/reduce_aggregate_%d.sql\", work.WorkerID))\n\t\t\tdefer reduce_db.Close()\n\t\t\trows, err := reduce_db.Query(\"select key, value from data order by key asc;\")\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tfailure(\"sql.Query2\")\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer rows.Close()\n\n\t\t\tvar key string\n\t\t\tvar value string\n\t\t\trows.Next()\n\t\t\trows.Scan(&key, &value)\n\n\t\t\t//type ReduceFunc func(key string, values <-chan string, output chan<- Pair) error\n\t\t\tinChan := make(chan string)\n\t\t\toutChan := make(chan Pair)\n\t\t\tgo func() {\n\t\t\t\terr = reduceFunc(key, inChan, outChan)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"reduceFunc\")\n\t\t\t\t\tlog.Println(err)\n\t\t\t\t}\n\t\t\t}()\n\t\t\tinChan <- value\n\t\t\tcurrent := key\n\n\t\t\tvar outputPairs []Pair\n\t\t\t// Walk through the file's rows, performing the reduce func\n\t\t\tfor rows.Next() {\n\t\t\t\trows.Scan(&key, &value)\n\t\t\t\tif key == current {\n\t\t\t\t\tinChan <- value\n\t\t\t\t} else {\n\t\t\t\t\tclose(inChan)\n\t\t\t\t\tp := <-outChan\n\t\t\t\t\toutputPairs = append(outputPairs, p)\n\n\t\t\t\t\tinChan = make(chan string)\n\t\t\t\t\toutChan = make(chan Pair)\n\t\t\t\t\tgo func() {\n\t\t\t\t\t\terr = reduceFunc(key, inChan, outChan)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\tfailure(\"reduceFunc\")\n\t\t\t\t\t\t\tlog.Println(err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}()\n\t\t\t\t\tinChan <- value\n\t\t\t\t\tcurrent = key\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose(inChan)\n\t\t\tp := <-outChan\n\t\t\toutputPairs = append(outputPairs, p)\n\n\t\t\t// Prepare tmp database\n\t\t\t// TODO: Use the command line parameter output\n\t\t\t//db_out, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"/home/s/squinn/tmp/reduce_out_%d.sql\", work.WorkerID))\n\t\t\t//db_out, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"/Users/Ren/tmp/reduce_out_%d.sql\", work.WorkerID))\n\t\t\tdb_out, err := sql.Open(\"sqlite3\", fmt.Sprintf(\"%s/reduce_out_%d.sql\", output, work.WorkerID))\n\t\t\tdefer db_out.Close()\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t\tfailure(fmt.Sprintf(\"sql.Open - reduce_out_%d.sql\", work.WorkerID))\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tsqls = []string{\n\t\t\t\t\"create table if not exists data (key text not null, value text not null)\",\n\t\t\t\t\"create index if not exists data_key on data (key asc, value asc);\",\n\t\t\t\t\"pragma synchronous = off;\",\n\t\t\t\t\"pragma journal_mode = off;\",\n\t\t\t}\n\t\t\tfor _, sql := range sqls {\n\t\t\t\t_, err = db_out.Exec(sql)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"sql.Exec5\")\n\t\t\t\t\tfmt.Printf(\"%q: %s\\n\", err, sql)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Write the data locally\n\t\t\tfor _, op := range outputPairs {\n\t\t\t\tsql := fmt.Sprintf(\"insert into data values ('%s', '%s');\", op.Key, op.Value)\n\t\t\t\t_, err = db_out.Exec(sql)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfailure(\"sql.Exec6\")\n\t\t\t\t\tfmt.Printf(\"%q: %s\\n\", err, sql)\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t} else if resp.Type == TYPE_DONE {\n\t\t} else {\n\t\t\tlog.Println(\"INVALID WORK TYPE\")\n\t\t\tvar err error\n\t\t\treturn err\n\t\t}\n\n\n\n\t\t/*\n\t\t * Notify the master when I'm done\n\t\t */\n\n\t\treq.Type = resp.Type\n\t\treq.Address = myAddress\n\t\terr = call(master, \"Notify\", req, &resp)\n\t\tif err != nil {\n\t\t\tfailure(\"Notify\")\n\t\t\ttasks_run++\n\t\t\tcontinue\n\t\t}\n\n\t\tif resp.Message == WORK_DONE {\n\t\t\tlog.Println(\"Notified - Finished Working\")\n\t\t\tlog.Println(\"Waiting for word from master to clean up...\")\n\t\t\t// TODO: Wait for word from master\n\n\t\t\t//CleanUp\n\t\t\t/*\n\t\t\tos.Remove(\"aggregate.sql\")\n\t\t\tfor r:=0; r<work.R; r++ {\n\t\t\t\tfor m:=0; m<work.M; m++ {\n\t\t\t\t\tos.Remove(fmt.Sprintf(\"map_%d_out_%d.sql\", m, r))\n\t\t\t\t\tos.Remove(fmt.Sprintf(\"map_out_%d_mapper_%d.sql\", r, m))\n\t\t\t\t}\n\t\t\t\tos.Remove(fmt.Sprintf(\"reduce_aggregate_%d.sql\", r))\n\t\t\t}\n\t\t\t*/\n\t\t\tos.RemoveAll(\"/tmp/squinn\")\n\t\t\treturn nil\n\t\t}\n\t\ttasks_run++\n\n\t}\n\n\treturn nil\n}", "func (p *unlimitedPool) Batch() Batch {\n\treturn newBatch(p)\n}", "func New(requestQueue rqueue.Queue, peerManager *peering.Manager, opts *Options) *Processor {\n\tproc := &Processor{\n\t\tpm: peerManager,\n\t\trequestQueue: requestQueue,\n\t\tEvents: Events{\n\t\t\tTransactionProcessed: events.NewEvent(TransactionProcessedCaller),\n\t\t\tBroadcastTransaction: events.NewEvent(BroadcastCaller),\n\t\t},\n\t\topts: *opts,\n\t}\n\twuCacheOpts := opts.WorkUnitCacheOpts\n\tproc.workUnits = objectstorage.New(\n\t\tnil,\n\t\tworkUnitFactory,\n\t\tobjectstorage.CacheTime(time.Duration(wuCacheOpts.CacheTimeMs)),\n\t\tobjectstorage.PersistenceEnabled(false),\n\t\tobjectstorage.KeysOnly(true),\n\t\tobjectstorage.StoreOnCreation(false),\n\t\tobjectstorage.LeakDetectionEnabled(wuCacheOpts.LeakDetectionOptions.Enabled,\n\t\t\tobjectstorage.LeakDetectionOptions{\n\t\t\t\tMaxConsumersPerObject: wuCacheOpts.LeakDetectionOptions.MaxConsumersPerObject,\n\t\t\t\tMaxConsumerHoldTime: time.Duration(wuCacheOpts.LeakDetectionOptions.MaxConsumerHoldTimeSec) * time.Second,\n\t\t\t}),\n\t)\n\n\tproc.wp = workerpool.New(func(task workerpool.Task) {\n\t\tp := task.Param(0).(*peer.Peer)\n\t\tdata := task.Param(2).([]byte)\n\n\t\tswitch task.Param(1).(message.Type) {\n\t\tcase sting.MessageTypeTransaction:\n\t\t\tproc.processTransaction(p, data)\n\t\tcase sting.MessageTypeTransactionRequest:\n\t\t\tproc.processTransactionRequest(p, data)\n\t\tcase sting.MessageTypeMilestoneRequest:\n\t\t\tproc.processMilestoneRequest(p, data)\n\t\t}\n\n\t\ttask.Return(nil)\n\t}, workerpool.WorkerCount(workerCount), workerpool.QueueSize(WorkerQueueSize))\n\n\treturn proc\n}", "func Broadcast(procs ...Processor) StageRunner {\n\tif len(procs) == 0 {\n\t\tpanic(\"Broadcast: at least one processor must be specific\")\n\t}\n\tfifos := make([]StageRunner, len(procs))\n\tfor i, p := range procs {\n\t\tfifos[i] = FIFO(p)\n\t}\n\treturn &broadcast{\n\t\tfifos: fifos,\n\t}\n}", "func (d *disp) Start() *disp {\n\n\t//pipelines_implementation_backup(d)\n\n\tl := len(d.Workers)\n\tfor i := 1; i <= l; i++ {\n\n\t\twrk := worker2.New(i, \"default\", make(worker2.PipelineChannel), d.PipelineQueue, make(worker2.JobChannel), d.Queue, make(chan struct{}))\n\t\twrk.Start()\n\t\td.Workers = append(d.Workers, wrk)\n\t}\n\tgo d.process()\n\n\treturn d\n}", "func MakeCoordinator(files []string, nReduce int) *Coordinator {\n\tmapTaskNum := len(files)\n\treduceTaskNum := nReduce\n\ttaskNum := mapTaskNum + reduceTaskNum\n\n\tvar mapTaskList []*Task\n\tfor iMap, file := range files {\n\t\tmapTaskList = append(mapTaskList, &Task{\n\t\t\tID: 0, // set later\n\t\t\tType: TaskMap,\n\t\t\tMapTask: &MapTask{\n\t\t\t\tFile: file,\n\t\t\t\tIMap: iMap,\n\t\t\t\tNReduce: reduceTaskNum,\n\t\t\t},\n\t\t\tReduceTask: nil,\n\t\t})\n\t}\n\n\tvar reduceTaskList []*Task\n\tfor iReduce := 0; iReduce < reduceTaskNum; iReduce++ {\n\t\treduceTaskList = append(reduceTaskList, &Task{\n\t\t\tID: 0, // set later\n\t\t\tType: TaskReduce,\n\t\t\tMapTask: nil,\n\t\t\tReduceTask: &ReduceTask{\n\t\t\t\tNMap: mapTaskNum,\n\t\t\t\tIReduce: iReduce,\n\t\t\t},\n\t\t})\n\t}\n\n\ttaskList := mapTaskList\n\ttaskList = append(taskList, reduceTaskList...)\n\tfor i, task := range taskList {\n\t\ttask.ID = i\n\t}\n\n\tc := Coordinator{\n\t\ttaskNum: taskNum,\n\t\tmapTaskNum: mapTaskNum,\n\t\treduceTaskNum: reduceTaskNum,\n\t\ttaskList: taskList,\n\t\ttaskBeginTime: make([]int64, taskNum),\n\t}\n\tc.isDone.Store(false)\n\tc.server()\n\treturn &c\n}", "func (s serverImpl) CreateBatch(goCtx context.Context, req *ecocredit.MsgCreateBatch) (*ecocredit.MsgCreateBatchResponse, error) {\n\tctx := types.UnwrapSDKContext(goCtx)\n\tclassID := req.ClassId\n\tclassInfo, err := s.getClassInfo(ctx, classID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif err = classInfo.AssertClassIssuer(req.Issuer); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmaxDecimalPlaces := classInfo.CreditType.Precision\n\tbatchSeqNo, err := s.nextBatchInClass(ctx, classInfo)\n\tif err != nil {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error())\n\t}\n\n\tbatchDenomStr, err := ecocredit.FormatDenom(classID, batchSeqNo, req.StartDate, req.EndDate)\n\tif err != nil {\n\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrap(err.Error())\n\t}\n\n\tbatchDenom := batchDenomT(batchDenomStr)\n\ttradableSupply := math.NewDecFromInt64(0)\n\tretiredSupply := math.NewDecFromInt64(0)\n\n\tstore := ctx.KVStore(s.storeKey)\n\n\tfor _, issuance := range req.Issuance {\n\t\tvar err error\n\t\ttradable, retired := math.NewDecFromInt64(0), math.NewDecFromInt64(0)\n\n\t\tif issuance.TradableAmount != \"\" {\n\t\t\ttradable, err = math.NewNonNegativeDecFromString(issuance.TradableAmount)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdecPlaces := tradable.NumDecimalPlaces()\n\t\t\tif decPlaces > maxDecimalPlaces {\n\t\t\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrapf(\"tradable amount exceeds precision for credit type: \"+\n\t\t\t\t\t\"is %v, should be < %v\", decPlaces, maxDecimalPlaces)\n\t\t\t}\n\t\t}\n\n\t\tif issuance.RetiredAmount != \"\" {\n\t\t\tretired, err = math.NewNonNegativeDecFromString(issuance.RetiredAmount)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\tdecPlaces := retired.NumDecimalPlaces()\n\t\t\tif decPlaces > maxDecimalPlaces {\n\t\t\t\treturn nil, sdkerrors.ErrInvalidRequest.Wrapf(\"retired amount does not conform to credit type \"+\n\t\t\t\t\t\"precision: %v should be %v\", decPlaces, maxDecimalPlaces)\n\t\t\t}\n\t\t}\n\n\t\trecipient := issuance.Recipient\n\t\trecipientAddr, err := sdk.AccAddressFromBech32(recipient)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif !tradable.IsZero() {\n\t\t\ttradableSupply, err = tradableSupply.Add(tradable)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\terr = addAndSetDecimal(store, TradableBalanceKey(recipientAddr, batchDenom), tradable)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tif !retired.IsZero() {\n\t\t\tretiredSupply, err = retiredSupply.Add(retired)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\n\t\t\terr = retire(ctx, store, recipientAddr, batchDenom, retired, issuance.RetirementLocation)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\terr = ctx.EventManager().EmitTypedEvent(&ecocredit.EventReceive{\n\t\t\tRecipient: recipient,\n\t\t\tBatchDenom: string(batchDenom),\n\t\t\tRetiredAmount: tradable.String(),\n\t\t\tTradableAmount: retired.String(),\n\t\t})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tctx.GasMeter().ConsumeGas(gasCostPerIteration, \"batch issuance\")\n\t}\n\n\tsetDecimal(store, TradableSupplyKey(batchDenom), tradableSupply)\n\tsetDecimal(store, RetiredSupplyKey(batchDenom), retiredSupply)\n\n\ttotalSupply, err := tradableSupply.Add(retiredSupply)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttotalSupplyStr := totalSupply.String()\n\n\tamountCancelledStr := math.NewDecFromInt64(0).String()\n\n\terr = s.batchInfoTable.Create(ctx, &ecocredit.BatchInfo{\n\t\tClassId: classID,\n\t\tBatchDenom: string(batchDenom),\n\t\tIssuer: req.Issuer,\n\t\tTotalAmount: totalSupplyStr,\n\t\tMetadata: req.Metadata,\n\t\tAmountCancelled: amountCancelledStr,\n\t\tStartDate: req.StartDate,\n\t\tEndDate: req.EndDate,\n\t\tProjectLocation: req.ProjectLocation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = ctx.EventManager().EmitTypedEvent(&ecocredit.EventCreateBatch{\n\t\tClassId: classID,\n\t\tBatchDenom: string(batchDenom),\n\t\tIssuer: req.Issuer,\n\t\tTotalAmount: totalSupplyStr,\n\t\tStartDate: req.StartDate.Format(\"2006-01-02\"),\n\t\tEndDate: req.EndDate.Format(\"2006-01-02\"),\n\t\tProjectLocation: req.ProjectLocation,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ecocredit.MsgCreateBatchResponse{BatchDenom: string(batchDenom)}, nil\n}", "func (c *ContainerClient) NewTransactionalBatch(partitionKey PartitionKey) TransactionalBatch {\n\treturn TransactionalBatch{partitionKey: partitionKey}\n}", "func NewSequentialMaster(jobName string, inputFileNames []string,\n\tnumReducers uint, mapF MapFunction, reduceF ReduceFunction) *SequentialMaster {\n\treturn &SequentialMaster{\n\t\tJobName: jobName,\n\t\tInputFileNames: inputFileNames,\n\t\tNumReducers: numReducers,\n\t\tMapF: mapF,\n\t\tReduceF: reduceF,\n\t\tactive: false,\n\t}\n}", "func (zp *ZPackIns) StartBatch(dt int64) {\n\tzp.startBatch(dt)\n}", "func (m *SequentialMaster) Start() {\n\tm.active = true\n\n\tw := *NewWorker(m.JobName, m.MapF, m.ReduceF)\n\n\tfor i, file := range m.InputFileNames {\n\t\tw.DoMap(file, uint(i), m.NumReducers);\n\t}\n\n\tfor i := uint(0); i < m.NumReducers; i++ {\n\t\tw.DoReduce(i, uint(len(m.InputFileNames)))\n\t}\n}", "func NewChain(jc *proto.JobChain) *chain {\n\t// Set the state of all jobs in the chain to \"Pending\".\n\tfor jobName, job := range jc.Jobs {\n\t\tjob.State = proto.STATE_PENDING\n\t\tjob.Data = map[string]interface{}{}\n\t\tjc.Jobs[jobName] = job\n\t}\n\n\treturn &chain{\n\t\tJobChain: jc,\n\t\tRunning: map[string]RunningJob{},\n\t\tN: 0,\n\t\tRWMutex: &sync.RWMutex{},\n\t}\n}", "func New(cfg Config) *RequestBatcher {\n\tvalidateConfig(&cfg)\n\tb := &RequestBatcher{\n\t\tcfg: cfg,\n\t\tpool: makePool(),\n\t\tbatches: makeBatchQueue(),\n\t\trequestChan: make(chan *request),\n\t\tsendDoneChan: make(chan struct{}),\n\t}\n\tb.sendBatchOpName = b.cfg.Name + \".sendBatch\"\n\tif err := cfg.Stopper.RunAsyncTask(context.Background(), b.cfg.Name, b.run); err != nil {\n\t\tpanic(err)\n\t}\n\treturn b\n}", "func NewParallel() *Parallel {\n\tres := new(Parallel)\n\tres.wg = new(sync.WaitGroup)\n\tres.wgChild = new(sync.WaitGroup)\n\tres.pipes = make([]*Pipeline, 0, 10)\n\treturn res\n}", "func (store *Engine) Workflow(workflowID string) (workflow *Workflow, err error) {\n\tworkflow = new(Workflow)\n\n\t_, err = store.api.\n\t\tURL(\"/workflow-engine/api/v1/workflows/%s\", url.PathEscape(workflowID)).\n\t\tGet(workflow)\n\n\treturn workflow, err\n}", "func NewWorker(taskListName, identity, domain string) Worker {\n\tworker := &activity.ActivityWorker{\n\t\tSWF: swf.New(NewSession()),\n\t\tDomain: domain,\n\t\tTaskList: taskListName,\n\t\tIdentity: identity,\n\t}\n\ttaskHandler := &activity.ActivityHandler{Activity: \"preproc\", HandlerFunc: handleTask}\n\tworker.AddHandler(taskHandler)\n\tworkerLog = logger.Log.New(\"component\", \"worker\", \"domain\", domain,\n\t\t\"taskListName\", taskListName, \"identity\", identity)\n\treturn worker\n}", "func NewSpriteBatch(texture ITexture, size int, usage Usage) *SpriteBatch {\n\treturn &SpriteBatch{\n\t\tsize: size,\n\t\ttexture: texture,\n\t\tusage: usage,\n\t\tcolor: []float32{1, 1, 1, 1},\n\t\tarrayBuf: newVertexBuffer(size*4*8, []float32{}, usage),\n\t\tquadIndices: newQuadIndices(size),\n\t\trangeMin: -1,\n\t\trangeMax: -1,\n\t}\n}", "func NewBatch() KVStoreBatch {\n\treturn newBaseKVStoreBatch()\n}", "func (m *Manager) loadAndStartJobsLocked() {\n\tuuids, err := m.ts.GetWorkflowNames(m.ctx)\n\tif err != nil {\n\t\tlog.Errorf(\"GetWorkflowNames failed to find existing workflows: %v\", err)\n\t\treturn\n\t}\n\n\tfor _, uuid := range uuids {\n\t\t// Load workflows from the topo server, only look at\n\t\t// 'Running' ones.\n\t\twi, err := m.ts.GetWorkflow(m.ctx, uuid)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to load workflow %v, will not start it: %v\", uuid, err)\n\t\t\tcontinue\n\t\t}\n\n\t\trw, err := m.instantiateWorkflow(wi.Workflow)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to instantiate workflow %v from factory %v, will not start it: %v\", uuid, wi.FactoryName, err)\n\t\t\tcontinue\n\t\t}\n\t\trw.wi = wi\n\n\t\tif rw.wi.State == workflowpb.WorkflowState_Running {\n\t\t\tm.runWorkflow(rw)\n\t\t}\n\t}\n}", "func MakeBatcher(batchInterval time.Duration) *Batcher {\n\treturn &Batcher{\n\t\tbatchInterval: batchInterval,\n\t\tmetrics: map[string]Metric{},\n\t}\n}", "func NewBatchBuffer() *BatchBuffer {\n\treturn &BatchBuffer{\n\t\tbuffer: make([]coldata.Batch, 0, 2),\n\t}\n}", "func New(conn *pgx.Conn, size int64, tableName string, columnNames []string) *Batcher {\n\treturn &Batcher{\n\t\tconn: conn,\n\t\tsize: size,\n\t\ttableName: tableName,\n\t\tcolumnNames: columnNames,\n\t}\n}", "func NewBatch() KVStoreBatch {\n\treturn &baseKVStoreBatch{}\n}", "func New(w int, l Log, p Proc) Streams {\n\tif w <= 0 {\n\t\tw = 1\n\t}\n\n\tif l == nil {\n\t\tl = events\n\t}\n\n\tsm := Stream{\n\t\tlog: l,\n\t\tuuid: uuid.NewV4().String(),\n\t\tworkers: w,\n\t\tproc: p,\n\t\tdata: make(dataSink),\n\t\terr: make(errorSink),\n\t\tnc: make(chan struct{}),\n\t}\n\n\t// initialize the total data workers needed.\n\tfor i := 0; i < w; i++ {\n\t\tgo sm.initDW()\n\t}\n\n\treturn &sm\n}" ]
[ "0.7028021", "0.5519338", "0.5455288", "0.5427371", "0.5417418", "0.5411967", "0.52581453", "0.5239248", "0.52226645", "0.51933974", "0.5162105", "0.5076186", "0.50602204", "0.50189704", "0.5016432", "0.5015127", "0.4996725", "0.49882042", "0.49671724", "0.49617833", "0.49080426", "0.4901355", "0.48911884", "0.4876518", "0.48704368", "0.484132", "0.4825498", "0.48162568", "0.48149168", "0.48068023", "0.4790165", "0.47835082", "0.4782547", "0.47726265", "0.47263715", "0.47224748", "0.47221512", "0.47173408", "0.47012827", "0.46854743", "0.46841273", "0.4637888", "0.46352214", "0.46132627", "0.46108904", "0.45901665", "0.45860338", "0.45681787", "0.4564928", "0.45613363", "0.45411927", "0.4514564", "0.45122296", "0.4507439", "0.44737566", "0.4464881", "0.4461531", "0.44589657", "0.44540864", "0.44472307", "0.44225538", "0.44189388", "0.4416739", "0.44119525", "0.44107506", "0.44033766", "0.43894443", "0.43860468", "0.43794942", "0.43794942", "0.4378495", "0.4378147", "0.43770188", "0.4374655", "0.4374324", "0.43711475", "0.43670827", "0.43586275", "0.43563902", "0.43402576", "0.43393466", "0.4336835", "0.43269587", "0.42968938", "0.429687", "0.42954183", "0.4293601", "0.4293501", "0.42910483", "0.42852014", "0.42735183", "0.42715597", "0.42664865", "0.4258874", "0.42574772", "0.42560533", "0.42508784", "0.42496553", "0.42449176", "0.42438895" ]
0.45862538
46
Validate returns an error if the config is underspecified.
func (cfg Config) Validate() error { var errs []string if cfg.Releaser == nil { errs = append(errs, "releaser not supplied") } if cfg.History == nil { errs = append(errs, "history DB not supplied") } if len(errs) > 0 { return errors.New("invalid: " + strings.Join(errs, "; ")) } return nil }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c Config) Validate() error {\n\tif len(c.Project) == 0 {\n\t\treturn errors.New(\"missing project in configuration\")\n\t}\n\tif len(c.Bucket) == 0 {\n\t\treturn errors.New(\"missing bucket in configuration\")\n\t}\n\tif len(c.LastMigrationObjectName) == 0 {\n\t\treturn errors.New(\"missing state name in configuration\")\n\t}\n\treturn nil\n}", "func (c configuration) Validate() error {\n\tvar errs error\n\n\terrs = errors.Append(errs, c.Auth.Validate())\n\terrs = errors.Append(errs, c.Config.Validate())\n\n\tif c.Environment == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"environment is required\"))\n\t}\n\n\t// TODO: this config is only used here, so the validation is here too. Either the config or the validation should be moved somewhere else.\n\tif c.Distribution.PKE.Amazon.GlobalRegion == \"\" {\n\t\terrs = errors.Append(errs, errors.New(\"pke amazon global region is required\"))\n\t}\n\n\treturn errs\n}", "func validateConfig() {\n\tif viper.Get(\"project\") == \"\" {\n\t\tlog.Fatal(\"Error: --project is required\")\n\t}\n\tif viper.Get(\"region\") == \"\" {\n\t\tlog.Fatal(\"Error: --region is required, e.g. us-west1\")\n\t}\n}", "func (c *Config) Validate() error {\n\treturn nil\n}", "func (c *Config) Validate() error {\n\treturn nil\n}", "func (c *Config) Validate() error {\n\treturn nil\n}", "func (m *Config) Validate() error {\n\treturn m.validate(false)\n}", "func (c *Config) validate() error {\n\tif c.iface == \"\" {\n\t\treturn errors.New(\"the iface must be set\")\n\t}\n\tif c.protocal != \"\" && c.protocal != \"tcp\" && c.protocal != \"udp\" {\n\t\treturn errors.New(\"the protocl must be set to tcp or udp or both\")\n\t}\n\treturn nil\n}", "func (cfg config) Validate() {\n\tif v, exists := cfg[\"tls_min_version\"]; exists {\n\t\tvar t tlsMinVersionOption\n\t\terr := t.Set(fmt.Sprintf(\"%v\", v))\n\t\tif err == nil {\n\t\t\tnewVal := fmt.Sprintf(\"%v\", t.Get())\n\t\t\tif newVal != \"0\" {\n\t\t\t\tcfg[\"tls_min_version\"] = newVal\n\t\t\t} else {\n\t\t\t\tdelete(cfg, \"tls_min_version\")\n\t\t\t}\n\t\t} else {\n\t\t\tlogFatal(\"failed parsing tls_min_version %+v\", v)\n\t\t}\n\t}\n\tif v, exists := cfg[\"log_level\"]; exists {\n\t\tvar t lg.LogLevel\n\t\terr := t.Set(fmt.Sprintf(\"%v\", v))\n\t\tif err == nil {\n\t\t\tcfg[\"log_level\"] = t\n\t\t} else {\n\t\t\tlogFatal(\"failed parsing log_level %+v\", v)\n\t\t}\n\t}\n}", "func (mgc Config) Validate() error {\n\tif mgc.User == \"\" {\n\t\treturn errors.New(\"Config.User is required\")\n\t}\n\tif mgc.Password == \"\" {\n\t\treturn errors.New(\"Config.Password is required\")\n\t}\n\tif mgc.AuthDB == \"\" {\n\t\treturn errors.New(\"Config.AuthDB is required\")\n\t}\n\tif mgc.Host == \"\" {\n\t\treturn errors.New(\"Config.Host is required\")\n\t}\n\tif mgc.DB == \"\" {\n\t\treturn errors.New(\"Config.DB is required\")\n\t}\n\treturn nil\n}", "func (c *Config) validate() error {\n\tif len(c.Port) == 0 {\n\t\treturn errors.New(\"missing port\")\n\t}\n\n\terr := c.BackendServerConfigs.validate()\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"invalid backend servers configuration\")\n\t}\n\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.ApplicationID != \"\" && c.AlgoliaAPIKey == \"\" {\n\t\treturn errors.New(\"API key must not be empty if indexer is enabled\")\n\t}\n\tif c.ApplicationID != \"\" && c.AlgoliaSearchKey == \"\" {\n\t\treturn errors.New(\"Search key must not be empty if indexer is enabled\")\n\t}\n\tif c.ApplicationID != \"\" && c.IndexName == \"\" {\n\t\treturn errors.New(\"Index name must not be empty if indexer is enabled\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.PublicKeyPath == \"\" {\n\t\treturn errors.New(\"Public Key Path is required\")\n\t}\n\n\treturn nil\n}", "func (c *Config) Validate() error {\n\t// TODO(felix): complete validates\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tif c.Addr == \"\" {\n\t\treturn fmt.Errorf(\"Address of the curator can not be empty\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif len(c.ClientID) == 0 {\n\t\treturn fmt.Errorf(\"error: ClientID missing\")\n\t}\n\n\tif c.VodID < 1 {\n\t\treturn fmt.Errorf(\"error: VodID missing\")\n\t}\n\n\ttimePattern := `\\d+ \\d+ \\d+`\n\ttimeRegex := regexp.MustCompile(timePattern)\n\tif c.StartTime != \"start\" && !timeRegex.MatchString(c.StartTime) {\n\t\treturn fmt.Errorf(\"error: StartTime must be 'start' or in format '%s'; got '%s'\", timePattern, c.StartTime)\n\t}\n\tif c.EndTime == \"\" && c.Length == \"\" {\n\t\treturn errors.New(\"error: must specify either EndTime or Length\")\n\t}\n\tif c.Length == \"\" && c.EndTime != \"end\" && !timeRegex.MatchString(c.EndTime) {\n\t\treturn fmt.Errorf(\"error: EndTime must be 'end' or in format '%s'; got '%s'\", timePattern, c.EndTime)\n\t}\n\tif c.EndTime == \"\" && c.Length != \"full\" && !timeRegex.MatchString(c.Length) {\n\t\treturn fmt.Errorf(\"error: Length must be 'full' or in format '%s'; got '%s'\", timePattern, c.Length)\n\t}\n\n\tqualityPattern := `\\d{3,4}p[36]0`\n\tqualityRegex := regexp.MustCompile(qualityPattern)\n\tif c.Quality != \"best\" && c.Quality != \"chunked\" && !qualityRegex.MatchString(c.Quality) {\n\t\treturn fmt.Errorf(\"error: Quality must be 'best', 'chunked', or in format '%s'; got '%s'\", qualityPattern, c.Quality)\n\t}\n\n\tif c.FilePrefix != \"\" && !isValidFilename(c.FilePrefix) {\n\t\treturn fmt.Errorf(\"error: FilePrefix contains invalid characters; got '%s'\", c.FilePrefix)\n\t}\n\n\tif c.Workers < 1 {\n\t\treturn fmt.Errorf(\"error: Worker must be an integer greater than 0; got '%d'\", c.Workers)\n\t}\n\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.Key == \"\" {\n\t\treturn errors.New(\"missing DigitalOcean access key\")\n\t}\n\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.Host == \"\" {\n\t\treturn errors.New(\"cadence host is required\")\n\t}\n\n\tif c.Port == 0 {\n\t\treturn errors.New(\"cadence port is required\")\n\t}\n\n\tif c.Domain == \"\" {\n\t\treturn errors.New(\"cadence domain is required\")\n\t}\n\n\treturn nil\n}", "func (config *Config) Validate() error {\n\tif len(config.NsqLookupdAddress) == 0 {\n\t\treturn fmt.Errorf(\"parameter NsqLookupdAddress missing\")\n\t}\n\tif len(config.NsqdAddress) == 0 {\n\t\treturn fmt.Errorf(\"parameter NsqdAddress missing\")\n\t}\n\tif len(config.BotName) == 0 {\n\t\treturn fmt.Errorf(\"parameter BotName missing\")\n\t}\n\tif len(config.BambooUrl) == 0 {\n\t\treturn fmt.Errorf(\"parameter BambooUrl missing\")\n\t}\n\tif len(config.BambooUsername) == 0 {\n\t\treturn fmt.Errorf(\"parameter BambooUsername missing\")\n\t}\n\tif len(config.BambooPassword) == 0 {\n\t\treturn fmt.Errorf(\"parameter AuthUrl missing\")\n\t}\n\tif len(config.BambooPassword) == 0 {\n\t\treturn fmt.Errorf(\"parameter AuthApplicationName missing\")\n\t}\n\tif len(config.BambooPassword) == 0 {\n\t\treturn fmt.Errorf(\"parameter AuthApplicationPassword missing\")\n\t}\n\tif len(config.BambooPassword) == 0 {\n\t\treturn fmt.Errorf(\"parameter BambooPassword missing\")\n\t}\n\tif len(config.Prefix) == 0 {\n\t\treturn fmt.Errorf(\"parameter Prefix missing\")\n\t}\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif len(cfg.Key) == 0 {\n\t\treturn trace.BadParameter(`etcd: missing \"prefix\" parameter`)\n\t}\n\t// Make sure the prefix starts with a '/'.\n\tif cfg.Key[0] != '/' {\n\t\tcfg.Key = \"/\" + cfg.Key\n\t}\n\tif len(cfg.Nodes) == 0 {\n\t\treturn trace.BadParameter(`etcd: missing \"peers\" parameter`)\n\t}\n\tif !cfg.Insecure {\n\t\tif cfg.TLSCAFile == \"\" {\n\t\t\treturn trace.BadParameter(`etcd: missing \"tls_ca_file\" parameter`)\n\t\t}\n\t}\n\tif cfg.BufferSize == 0 {\n\t\tcfg.BufferSize = backend.DefaultBufferCapacity\n\t}\n\tif cfg.DialTimeout == 0 {\n\t\tcfg.DialTimeout = apidefaults.DefaultIOTimeout\n\t}\n\tif cfg.PasswordFile != \"\" {\n\t\tout, err := os.ReadFile(cfg.PasswordFile)\n\t\tif err != nil {\n\t\t\treturn trace.ConvertSystemError(err)\n\t\t}\n\t\t// trim newlines as passwords in files tend to have newlines\n\t\tcfg.Password = strings.TrimSpace(string(out))\n\t}\n\n\tif cfg.ClientPoolSize < 1 {\n\t\tcfg.ClientPoolSize = defaultClientPoolSize\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.CollectorEndpoint == \"\" && c.AgentEndpoint == \"\" {\n\t\treturn xerrors.New(\"jaeger: either collector endpoint or agent endpoint must be configured\")\n\t}\n\tif c.ServiceName == \"\" {\n\t\treturn xerrors.New(\"jaeger: service name must not be blank\")\n\t}\n\n\treturn nil\n}", "func validateConfig(appConfig AppConfig) error {\n\n\treturn nil\n}", "func Validate(cfg *Config) error {\n\tif cfg == nil {\n\t\treturn errors.New(\"config needs to be defined\")\n\t}\n\n\tvar result *multierror.Error\n\tif cfg.HostProvider == \"\" {\n\t\tresult = multierror.Append(result, errors.New(\"a host provider needs to be provided\"))\n\t}\n\tif cfg.BaseClusterCloudprovider == \"\" {\n\t\tresult = multierror.Append(result, errors.New(\"the cloudprovider of the hostcluster needs to be defined\"))\n\t}\n\tif cfg.Shoots.DefaultTest == nil {\n\t\tresult = multierror.Append(result, errors.New(\"a default test needs to be defined\"))\n\t}\n\n\tif cfg.Shoots.Namespace == \"\" {\n\t\tresult = multierror.Append(result, errors.New(\"the shoot project namespace has to be defined\"))\n\t}\n\n\tif cfg.Gardener.Version == \"\" && cfg.Gardener.Commit == \"\" {\n\t\tresult = multierror.Append(result, errors.New(\"a gardener version or commit has to be defined\"))\n\t}\n\n\tif len(cfg.GardenerExtensions) == 0 {\n\t\tresult = multierror.Append(result, errors.New(\"the gardener extensions have to be defined\"))\n\t}\n\n\treturn util.ReturnMultiError(result)\n}", "func (c *Config) Validate() (err error) {\n\t// Handle queue size\n\tif c.QueueSize <= 0 {\n\t\tc.QueueSize = defaultQueueSize\n\t}\n\n\t// Handle the number of workers\n\tif c.Workers <= 0 {\n\t\tc.Workers = runtime.NumCPU()\n\t}\n\n\t// Handle the addr\n\tif c.Addr == \"\" {\n\t\tc.Addr = defaultAddr\n\t}\n\n\t// Handle the metrics addr\n\tif c.MetricsAddr == \"\" {\n\t\tc.MetricsAddr = defaultMetricsAddr\n\t}\n\n\t// Handle the log level\n\tif c.LogLevel == \"\" {\n\t\tc.LogLevel = \"info\"\n\t} else {\n\t\tc.LogLevel = strings.ToLower(c.LogLevel)\n\t\tif _, ok := logLevels[c.LogLevel]; !ok {\n\t\t\treturn Errorf(ErrInvalidConfig, \"%q is an invalid log level, use trace, debug, info, caution, status, warn, or silent\", c.LogLevel)\n\t\t}\n\t}\n\tc.setLogLevel()\n\n\t// Handle the caution threshold\n\tif c.CautionThreshold == 0 {\n\t\tc.CautionThreshold = out.DefaultCautionThreshold\n\t}\n\tc.setCautionThreshold()\n\n\treturn nil\n}", "func (cfg Config) Validate() error {\n\treturn validation.ValidateStruct(\n\t\t&cfg,\n\t\tvalidation.Field(&cfg.NodeID, validation.Required),\n\t\tvalidation.Field(&cfg.ListenAddr, validation.Required, is.Host),\n\t\tvalidation.Field(&cfg.DataDir, validation.Required),\n\t\tvalidation.Field(&cfg.CompactionEnabled, validation.Required),\n\t\tvalidation.Field(&cfg.Peers),\n\t)\n}", "func (c *Config) Validate() error {\n\tif c.Address == \"\" {\n\t\treturn errors.New(\"the address of mockserver is required\")\n\t}\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.HTTPServerSettings == nil && cfg.GRPCServerSettings == nil {\n\t\treturn errAtLeastOneProtocol\n\t}\n\n\tif cfg.Source.File != \"\" && cfg.Source.Remote != nil {\n\t\treturn errTooManySources\n\t}\n\n\tif cfg.Source.File == \"\" && cfg.Source.Remote == nil {\n\t\treturn errNoSources\n\t}\n\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.HTTPServerSettings == nil && cfg.GRPCServerSettings == nil {\n\t\treturn errAtLeastOneProtocol\n\t}\n\n\tif cfg.Source.File != \"\" && cfg.Source.Remote != nil {\n\t\treturn errTooManySources\n\t}\n\n\tif cfg.Source.File == \"\" && cfg.Source.Remote == nil {\n\t\treturn errNoSources\n\t}\n\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.ID == \"\" {\n\t\treturn fmt.Errorf(\"consul discovery must be given a ID\")\n\t}\n\tif strings.TrimSpace(c.Address) == \"\" {\n\t\treturn fmt.Errorf(\"consul discovery requires a server address\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.ServiceName == \"\" {\n\t\treturn xerrors.New(\"ocagent: service name must not be blank\")\n\t}\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tvar errs []error\n\n\tif len(c.Hosts) == 0 {\n\t\terrs = append(errs, fmt.Errorf(\"missing hosts\"))\n\t}\n\tif c.Port == \"\" {\n\t\terrs = append(errs, fmt.Errorf(\"missing port\"))\n\t}\n\n\treturn apierrors.NewAggregate(errs)\n}", "func (cfg *Config) Validate() error {\n\tif len(cfg.Scrapers) == 0 {\n\t\treturn errors.New(\"must specify at least one scraper\")\n\t}\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tvar err error\n\tif c.Endpoint == \"\" {\n\t\terr = multierr.Append(err, errors.New(\"no manager endpoint was specified\"))\n\t\treturn err\n\t}\n\n\tres, err := url.Parse(c.Endpoint)\n\tif err != nil {\n\t\terr = multierr.Append(err, fmt.Errorf(\"unable to parse url %s: %w\", c.Endpoint, err))\n\t\treturn err\n\t}\n\n\tif res.Scheme != \"http\" && res.Scheme != \"https\" {\n\t\terr = multierr.Append(err, errors.New(\"url scheme must be http or https\"))\n\t}\n\n\tif c.Username == \"\" {\n\t\terr = multierr.Append(err, errors.New(\"username not provided and is required\"))\n\t}\n\n\tif c.Password == \"\" {\n\t\terr = multierr.Append(err, errors.New(\"password not provided and is required\"))\n\t}\n\treturn err\n}", "func (config appConfig) Validate() error {\n\treturn validator.New().Struct(&config)\n}", "func (c *Config) Validate() error {\n\tlogrus.Trace(\"validating config configuration\")\n\n\t// verify server is provided\n\tif len(c.Server) == 0 {\n\t\treturn fmt.Errorf(\"no config server provided\")\n\t}\n\n\t// check to make sure it's a valid url\n\t_, err := url.ParseRequestURI(c.Server)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%s is not a valid url\", c.Server)\n\t}\n\n\t// verify token is provided\n\tif len(c.Token) == 0 {\n\t\treturn fmt.Errorf(\"no config token provided\")\n\t}\n\n\treturn nil\n}", "func (c config) validate() error {\n\tif c.MinPort <= 0 || c.MaxPort <= 0 {\n\t\treturn errors.New(\"min Port and Max Port values are required\")\n\t}\n\tif c.MaxPort < c.MinPort {\n\t\treturn errors.New(\"max Port cannot be set less that the Min Port\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\tif c.ResetSeconds <= 0 {\n\t\treturn errors.New(\"ResetSeconds must be positive\")\n\t}\n\tif c.StreakBreakSeconds <= 0 {\n\t\treturn errors.New(\"StreakBreakSeconds must be positive\")\n\t}\n\tif c.Wheels == nil {\n\t\treturn errors.New(\"wheels cannot be null\")\n\t}\n\tif err := c.Wheels.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"failed to validate wheels\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() (err error) {\n\tvar fi os.FileInfo\n\n\t// validate key fingerprint\n\t_, err = HexStringToFingerprint(c.MasterKeyFingerprint)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// validate TLSCert\n\tif len(c.TLSCert) == 0 {\n\t\treturn errors.New(\"Missing config param: TLSCert\")\n\t}\n\tfi, err = os.Stat(c.TLSCert)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in TLSCert '%s': %s\", c.TLSCert, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in TLSCert '%s': expected file path, got directory\", c.TLSCert)\n\t}\n\n\t// validate TLSKey\n\tif len(c.TLSKey) == 0 {\n\t\treturn errors.New(\"Missing config param: TLSKey\")\n\t}\n\tfi, err = os.Stat(c.TLSKey)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in TLSKey '%s': %s\", c.TLSKey, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in TLSKey '%s': expected file path, got directory\", c.TLSKey)\n\t}\n\n\t// validate SecRing\n\tif len(c.SecRing) == 0 {\n\t\treturn errors.New(\"Missing config param: SecRing\")\n\t}\n\tfi, err = os.Stat(c.SecRing)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in SecRing '%s': %s\", c.SecRing, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in SecRing '%s': expected file path, got directory\", c.SecRing)\n\t}\n\n\t// validate ProdSupportPubRing\n\tif len(c.ProdSupportPubRing) == 0 {\n\t\treturn errors.New(\"Missing config param: ProdSupportPubRing\")\n\t}\n\tfi, err = os.Stat(c.ProdSupportPubRing)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in ProdSupportPubRing '%s': %s\", c.ProdSupportPubRing, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in ProdSupportPubRing '%s': expected file path, got directory\", c.ProdSupportPubRing)\n\t}\n\n\t// validate DataRoot\n\tif len(c.DataRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: DataRoot\")\n\t}\n\tfi, err = os.Stat(c.DataRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.DataRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in DataRoot '%s': %s\", c.DataRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in DataRoot '%s': expected directory, got file path\", c.DataRoot)\n\t\t}\n\t}\n\n\t// validate ProdSupportDir\n\tif len(c.ProdSupportDir) == 0 {\n\t\treturn errors.New(\"Missing config param: ProdSupportDir\")\n\t}\n\tfi, err = os.Stat(c.ProdSupportDir)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.ProdSupportDir, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in ProdSupportDir '%s': %s\", c.ProdSupportDir, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in ProdSupportDir '%s': expected directory, got file path\", c.ProdSupportDir)\n\t\t}\n\t}\n\n\t// validate KeyRoot\n\tif len(c.KeyRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: KeyRoot\")\n\t}\n\tfi, err = os.Stat(c.KeyRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.KeyRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in KeyRoot '%s': %s\", c.KeyRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in KeyRoot '%s': expected directory, got file path\", c.KeyRoot)\n\t\t}\n\t}\n\n\t// validate MetaRoot\n\tif len(c.MetaRoot) == 0 {\n\t\treturn errors.New(\"Missing config param: MetaRoot\")\n\t}\n\tfi, err = os.Stat(c.MetaRoot)\n\tif err != nil {\n\t\t// doesn't exist... can we create it?\n\t\tif err = os.MkdirAll(c.MetaRoot, 0744); err != nil {\n\t\t\treturn fmt.Errorf(\"Config error in MetaRoot '%s': %s\", c.MetaRoot, err)\n\t\t}\n\t} else {\n\t\tif !fi.IsDir() {\n\t\t\treturn fmt.Errorf(\"Config error in MetaRoot '%s': expected directory, got file path\", c.MetaRoot)\n\t\t}\n\t}\n\n\t// validate HTTPLog\n\tif len(c.HTTPLog) > 0 {\n\t\tfi, err = os.Stat(filepath.Dir(c.HTTPLog))\n\t\tif err != nil {\n\t\t\t// doesn't exist... can we create it?\n\t\t\tif err = os.MkdirAll(filepath.Dir(c.HTTPLog), 0744); err != nil {\n\t\t\t\treturn fmt.Errorf(\"Config error in HTTPLog '%s': %s\", c.HTTPLog, err)\n\t\t\t}\n\t\t}\n\t}\n\n\t// validate HtpasswdFile\n\tif len(c.HtpasswdFile) == 0 {\n\t\treturn errors.New(\"Missing config param: HtpasswdFile\")\n\t}\n\tfi, err = os.Stat(c.HtpasswdFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Config error in HtpasswdFile '%s': %s\", c.HtpasswdFile, err)\n\t}\n\tif fi.IsDir() {\n\t\treturn fmt.Errorf(\"Config error in HtpasswdFile '%s': expected file path, got directory\", c.HtpasswdFile)\n\t}\n\n\tif len(c.MasterKeyPassphrase) == 0 {\n\t\tlog.Println(\"no passphrase specified for secure keyring\")\n\t}\n\n\treturn nil\n}", "func (c *Configuration) Validate() error {\n\n\tif c.Database == \"\" {\n\t\treturn errors.EValidation(\"Missing Database\", nil)\n\t}\n\n\tif c.MongoURL == \"\" {\n\t\treturn errors.EValidation(\"Missing ConnectionString\", nil)\n\t}\n\n\treturn nil\n}", "func (c *Config) Validate(log log.Logger) error {\n\tif err := c.SchemaConfig.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"invalid schema config\")\n\t}\n\tif err := c.StorageConfig.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"invalid storage config\")\n\t}\n\tif err := c.QueryRange.Validate(log); err != nil {\n\t\treturn errors.Wrap(err, \"invalid queryrange config\")\n\t}\n\tif err := c.TableManager.Validate(); err != nil {\n\t\treturn errors.Wrap(err, \"invalid tablemanager config\")\n\t}\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.MetricTTL <= 0 {\n\t\treturn errors.New(\"disk.metric_ttl is invalid\")\n\t}\n\n\tif cfg.MetricType.String() == \"\" {\n\t\treturn errors.New(\"disk.metric_type is invalid\")\n\t}\n\treturn nil\n}", "func (config *Configuration) validate() (isValid bool) {\n\tisValid = true // until proven otherwise\n\n\tmissing := func(str string) {\n\t\tfmt.Fprintf(os.Stderr, \"error: invalid config file: %s\\n\", str)\n\t\tisValid = false\n\t}\n\n\tif len(config.Spec) == 0 {\n\t\tmissing(\"no files/directories specified in the config file's spec.\")\n\t}\n\n\treturn\n}", "func (c *Config) Validate() liberr.Error {\n\tvar e = ErrorValidatorError.Error(nil)\n\n\tif err := libval.New().Struct(c); err != nil {\n\t\tif er, ok := err.(*libval.InvalidValidationError); ok {\n\t\t\te.Add(er)\n\t\t}\n\n\t\tfor _, er := range err.(libval.ValidationErrors) {\n\t\t\t//nolint #goerr113\n\t\t\te.Add(fmt.Errorf(\"config field '%s' is not validated by constraint '%s'\", er.Namespace(), er.ActualTag()))\n\t\t}\n\t}\n\n\tif !e.HasParent() {\n\t\te = nil\n\t}\n\n\treturn e\n}", "func (c *Config) Validate() error {\n\tif c.Transport == nil {\n\t\treturn util.Error(\"Transport is required\")\n\t}\n\tif c.ElectionTimeoutTicks == 0 {\n\t\treturn util.Error(\"ElectionTimeoutTicks must be non-zero\")\n\t}\n\tif c.HeartbeatIntervalTicks == 0 {\n\t\treturn util.Error(\"HeartbeatIntervalTicks must be non-zero\")\n\t}\n\tif c.TickInterval == 0 {\n\t\treturn util.Error(\"TickInterval must be non-zero\")\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\t// Check DbConfig\n\tif err := c.Db.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"error verifying db config: %s\", err.Error())\n\t}\n\n\t// Check AuthConfig\n\tif err := c.Auth.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"error verifying auth config: %s\", err.Error())\n\t}\n\n\t// All good\n\treturn nil\n}", "func (c *Config) validate() error {\n\t/* Metrics */\n\n\t// Users can omit the metrics block entirely to disable metrics reporting.\n\tif c.Metrics != nil && c.Metrics.Statsd != nil {\n\t\tif c.Metrics.Statsd.Address == \"\" {\n\t\t\treturn fmt.Errorf(\"config: missing metrics statsd address\")\n\t\t}\n\n\t\tif c.Metrics.Statsd.SampleRate < 0 || c.Metrics.Statsd.SampleRate > 1 {\n\t\t\treturn fmt.Errorf(\"config: statsd sample rate must be in range [0.0, 1.0]\")\n\t\t}\n\t}\n\n\t/* Listener */\n\n\tif c.Listener == nil {\n\t\treturn fmt.Errorf(\"config: missing top-level listener config key\")\n\t}\n\n\tif c.Listener.TCP == nil && c.Listener.UDP == nil {\n\t\treturn fmt.Errorf(\"config: at least one TCP or UDP listener must be specified\")\n\t}\n\n\tif c.Listener.TCP != nil && c.Listener.TCP.Address == \"\" {\n\t\treturn fmt.Errorf(\"config: missing TCP server listening address\")\n\t}\n\n\tif c.Listener.UDP != nil && c.Listener.UDP.Address == \"\" {\n\t\treturn fmt.Errorf(\"config: missing UDP server listening address\")\n\t}\n\n\t/* Upstream */\n\n\tif c.Upstream == nil {\n\t\treturn fmt.Errorf(\"config: missing top-level upstream config key\")\n\t}\n\n\t// Validate the load balancing policy, only if provided (empty signifies default).\n\tif c.Upstream.LoadBalancingPolicy != \"\" {\n\t\tif _, ok := network.ParseLoadBalancingPolicy(c.Upstream.LoadBalancingPolicy); !ok {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"config: unknown load balancing policy: policy=%s\",\n\t\t\t\tc.Upstream.LoadBalancingPolicy,\n\t\t\t)\n\t\t}\n\t}\n\n\tif len(c.Upstream.Servers) == 0 {\n\t\treturn fmt.Errorf(\"config: no upstream servers specified\")\n\t}\n\n\tfor idx, server := range c.Upstream.Servers {\n\t\tif server.Address == \"\" {\n\t\t\treturn fmt.Errorf(\"config: missing server address: idx=%d\", idx)\n\t\t}\n\n\t\tif server.ServerName == \"\" {\n\t\t\treturn fmt.Errorf(\"config: missing server TLS hostname: idx=%d\", idx)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tif len(c.PrometheusURL) > 0 {\n\t\tif _, err := url.Parse(c.PrometheusURL); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif len(c.LogFormat) > 0 {\n\t\tif !mapLogFormat[c.LogFormat] {\n\t\t\treturn fmt.Errorf(`invalid value for logFormat. \"%s\" Valid values are \"%s\" or \"%s\"`, c.LogFormat, TextFormat, JSONFormat)\n\t\t}\n\t} else {\n\t\t// default value\n\t\tc.LogFormat = TextFormat\n\t}\n\n\treturn nil\n}", "func (config configuration) validate() error {\n\t_, err := govalidator.ValidateStruct(&config)\n\treturn err\n}", "func validateConfig(config ProvisionerConfig) error {\n\tswitch config.CloudProvider {\n\tcase constants.AWS, constants.Azure, constants.GCE, constants.Ops:\n\tdefault:\n\t\treturn trace.BadParameter(\"unknown cloud provider %s\", config.CloudProvider)\n\t}\n\n\terr := validator.New().Struct(&config)\n\tif err == nil {\n\t\treturn nil\n\t}\n\n\tvar errs []error\n\tif validationErrors, ok := err.(validator.ValidationErrors); ok {\n\t\tfor _, fieldError := range validationErrors {\n\t\t\terrs = append(errs,\n\t\t\t\ttrace.BadParameter(` * %s=\"%v\" fails \"%s\"`,\n\t\t\t\t\tfieldError.Field(), fieldError.Value(), fieldError.Tag()))\n\t\t}\n\t}\n\treturn trace.NewAggregate(errs...)\n}", "func (c *Config) Validate() error {\n\tif c.ServerConf.RestAPIPort < 0 || c.ServerConf.RestAPIPort > 65535 {\n\t\treturn errors.New(\"invalid restful port: \" + strconv.Itoa(c.ServerConf.RestAPIPort))\n\t}\n\n\t// remove \"/\"\n\tc.ZeekConf.LogDir = processDirName(c.ZeekConf.LogDir)\n\tc.ZeekConf.PcapDir = processDirName(c.ZeekConf.PcapDir)\n\tc.ZeekConf.ExtractedFileDir = processDirName(c.ZeekConf.ExtractedFileDir)\n\tc.SeaweedfsConf.ExtractedFileDir = processDirName(c.SeaweedfsConf.ExtractedFileDir)\n\n\tif c.SeaweedfsConf.Retries < 1 {\n\t\treturn errors.New(\"seaweedfs post retry times < 1\")\n\t}\n\treturn nil\n}", "func (cfg *Config) validate() error {\n\tif cfg.Range&^rangebits != 0 && cfg.Range != 1 {\n\t\treturn ErrBadRange\n\t}\n\treturn nil\n}", "func (c *Config) Validate() {\n\tif c.Global.TempDir == \"\" {\n\t\tc.Global.TempDir = \"/tmp/\"\n\t} else if !strings.HasSuffix(c.Global.TempDir, \"/\") {\n\t\tc.Global.TempDir += \"/\"\n\t}\n\tif c.Imessage.QueueSize < 20 {\n\t\tc.Imessage.QueueSize = 20\n\t}\n}", "func (c *configuration) validateConfig() error {\n\tif c.Provider == \"\" {\n\t\treturn errors.New(msgConfigNoProvider)\n\t}\n\n\tif len(c.Servers) == 0 {\n\t\treturn errors.New(msgConfigNoServers)\n\t}\n\n\tfor i, srv := range c.Servers {\n\t\tif srv.FabricIface == \"\" {\n\t\t\treturn errors.Errorf(\n\t\t\t\tmsgConfigServerNoIface+\" for I/O service %d\", i)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (c *Config) Validate() (err error) {\n\terr = validation.ValidateStruct(c,\n\t\tvalidation.Field(&c.GithubAPIToken, validation.Required),\n\t\tvalidation.Field(&c.GithubOrganization, validation.Required),\n\t)\n\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// Validate Github Team exists\n\tif c.GithubTeamName == \"\" && c.GithubTeamID == 0 {\n\t\terr = errors.New(\"Team name or Team id should be specified\")\n\t}\n\n\treturn\n}", "func (cfg *Config) Validate() error {\n\tif cfg.PushPreCheck == nil {\n\t\treturn fmt.Errorf(\"PreCheck is required\")\n\t}\n\tif cfg.PushFinalCheck == nil {\n\t\treturn fmt.Errorf(\"FinalCheck is required\")\n\t}\n\treturn nil\n}", "func (config AppConfigStruct) Validate() error {\n\treturn nil\n}", "func (c Config) Validate() error {\n\treturn validation.ValidateStruct(&c,\n\t\tvalidation.Field(&c.AppMode, validation.Required),\n\t\tvalidation.Field(&c.AppName, validation.Required),\n\t\tvalidation.Field(&c.DBType, validation.Required),\n\t\tvalidation.Field(&c.DSN, validation.Required),\n\t\tvalidation.Field(&c.JWTSigningKey, validation.Required),\n\t\tvalidation.Field(&c.JWTExpiration, validation.Required),\n\t\tvalidation.Field(&c.MailSmtphost, validation.Required),\n\t\tvalidation.Field(&c.MailSmtpport, validation.Required),\n\t\tvalidation.Field(&c.MailUsername, validation.Required),\n\t\tvalidation.Field(&c.MailPassword, validation.Required),\n\t\tvalidation.Field(&c.AppFqdn, validation.Required),\n\t\tvalidation.Field(&c.HttpEntrypoint, validation.Required),\n\t\tvalidation.Field(&c.WebservName, validation.Required),\n\t\tvalidation.Field(&c.GoogleCredentialFile, validation.Required),\n\t\tvalidation.Field(&c.GoogleRedirectPath, validation.Required),\n\t\tvalidation.Field(&c.AppSecretKey, validation.Required),\n\t\tvalidation.Field(&c.BizName, validation.Required),\n\t\tvalidation.Field(&c.BizShortname, validation.Required),\n\t\tvalidation.Field(&c.BizEmail, validation.Required),\n\t\tvalidation.Field(&c.BizPhone),\n\t\tvalidation.Field(&c.BizPhone2),\n\t\tvalidation.Field(&c.BizLogo, validation.Required),\n\t)\n}", "func (c *Config) Validate() error {\n\n\tif err := c.Data.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t//if err := c.HintedHandoff.Validate(); err != nil {\n\t//\treturn err\n\t//}\n\tfor _, graphite := range c.GraphiteInputs {\n\t\tif err := graphite.Validate(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid graphite config: %v\", err)\n\t\t}\n\t}\n\n\tif err := c.Monitor.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.ContinuousQuery.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Retention.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Precreator.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tif err := c.Subscriber.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tfor _, collectd := range c.CollectdInputs {\n\t\tif err := collectd.Validate(); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid collectd config: %v\", err)\n\t\t}\n\t}\n\n\tif err := c.TLS.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *operatorConfig) validate() (err error) {\n\tswitch config := c; {\n\tcase config.serverVersion == nil:\n\t\terr = newInvalidOperatorConfigError(\"discovery client nil\")\n\tcase config.numWorkers < 1:\n\t\terr = newInvalidOperatorConfigError(\"must specify at least one worker per queue\")\n\t}\n\n\treturn\n}", "func (c *Config) Validate() error {\n\tvar allErrs error\n\n\tif c.Endpoint == \"\" {\n\t\treturn multierr.Append(allErrs, errEmptyEndpoint)\n\t}\n\n\thost, portStr, err := net.SplitHostPort(c.Endpoint)\n\tif err != nil {\n\t\treturn multierr.Append(allErrs, fmt.Errorf(\"%w: %s\", errBadEndpoint, err.Error()))\n\t}\n\n\tif host == \"\" {\n\t\tallErrs = multierr.Append(allErrs, errBadEndpoint)\n\t}\n\n\tport, err := strconv.ParseInt(portStr, 10, 32)\n\tif err != nil {\n\t\tallErrs = multierr.Append(allErrs, fmt.Errorf(\"%w: %s\", errBadPort, err.Error()))\n\t}\n\n\tif port < 0 || port > 65535 {\n\t\tallErrs = multierr.Append(allErrs, fmt.Errorf(\"%w: %d\", errBadPort, port))\n\t}\n\n\tif c.Username != \"\" && c.Password == \"\" {\n\t\tallErrs = multierr.Append(allErrs, errEmptyPassword)\n\t}\n\n\tif c.Password != \"\" && c.Username == \"\" {\n\t\tallErrs = multierr.Append(allErrs, errEmptyUsername)\n\t}\n\tif c.Timeout.Milliseconds() < 0 {\n\t\tallErrs = multierr.Append(allErrs, fmt.Errorf(\"%w: must be positive\", errNegativeTimeout))\n\t}\n\n\tif c.TLS != nil {\n\t\t_, err := c.TLS.LoadTLSConfig()\n\t\tif err != nil {\n\t\t\tallErrs = multierr.Append(allErrs, fmt.Errorf(\"%w: %s\", errFailedTLSLoad, err.Error()))\n\t\t}\n\t}\n\n\tif c.TLS != nil && c.TLSName == \"\" {\n\t\tallErrs = multierr.Append(allErrs, fmt.Errorf(\"%w: when using TLS\", errEmptyEndpointTLSName))\n\t}\n\n\treturn allErrs\n}", "func (c *appConfig) Validate() error {\n\treturn validator.New().Struct(c)\n}", "func (cfg *Config) Validate() error {\n\tchecks := []struct {\n\t\tbad bool\n\t\terrMsg string\n\t}{\n\t\t{cfg.AuthorizeURL == \"\", \"no authorizeURL specified\"},\n\t\t{cfg.TokenURL == \"\", \"no tokenURL specified\"},\n\t\t{cfg.ClientID == \"\", \"no clientID specified\"},\n\t\t{cfg.ClientSecret == \"\" && !cfg.AllowEmptyClientSecret, \"no clientSecret specified\"},\n\t\t{cfg.RedirectURL == \"\", \"no redirectURL specified\"},\n\t\t{cfg.SessionSecurityKey == \"\", \"no SessionSecurityKey specified\"},\n\t\t{cfg.APIServerURL == \"\", \"no apiServerURL specified\"},\n\t}\n\n\tfor _, check := range checks {\n\t\tif check.bad {\n\t\t\treturn fmt.Errorf(\"invalid config: %s\", check.errMsg)\n\t\t}\n\t}\n\treturn nil\n}", "func validateConfig(conf *Config) {\n\t// Hopefully lxc package derives this correctly\n\tif conf.LXCPath == \"\" {\n\t\tconf.LXCPath = lxc.DefaultConfigPath()\n\t}\n\n\t// Generate \"Docker-style\" container names if it is not provided\n\tif conf.Name == \"\" {\n\t\tconf.Name = randomdata.SillyName()\n\t}\n}", "func (config *Config) Validate() error {\n\n\tif _, err := os.Stat(filepath.Join(config.KirdPath, config.KernelFile)); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"kernel '%s' not found\", filepath.Join(config.KirdPath, config.KernelFile))\n\t}\n\tif _, err := os.Stat(filepath.Join(config.KirdPath, config.InitrdFile)); os.IsNotExist(err) {\n\t\treturn fmt.Errorf(\"initrd '%s' not found\", filepath.Join(config.KirdPath, config.InitrdFile))\n\t}\n\n\t// Ensure all the MappedVirtualDisks exist on the host\n\tfor _, mvd := range config.MappedVirtualDisks {\n\t\tif _, err := os.Stat(mvd.HostPath); err != nil {\n\t\t\treturn fmt.Errorf(\"mapped virtual disk '%s' not found\", mvd.HostPath)\n\t\t}\n\t\tif mvd.ContainerPath == \"\" {\n\t\t\treturn fmt.Errorf(\"mapped virtual disk '%s' requested without a container path\", mvd.HostPath)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (d Config) Validate() error {\n\tif d.ID == \"\" {\n\t\treturn fmt.Errorf(\"dns discovery must be given a ID\")\n\t}\n\tswitch strings.ToUpper(d.Type) {\n\tcase \"SRV\":\n\tcase \"A\", \"AAAA\":\n\t\tif d.Port == 0 {\n\t\t\treturn fmt.Errorf(\"Port required for dns discovery type %s\", d.Type)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid dns discovery records type %s\", d.Type)\n\t}\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif !cfg.LogDataEnabled && !cfg.ProfilingDataEnabled {\n\t\treturn errors.New(`either \"log_data_enabled\" or \"profiling_data_enabled\" has to be true`)\n\t}\n\tif cfg.HTTPClientSettings.Endpoint == \"\" {\n\t\treturn errors.New(`requires a non-empty \"endpoint\"`)\n\t}\n\t_, err := cfg.getURL()\n\tif err != nil {\n\t\treturn fmt.Errorf(`invalid \"endpoint\": %w`, err)\n\t}\n\tif cfg.Token == \"\" {\n\t\treturn errors.New(`requires a non-empty \"token\"`)\n\t}\n\n\tif cfg.MaxContentLengthLogs > maxContentLengthLogsLimit {\n\t\treturn fmt.Errorf(`requires \"max_content_length_logs\" <= %d`, maxContentLengthLogsLimit)\n\t}\n\n\tif cfg.MaxContentLengthMetrics > maxContentLengthMetricsLimit {\n\t\treturn fmt.Errorf(`requires \"max_content_length_metrics\" <= %d`, maxContentLengthMetricsLimit)\n\t}\n\n\tif cfg.MaxContentLengthTraces > maxContentLengthTracesLimit {\n\t\treturn fmt.Errorf(`requires \"max_content_length_traces\" <= %d`, maxContentLengthTracesLimit)\n\t}\n\n\tif cfg.MaxEventSize > maxMaxEventSize {\n\t\treturn fmt.Errorf(`requires \"max_event_size\" <= %d`, maxMaxEventSize)\n\t}\n\n\tif err := cfg.QueueSettings.Validate(); err != nil {\n\t\treturn fmt.Errorf(\"sending_queue settings has invalid configuration: %w\", err)\n\t}\n\treturn nil\n}", "func (v *Config) Validate() error {\n\tctx := v.ctx\n\n\tif v.Log.Level == \"info\" {\n\t\tWarn.Println(ctx, \"info level hurts performance\")\n\t}\n\n\tif len(v.Stat.Disks) > 0 {\n\t\tWarn.Println(ctx, \"stat disks not support\")\n\t}\n\n\tif v.Workers < 0 || v.Workers > 64 {\n\t\treturn fmt.Errorf(\"workers must in [0, 64], actual is %v\", v.Workers)\n\t}\n\tif v.Listen <= 0 || v.Listen > 65535 {\n\t\treturn fmt.Errorf(\"listen must in (0, 65535], actual is %v\", v.Listen)\n\t}\n\tif v.ChunkSize < 128 || v.ChunkSize > 65535 {\n\t\treturn fmt.Errorf(\"chunk_size must in [128, 65535], actual is %v\", v.ChunkSize)\n\t}\n\n\tif v.Go.GcInterval < 0 || v.Go.GcInterval > 24*3600 {\n\t\treturn fmt.Errorf(\"go gc_interval must in [0, 24*3600], actual is %v\", v.Go.GcInterval)\n\t}\n\n\tif v.Log.Level != \"info\" && v.Log.Level != \"trace\" && v.Log.Level != \"warn\" && v.Log.Level != \"error\" {\n\t\treturn fmt.Errorf(\"log.leve must be info/trace/warn/error, actual is %v\", v.Log.Level)\n\t}\n\tif v.Log.Tank != \"console\" && v.Log.Tank != \"file\" {\n\t\treturn fmt.Errorf(\"log.tank must be console/file, actual is %v\", v.Log.Tank)\n\t}\n\tif v.Log.Tank == \"file\" && len(v.Log.File) == 0 {\n\t\treturn errors.New(\"log.file must not be empty for file tank\")\n\t}\n\n\tfor i, p := range v.Vhosts {\n\t\tif p.Name == \"\" {\n\t\t\treturn fmt.Errorf(\"the %v vhost is empty\", i)\n\t\t}\n\t}\n\n\treturn nil\n}", "func (kce *KafkaConfigExecutor) Validate(config *gateways.ConfigContext) error {\n\tkafkaConfig, err := parseConfig(config.Data.Config)\n\tif err != nil {\n\t\treturn gateways.ErrConfigParseFailed\n\t}\n\tif kafkaConfig == nil {\n\t\treturn fmt.Errorf(\"%+v, configuration must be non empty\", gateways.ErrInvalidConfig)\n\t}\n\tif kafkaConfig.URL == \"\" {\n\t\treturn fmt.Errorf(\"%+v, url must be specified\", gateways.ErrInvalidConfig)\n\t}\n\tif kafkaConfig.Topic == \"\" {\n\t\treturn fmt.Errorf(\"%+v, topic must be specified\", gateways.ErrInvalidConfig)\n\t}\n\tif kafkaConfig.Partition == \"\" {\n\t\treturn fmt.Errorf(\"%+v, partition must be specified\", gateways.ErrInvalidConfig)\n\t}\n\treturn nil\n}", "func (c *Configuration) Validate() error {\n\tif c.PeekMax < 0 {\n\t\treturn errors.New(\"The maximum peek depth for PipeScript must be > 0\")\n\t}\n\tif c.SplitMax < 0 {\n\t\treturn errors.New(\"The maximum data split size in PipeScript must be > 0\")\n\t}\n\tif c.StringMax < 0 {\n\t\treturn errors.New(\"The maximum string size in PipeScript must be > 0\")\n\t}\n\n\treturn nil\n}", "func (o *AddConfig) Validate() error {\n\terr := o.ResultDetails.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(strings.TrimSpace(o.ImageSourcePath)) == 0 {\n\t\treturn errors.New(\"please specify a tile image source path\")\n\t}\n\n\tif o.Mode == 0 {\n\t\to.Mode = defaultImageMode\n\t}\n\n\treturn nil\n}", "func (a FIFOTopicAdvanceConfig) validate() error {\n\treturn nil\n}", "func validateConfig(args ArgCollection) error {\n\texpectedKeys := []string{}\n\tconfigFileRequired := false\n\tif args.ProviderFlag == \"custom\" {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"providers.custom.insecure\", \"providers.custom.endpoint_format\", \"providers.custom.regions\", \"providers.custom.address_style\"}...)\n\t}\n\tif args.WriteToDB {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"db.uri\"}...)\n\t}\n\tif args.UseMq {\n\t\tconfigFileRequired = true\n\t\texpectedKeys = append(expectedKeys, []string{\"mq.queue_name\", \"mq.uri\"}...)\n\t}\n\t// User didn't give any arguments that require the config file\n\tif !configFileRequired {\n\t\treturn nil\n\t}\n\n\t// Try to find and read config file\n\tif err := viper.ReadInConfig(); err != nil {\n\t\tif _, ok := err.(viper.ConfigFileNotFoundError); ok {\n\t\t\treturn errors.New(\"config file not found\")\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// Verify all expected keys are in the config file\n\tfor _, k := range expectedKeys {\n\t\tif !viper.IsSet(k) {\n\t\t\treturn fmt.Errorf(\"config file missing key: %s\", k)\n\t\t}\n\t}\n\treturn nil\n}", "func (c Config) Validate() error {\n\treturn validation.ValidateStruct(&c,\n\t\tvalidation.Field(\n\t\t\t&c.Database,\n\t\t),\n\t)\n}", "func (c *ServiceConfig) Validate() error {\n\tif c.Name == \"\" {\n\t\treturn errors.New(\"Name must be set\")\n\t}\n\n\tif c.ID == \"\" {\n\t\treturn errors.New(\"ID must be set\")\n\t}\n\n\tif c.Network == \"\" {\n\t\treturn errors.New(\"nginx.network must be set\")\n\t}\n\n\t//calculate max parameter length\n\tmax := len(c.Ports)\n\n\tif l := len(c.ListenIPs); l > max {\n\t\tmax = l\n\t}\n\tif l := len(c.ListenPorts); l > max {\n\t\tmax = l\n\t}\n\tif l := len(c.ListenProtos); l > max {\n\t\tmax = l\n\t}\n\n\t//verify parameter lengths\n\tif l := len(c.Ports); l == 1 {\n\t\tfor i := 1; i < max; i++ {\n\t\t\tc.Ports = append(c.Ports, c.Ports[0])\n\t\t}\n\t} else if l < max {\n\t\treturn fmt.Errorf(\"nginx.port length mismatch. Expected %d or 1, got %d\", max, l)\n\t}\n\n\tif l := len(c.ListenIPs); l == 1 {\n\t\tfor i := 1; i < max; i++ {\n\t\t\tc.ListenIPs = append(c.ListenIPs, c.ListenIPs[0])\n\t\t}\n\t} else if l < max {\n\t\treturn fmt.Errorf(\"nginx.listenIP length mismatch. Expected %d or 1, got %d\", max, l)\n\t}\n\n\tif l := len(c.ListenPorts); l == 1 {\n\t\tfor i := 1; i < max; i++ {\n\t\t\tc.ListenPorts = append(c.ListenPorts, c.ListenPorts[0])\n\t\t}\n\t} else if l < max {\n\t\treturn fmt.Errorf(\"nginx.listenPort length mismatch. Expected %d or 1, got %d\", max, l)\n\t}\n\n\tif l := len(c.ListenProtos); l == 1 {\n\t\tfor i := 1; i < max; i++ {\n\t\t\tc.ListenProtos = append(c.ListenProtos, c.ListenProtos[0])\n\t\t}\n\t} else if l < max {\n\t\treturn fmt.Errorf(\"nginx.listenProto length mismatch. Expected %d or 1, got %d\", max, l)\n\t}\n\n\treturn nil\n}", "func (c *DataGeneratorConfig) Validate() error {\n\terr := c.BaseConfig.Validate()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif c.InitialScale == 0 {\n\t\tc.InitialScale = c.BaseConfig.Scale\n\t}\n\n\tif c.LogInterval == 0 {\n\t\treturn fmt.Errorf(errLogIntervalZero)\n\t}\n\n\terr = utils.ValidateGroups(c.InterleavedGroupID, c.InterleavedNumGroups)\n\n\tif c.Use == UseCaseDevopsGeneric && c.MaxMetricCountPerHost < 1 {\n\t\treturn fmt.Errorf(errMaxMetricCountValue)\n\t}\n\n\treturn err\n}", "func (m *StatsConfig) Validate() error {\n\treturn m.validate(false)\n}", "func (c *Config) Validate() error {\n\t// Resolve symlinks.\n\tfor i, p := range c.Paths {\n\t\tif evalPath, err := filepath.EvalSymlinks(p); err == nil {\n\t\t\tc.Paths[i] = evalPath\n\t\t}\n\t}\n\t// Sort and deduplicate.\n\tsort.Strings(c.Paths)\n\tc.Paths = deduplicate(c.Paths)\n\n\tvar errs multierror.Errors\n\tvar err error\n\nnextHash:\n\tfor _, ht := range c.HashTypes {\n\t\tht = HashType(strings.ToLower(string(ht)))\n\t\tfor _, validHash := range validHashes {\n\t\t\tif ht == validHash {\n\t\t\t\tcontinue nextHash\n\t\t\t}\n\t\t}\n\t\terrs = append(errs, errors.Errorf(\"invalid hash_types value '%v'\", ht))\n\t}\n\n\tc.MaxFileSizeBytes, err = humanize.ParseBytes(c.MaxFileSize)\n\tif err != nil {\n\t\terrs = append(errs, errors.Wrap(err, \"invalid max_file_size value\"))\n\t} else if c.MaxFileSizeBytes <= 0 {\n\t\terrs = append(errs, errors.Errorf(\"max_file_size value (%v) must be positive\", c.MaxFileSize))\n\t}\n\n\tc.ScanRateBytesPerSec, err = humanize.ParseBytes(c.ScanRatePerSec)\n\tif err != nil {\n\t\terrs = append(errs, errors.Wrap(err, \"invalid scan_rate_per_sec value\"))\n\t}\n\treturn errs.Err()\n}", "func (cc *Config) Validate() error {\n\tif len(cc.BrokerList) == 0 {\n\t\treturn ErrConfigNoBrokers\n\t}\n\n\tif cc.ReadTimeout < time.Millisecond {\n\t\treturn ErrConfigInvalidReadTimeout\n\t}\n\n\tif cc.WriteTimeout < time.Millisecond {\n\t\treturn ErrConfigInvalidWriteTimeout\n\t}\n\n\tif cc.ConnectTimeout < time.Millisecond {\n\t\treturn ErrConfigInvalidConnectTimeout\n\t}\n\n\tif cc.KeepAliveTimeout < time.Millisecond {\n\t\treturn ErrConfigInvalidKeepAliveTimeout\n\t}\n\n\tif cc.FetchSize < 1 {\n\t\treturn ErrConfigInvalidFetchSize\n\t}\n\n\tif cc.MetadataRetries < 0 {\n\t\treturn ErrConfigInvalidMetadataRetries\n\t}\n\n\tif cc.MetadataBackoff < time.Millisecond {\n\t\treturn ErrConfigInvalidMetadataBackoff\n\t}\n\n\tif cc.MetadataTTL < time.Millisecond {\n\t\treturn ErrConfigInvalidMetadataTTL\n\t}\n\n\tif cc.CommitOffsetRetries < 0 {\n\t\treturn ErrConfigInvalidCommitOffsetRetries\n\t}\n\n\tif cc.CommitOffsetBackoff < time.Millisecond {\n\t\treturn ErrConfigInvalidCommitOffsetBackoff\n\t}\n\n\tif cc.ConsumerMetadataRetries < 0 {\n\t\treturn ErrConfigInvalidConsumerMetadataRetries\n\t}\n\n\tif cc.ConsumerMetadataBackoff < time.Millisecond {\n\t\treturn ErrConfigInvalidConsumerMetadataBackoff\n\t}\n\n\tif cc.ClientID == \"\" {\n\t\treturn ErrConfigEmptyClientID\n\t}\n\n\treturn nil\n}", "func (c RouterConfig) Validate() error {\n\treturn nil\n}", "func (c DbConfig) Validate() error {\n\t// Holds empty config fields\n\tempty := []string{}\n\n\t// Host\n\tif len(c.Host) == 0 {\n\t\tempty = append(empty, \"Host\")\n\t}\n\n\t// User\n\tif len(c.User) == 0 {\n\t\tempty = append(empty, \"User\")\n\t}\n\n\t// Password\n\tif len(c.Password) == 0 {\n\t\tempty = append(empty, \"Password\")\n\t}\n\n\t// Db\n\tif len(c.Db) == 0 {\n\t\tempty = append(empty, \"Db\")\n\t}\n\n\t// If any empty\n\tif len(empty) > 0 {\n\t\treturn fmt.Errorf(\"the db config fields: %s, were empty\",\n\t\t\tstrings.Join(empty, \",\"))\n\t}\n\n\t// All good\n\treturn nil\n}", "func (c *Config) Validate() error {\n\treturn c.validateTemplates()\n}", "func (cfg *Config) Validate() error {\n\tif cfg.DisableValidation {\n\t\treturn nil\n\t}\n\n\tif _, err := os.Stat(cfg.KernelImagePath); err != nil {\n\t\treturn fmt.Errorf(\"failed to stat kernel image path, %q: %v\", cfg.KernelImagePath, err)\n\t}\n\n\tif cfg.InitrdPath != \"\" {\n\t\tif _, err := os.Stat(cfg.InitrdPath); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to stat initrd image path, %q: %v\", cfg.InitrdPath, err)\n\t\t}\n\t}\n\n\tfor _, drive := range cfg.Drives {\n\t\tif BoolValue(drive.IsRootDevice) {\n\t\t\trootPath := StringValue(drive.PathOnHost)\n\t\t\tif _, err := os.Stat(rootPath); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to stat host drive path, %q: %v\", rootPath, err)\n\t\t\t}\n\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Check the non-existence of some files:\n\tif _, err := os.Stat(cfg.SocketPath); err == nil {\n\t\treturn fmt.Errorf(\"socket %s already exists\", cfg.SocketPath)\n\t}\n\n\tif cfg.MachineCfg.VcpuCount == nil ||\n\t\tInt64Value(cfg.MachineCfg.VcpuCount) < 1 {\n\t\treturn fmt.Errorf(\"machine needs a nonzero VcpuCount\")\n\t}\n\tif cfg.MachineCfg.MemSizeMib == nil ||\n\t\tInt64Value(cfg.MachineCfg.MemSizeMib) < 1 {\n\t\treturn fmt.Errorf(\"machine needs a nonzero amount of memory\")\n\t}\n\tif cfg.MachineCfg.HtEnabled == nil {\n\t\treturn fmt.Errorf(\"machine needs a setting for ht_enabled\")\n\t}\n\treturn nil\n}", "func (c *Config) validate() error {\n\tif err := validation.ValidateStruct(c); err != nil {\n\t\treturn err\n\t}\n\n\tif c.EnableBuiltInFiltering != nil && !*c.EnableBuiltInFiltering {\n\t\treturn errors.New(\"enableBuiltInFiltering must be true or unset, false is no longer supported\")\n\t}\n\n\tif _, err := url.Parse(c.IngestURL); err != nil {\n\t\treturn fmt.Errorf(\"%s is not a valid ingest URL: %v\", c.IngestURL, err)\n\t}\n\n\tif _, err := url.Parse(c.APIURL); err != nil {\n\t\treturn fmt.Errorf(\"%s is not a valid API URL: %v\", c.APIURL, err)\n\t}\n\n\tif _, err := url.Parse(c.EventEndpointURL); err != nil {\n\t\treturn fmt.Errorf(\"%s is not a valid event endpoint URL: %v\", c.EventEndpointURL, err)\n\t}\n\n\tif c.TraceEndpointURL != \"\" {\n\t\tif _, err := url.Parse(c.TraceEndpointURL); err != nil {\n\t\t\treturn fmt.Errorf(\"%s is not a valid trace endpoint URL: %v\", c.TraceEndpointURL, err)\n\t\t}\n\t}\n\n\tif err := c.Collectd.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\tfor i := range c.Monitors {\n\t\tif err := c.Monitors[i].Validate(); err != nil {\n\t\t\treturn fmt.Errorf(\"monitor config for type '%s' is invalid: %v\", c.Monitors[i].Type, err)\n\t\t}\n\t}\n\n\treturn c.Writer.Validate()\n}", "func (c *Config) Validate() error {\n\tif c.RNG.Seed == 0 {\n\t\tc.RNG.Seed = time.Now().Unix()\n\t}\n\n\tif c.Time.TicksPerDay < 1 {\n\t\treturn fmt.Errorf(\"time.ticksPerDay must be greater than 1\")\n\t}\n\n\tif c.Time.TotalDays < 1 {\n\t\treturn fmt.Errorf(\"time.totalDays must be greater than 1\")\n\t}\n\n\tif c.Arena.Width < 1 {\n\t\treturn fmt.Errorf(\"arena.width must be greater than 1\")\n\t}\n\n\tif c.Arena.Height < 1 {\n\t\treturn fmt.Errorf(\"arena.height must be greater than 1\")\n\t}\n\n\tif c.Arena.MajorX > c.Arena.Height {\n\t\treturn fmt.Errorf(\"arena.majorX cannot be more than arena.height (%d)\", c.Arena.Height)\n\t}\n\n\tif c.Arena.MajorY > c.Arena.Width {\n\t\treturn fmt.Errorf(\"arena.majorY cannot be more than arena.width (%d)\", c.Arena.Width)\n\t}\n\n\tmoralSum := c.Moral.MajorMajorLow + c.Moral.MajorMinorLow + c.Moral.MinorMinorLow\n\tif moralSum != 100 && (c.Arena.MajorX > 0 || c.Arena.MajorY > 0) {\n\t\treturn fmt.Errorf(\"moral context percentages must add up to 100%% (currently: %d%%)\", moralSum)\n\t}\n\n\tworkspaceSum := c.Workspace.MajorMajorLow + c.Workspace.MajorMajorHigh +\n\t\tc.Workspace.MajorMinorLow + c.Workspace.MajorMinorHigh +\n\t\tc.Workspace.MinorMinorLow + c.Workspace.MinorMinorHigh\n\tif workspaceSum != 100 && (c.Arena.MajorX > 0 || c.Arena.MajorY > 0) {\n\t\treturn fmt.Errorf(\"workspace distribution percentages must add up to 100%% (currently: %d%%)\", workspaceSum)\n\t}\n\n\tif c.Arena.MajorX == 0 && c.Arena.MajorY == 0 {\n\t\tif c.Moral.MajorMajorLow > 0 {\n\t\t\treturn fmt.Errorf(\"moral.majorMajorLow cannot be greater than 0 with no major streets\")\n\t\t}\n\t\tif c.Moral.MajorMinorLow > 0 {\n\t\t\treturn fmt.Errorf(\"moral.majorMinorLow cannot be greater than 0 with no major streets\")\n\t\t}\n\n\t\tif c.Workspace.MajorMajorLow > 0 {\n\t\t\treturn fmt.Errorf(\"workspace.majorMajorLow cannot be greater than 0 with no major streets\")\n\t\t}\n\n\t\tif c.Workspace.MajorMajorHigh > 0 {\n\t\t\treturn fmt.Errorf(\"workspace.majorMajorHigh cannot be greater than 0 with no major streets\")\n\t\t}\n\n\t\tif c.Workspace.MajorMinorLow > 0 {\n\t\t\treturn fmt.Errorf(\"workspace.majorMinorLow cannot be greater than 0 with no major streets\")\n\t\t}\n\n\t\tif c.Workspace.MajorMinorHigh > 0 {\n\t\t\treturn fmt.Errorf(\"workspace.majorMinorHigh cannot be greater than 0 with no major streets\")\n\t\t}\n\t}\n\n\tif c.Economy.Unemployment > 100 {\n\t\treturn fmt.Errorf(\"economy.unemployment cannot be more than 100%%\")\n\t}\n\n\tif c.Economy.HiringRate > 100 {\n\t\treturn fmt.Errorf(\"economy.hiringRate cannot be more than 100%%\")\n\t}\n\n\tif c.Economy.FiringRate > 100 {\n\t\treturn fmt.Errorf(\"economy.firingRate cannot be more than 100%%\")\n\t}\n\n\treturn nil\n}", "func validateConfig(config *ProviderConfig) error {\n\t// Validate the inputs\n\tif config == nil {\n\t\treturn fmt.Errorf(\"missing config\")\n\t}\n\tif config.Service == nil {\n\t\treturn fmt.Errorf(\"missing service\")\n\t}\n\tif config.Service.Service == \"\" {\n\t\treturn fmt.Errorf(\"missing service name\")\n\t}\n\tif config.Service.ServiceVersion == \"\" {\n\t\treturn fmt.Errorf(\"missing service version\")\n\t}\n\tif config.Service.ResourceType == \"\" {\n\t\treturn fmt.Errorf(\"missing service resource type\")\n\t}\n\tif config.Handlers == nil && len(config.Service.Capabilities) != 0 {\n\t\treturn fmt.Errorf(\"missing handlers\")\n\t}\n\tfor c := range config.Service.Capabilities {\n\t\tif _, ok := config.Handlers[c]; !ok {\n\t\t\treturn fmt.Errorf(\"missing handler for '%s' capability\", c)\n\t\t}\n\t}\n\tif config.ResourceGroup == \"\" {\n\t\treturn fmt.Errorf(\"missing resource group\")\n\t}\n\tif config.Token == \"\" {\n\t\tconfig.Token = os.Getenv(\"ATLAS_TOKEN\")\n\t}\n\tif config.Token == \"\" {\n\t\treturn fmt.Errorf(\"missing token\")\n\t}\n\n\t// Default the endpoint\n\tif config.Endpoint == \"\" {\n\t\tconfig.Endpoint = DefaultEndpoint\n\t\tif end := os.Getenv(\"SCADA_ENDPOINT\"); end != \"\" {\n\t\t\tconfig.Endpoint = end\n\t\t}\n\t}\n\treturn nil\n}", "func (c *Config) Validate() error {\n\tswitch {\n\tcase c.SkipValidation:\n\t\treturn nil\n\tcase c.Address == \"\":\n\t\treturn errors.New(\"address cannot be empty\")\n\tcase len(c.DNSNames) == 0:\n\t\treturn errors.New(\"dnsNames cannot be empty\")\n\tcase c.AuthorityConfig == nil:\n\t\treturn errors.New(\"authority cannot be nil\")\n\t}\n\n\t// Options holds the RA/CAS configuration.\n\tra := c.AuthorityConfig.Options\n\t// The default RA/CAS requires root, crt and key.\n\tif ra.Is(cas.SoftCAS) {\n\t\tswitch {\n\t\tcase c.Root.HasEmpties():\n\t\t\treturn errors.New(\"root cannot be empty\")\n\t\tcase c.IntermediateCert == \"\":\n\t\t\treturn errors.New(\"crt cannot be empty\")\n\t\tcase c.IntermediateKey == \"\":\n\t\t\treturn errors.New(\"key cannot be empty\")\n\t\t}\n\t}\n\n\t// Validate address (a port is required)\n\tif _, _, err := net.SplitHostPort(c.Address); err != nil {\n\t\treturn errors.Errorf(\"invalid address %s\", c.Address)\n\t}\n\n\tif c.TLS == nil {\n\t\tc.TLS = &DefaultTLSOptions\n\t} else {\n\t\tif len(c.TLS.CipherSuites) == 0 {\n\t\t\tc.TLS.CipherSuites = DefaultTLSOptions.CipherSuites\n\t\t}\n\t\tif c.TLS.MaxVersion == 0 {\n\t\t\tc.TLS.MaxVersion = DefaultTLSOptions.MaxVersion\n\t\t}\n\t\tif c.TLS.MinVersion == 0 {\n\t\t\tc.TLS.MinVersion = DefaultTLSOptions.MinVersion\n\t\t}\n\t\tif c.TLS.MinVersion > c.TLS.MaxVersion {\n\t\t\treturn errors.New(\"tls minVersion cannot exceed tls maxVersion\")\n\t\t}\n\t\tc.TLS.Renegotiation = c.TLS.Renegotiation || DefaultTLSOptions.Renegotiation\n\t}\n\n\t// Validate KMS options, nil is ok.\n\tif err := c.KMS.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Validate RA/CAS options, nil is ok.\n\tif err := ra.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Validate ssh: nil is ok\n\tif err := c.SSH.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Validate templates: nil is ok\n\tif err := c.Templates.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Validate crl config: nil is ok\n\tif err := c.CRL.Validate(); err != nil {\n\t\treturn err\n\t}\n\n\treturn c.AuthorityConfig.Validate(c.GetAudiences())\n}", "func (c *config) Validate() []error {\n\tvar errs []error\n\tif value, err := validateProvider(c.Provider); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.Provider = value\n\t}\n\tif value, err := validateAccountName(c.AccountName); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.AccountName = value\n\t}\n\tif value, err := validateAccountSecret(c.AccountSecret); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.AccountSecret = value\n\t}\n\tif value, err := validateDNSContent(c.DNSContent); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.DNSContent = value\n\t}\n\tif value, err := validateDockerLabel(c.DockerLabel); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.DockerLabel = value\n\t}\n\tif value, err := validateStore(c.Store); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.Store = value\n\t}\n\tif value, err := validateDataDirectory(c.DataDirectory); err != nil {\n\t\terrs = append(errs, err)\n\t} else {\n\t\tc.DataDirectory = value\n\t}\n\treturn errs\n}", "func (cfg fromCFN) validate() error {\n\tif cfg.isEmpty() {\n\t\treturn nil\n\t}\n\tif len(aws.StringValue(cfg.Name)) == 0 {\n\t\treturn errors.New(\"name cannot be an empty string\")\n\t}\n\treturn nil\n}", "func (cfg *Config) Validate() error {\n\tif cfg.MaxCompactionParallelism < 1 {\n\t\treturn errors.New(\"max compaction parallelism must be >= 1\")\n\t}\n\tif cfg.RetentionEnabled && cfg.ApplyRetentionInterval != 0 && cfg.ApplyRetentionInterval%cfg.CompactionInterval != 0 {\n\t\treturn errors.New(\"interval for applying retention should either be set to a 0 or a multiple of compaction interval\")\n\t}\n\n\tif err := shipper_storage.ValidateSharedStoreKeyPrefix(cfg.SharedStoreKeyPrefix); err != nil {\n\t\treturn err\n\t}\n\n\tif cfg.DeletionMode != \"\" {\n\t\tlevel.Warn(util_log.Logger).Log(\"msg\", \"boltdb.shipper.compactor.deletion-mode has been deprecated and will be ignored. This has been moved to the deletion_mode per tenant configuration.\")\n\t}\n\n\treturn nil\n}", "func (c *RaftConfig) validate() error {\n\tif c.ID == 0 {\n\t\treturn errors.New(\"ID is required\")\n\t}\n\tif len(c.Peers) == 0 {\n\t\treturn errors.New(\"Peers is required\")\n\t}\n\t/*if c.Storage == nil {\n\t\treturn errors.New(\"Storage is required\")\n\t}\n\tif c.StateMachine == nil {\n\t\treturn errors.New(\"StateMachine is required\")\n\t}*/\n\n\treturn nil\n}", "func (config *IDConfig) validate() error {\n\tswitch config.idType {\n\tcase \"halo-id\", \"m200m\":\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'IDType' variable is set to '%s', which I \"+\n\t\t\t\"don't recognize.\", config.idType)\n\t}\n\n\tswitch config.exclusionStrategy {\n\tcase \"none\", \"subhalo\", \"neighbor\":\n\tcase \"overlap\":\n\t\tif config.exclusionRadiusMult <= 0 {\n\t\t\treturn fmt.Errorf(\"The 'ExclusionRadiusMult' varaible is set to \"+\n\t\t\t\t\"%g, but it needs to be positive.\", config.exclusionRadiusMult)\n\t\t}\n\tdefault:\n\t\treturn fmt.Errorf(\"The 'ExclusionStrategy' variable is set to '%s', \"+\n\t\t\t\"which I don't recognize.\", config.exclusionStrategy)\n\t}\n\n\tswitch {\n\tcase config.snap == -1:\n\t\treturn fmt.Errorf(\"'Snap' variable not set.\")\n\tcase config.snap < 0:\n\t\treturn fmt.Errorf(\"'Snap' variable set to %d.\", config.snap)\n\t}\n\n\tif config.mult <= 0 {\n\t\treturn fmt.Errorf(\"'Mult' variable set to %d\", config.mult)\n\t}\n\n\tswitch {\n\tcase config.m200mMax < 0:\n\t\treturn fmt.Errorf(\"M200mStart set to %g\", config.m200mMax)\n\tcase config.m200mMax > config.m200mMin:\n\t\tfmt.Errorf(\"M200mEnd smaller than M200mStart\")\n\t}\n\n\treturn nil\n}", "func Validate(config *Config) []error {\n\t// TODO: Write validation logic later\n\treturn []error{}\n}", "func (config DiskConfig) validate() error {\n\tswitch config {\n\tcase Auto, Manual:\n\t\treturn nil\n\tdefault:\n\t\treturn ErrInvalidDiskConfig\n\t}\n}", "func (c *EtcdConfig) Validate() error {\n\t_, err := govalidator.ValidateStruct(c)\n\treturn err\n}", "func validateConfig(c *Config) error {\n\t// SOM must have 2 dimensions\n\t// TODO: figure out 3D maps\n\tif dimLen := len(c.Dims); dimLen != 2 {\n\t\treturn fmt.Errorf(\"Incorrect number of dimensions supplied: %d\\n\", dimLen)\n\t}\n\t// check if the supplied dimensions are negative integers\n\tfor _, dim := range c.Dims {\n\t\tif dim < 0 {\n\t\t\treturn fmt.Errorf(\"Incorrect SOM dimensions supplied: %v\\n\", c.Dims)\n\t\t}\n\t}\n\t// check if the supplied grid type is supported\n\tif _, ok := CoordsInit[c.Grid]; !ok {\n\t\treturn fmt.Errorf(\"Unsupported SOM grid type: %s\\n\", c.Grid)\n\t}\n\t// check if the supplied unit shape type is supported\n\tif _, ok := UShape[c.UShape]; !ok {\n\t\treturn fmt.Errorf(\"Unsupported SOM unit shape: %s\\n\", c.UShape)\n\t}\n\t// initial SOM unit radius must be greater than zero\n\tif c.Radius < 0 {\n\t\treturn fmt.Errorf(\"Invalid SOM unit radius: %d\\n\", c.Radius)\n\t}\n\t// check Radius decay strategy\n\tif _, ok := Cool[c.RDecay]; !ok {\n\t\treturn fmt.Errorf(\"Unsupported Radius decay strategy: %s\\n\", c.RDecay)\n\t}\n\t// hcheck the supplied neighbourhood function\n\tif _, ok := Neighb[c.NeighbFn]; !ok {\n\t\treturn fmt.Errorf(\"Unsupported Neighbourhood function: %s\\n\", c.NeighbFn)\n\t}\n\t// initial SOM learning rate must be greater than zero\n\tif c.LRate < 0 {\n\t\treturn fmt.Errorf(\"Invalid SOM learning rate: %d\\n\", c.LRate)\n\t}\n\t// check Learning rate decay strategy\n\tif _, ok := Cool[c.LDecay]; !ok {\n\t\treturn fmt.Errorf(\"Unsupported Learning rate decay strategy: %s\\n\", c.LDecay)\n\t}\n\treturn nil\n}", "func (c *Config) valid() error {\n\tif c.Score == nil {\n\t\treturn errors.New(\"Expected Score to not be nil\")\n\t}\n\tif c.Sampler == nil {\n\t\treturn errors.New(\"Expected Sampler to not be nil\")\n\t}\n\treturn nil\n}", "func (scc *ServiceCustomConfig) Validate() error {\n\n\tif len(scc.MyserviceInfo.Host) == 0 {\n\t\treturn errors.New(\"host setting for service not configured\")\n\t}\n\tif scc.MyserviceInfo.Port == 0 {\n\t\treturn errors.New(\"port setting for service not configured\")\n\t}\n\n\tif len(scc.CommandClientInfo.Host) == 0 {\n\t\treturn errors.New(\"host setting for Core Command client not configured\")\n\t}\n\tif scc.CommandClientInfo.Port == 0 {\n\t\treturn errors.New(\"port setting for Core Command client not configured\")\n\t}\n\n\tif len(scc.NotificationClientInfo.Host) == 0 {\n\t\treturn errors.New(\"host setting for Core Command client not configured\")\n\t}\n\tif scc.NotificationClientInfo.Port == 0 {\n\t\treturn errors.New(\"port setting for Core Command client not configured\")\n\t}\n\n\tif len(scc.SchedulerClientInfo.Host) == 0 {\n\t\treturn errors.New(\"host setting for Scheduler client not configured\")\n\t}\n\tif scc.SchedulerClientInfo.Port == 0 {\n\t\treturn errors.New(\"port setting for Scheduler client not configured\")\n\t}\n\n\tif len(scc.RuleEngineClientInfo.Host) == 0 {\n\t\treturn errors.New(\"host setting for Rule Engine client not configured\")\n\t}\n\tif scc.RuleEngineClientInfo.Port == 0 {\n\t\treturn errors.New(\"port setting for Rule Engine client not configured\")\n\t}\n\n\treturn nil\n}", "func (c *Config) validate() error {\n\tdataDir, err := filepath.Abs(c.DataDir)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tlogFile, err := filepath.Abs(c.Log.File.Filename)\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\trel, err := filepath.Rel(dataDir, filepath.Dir(logFile))\n\tif err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\tif !strings.HasPrefix(rel, \"..\") {\n\t\treturn errors.New(\"log directory shouldn't be the subdirectory of data directory\")\n\t}\n\n\treturn nil\n}", "func (c *Config) IsValid() error {\n\tif len(c.NetworkServices) == 0 {\n\t\treturn errors.New(\"no network services are specified\")\n\t}\n\tif c.Name == \"\" {\n\t\treturn errors.New(\"no cleint name specified\")\n\t}\n\tif c.ConnectTo.String() == \"\" {\n\t\treturn errors.New(\"no NSMGr ConnectTO URL are sepecified\")\n\t}\n\treturn nil\n}", "func validate(cfg Settings) error {\n\tif len(cfg.Selectors) == 0 {\n\t\treturn errors.New(\"no selectors configured\")\n\t}\n\tif cfg.ServiceTLS {\n\t\treturn errors.New(\"TLS mode not yet implemented\")\n\t}\n\n\treturn nil\n}" ]
[ "0.75037235", "0.7351897", "0.73500097", "0.7334031", "0.7334031", "0.7334031", "0.733164", "0.7265028", "0.72637486", "0.72489303", "0.723954", "0.7234314", "0.7229491", "0.7218521", "0.7188024", "0.71765065", "0.71698743", "0.71461374", "0.7125144", "0.7106589", "0.7103617", "0.71015257", "0.7093116", "0.7064059", "0.7057185", "0.7048142", "0.70443124", "0.70443124", "0.7043419", "0.7035423", "0.7030668", "0.70119715", "0.70087874", "0.70084023", "0.70008904", "0.6998513", "0.698139", "0.6977818", "0.6976533", "0.6968631", "0.69673485", "0.69654685", "0.69574577", "0.69549465", "0.69340533", "0.69223183", "0.69117755", "0.6905104", "0.68907326", "0.6880238", "0.6863645", "0.68480015", "0.68450654", "0.6842392", "0.6837977", "0.6835095", "0.68209594", "0.6820473", "0.68067956", "0.68022907", "0.6798477", "0.6783382", "0.6777344", "0.6773766", "0.67635447", "0.674463", "0.67389905", "0.6738411", "0.67313564", "0.6721735", "0.6716248", "0.67149496", "0.6713733", "0.67130256", "0.6692888", "0.66901475", "0.6670795", "0.6666892", "0.6661721", "0.66595185", "0.66519165", "0.6649143", "0.6642193", "0.6632255", "0.6632065", "0.66205674", "0.6616239", "0.6613745", "0.6611448", "0.65995866", "0.6598382", "0.65875155", "0.65755093", "0.65687454", "0.6566927", "0.656296", "0.6556914", "0.65486467", "0.6542055", "0.6535538" ]
0.73756576
1
PrintMessages will print messages to the console for the user
func PrintMessages(products Products, discounts Discounts) { printWelcomeMessage() printCurrentProducts(products) printDiscountProducts(discounts, products) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (gossiper *Gossiper) printMessages() {\n\tfor str := range gossiper.ToPrint {\n\t\tfmt.Println(str)\n\t}\n}", "func PrintMsgs(messages ...string) {\n\tif !verbose {\n\t\treturn\n\t}\n\n\tsep := \"\"\n\tfor _, msg := range messages {\n\t\tfmt.Fprintln(vDest, sep, msg)\n\t\tsep = \"\\t\"\n\t}\n}", "func PrintMessage(args ...interface{}) {\n\tfmt.Println()\n\tfmt.Println(\"---------------------------------------------------------------\")\n\tfmt.Println(args...)\n\tfmt.Println(\"---------------------------------------------------------------\")\n\tfmt.Println()\n}", "func (mp *messagePrinter) printMessage(message string) {\n\tprintln(message)\n}", "func (e *Election) PrintMessages() string {\n\tstr := fmt.Sprintf(\"-- In -- (%p)\\n\", e.MsgListIn)\n\tfor i, m := range e.MsgListIn {\n\t\tif m.Msg != nil {\n\t\t\tstr += fmt.Sprintf(\"%d Depth:%d %s\\n\", i, m.Depth, e.Display.FormatMessage(m.Msg))\n\t\t} else if m.VoteMsg != nil {\n\t\t\tstr += fmt.Sprintf(\"%d Depth:%d %s\\n\", i, m.Depth, e.Display.FormatMessage(m.VoteMsg))\n\t\t}\n\t}\n\tstr += fmt.Sprintf(\"-- Out -- (%p)\\n\", e.MsgListOut)\n\tfor i, m := range e.MsgListOut {\n\t\tif m.Msg != nil {\n\t\t\tstr += fmt.Sprintf(\"%d Depth:%d %s\\n\", i, m.Depth, e.Display.FormatMessage(m.Msg))\n\t\t} else if m.VoteMsg != nil {\n\t\t\tstr += fmt.Sprintf(\"%d Depth:%d %s\\n\", i, m.Depth, e.Display.FormatMessage(m.VoteMsg))\n\t\t}\n\t}\n\treturn str\n}", "func PrintMessage(message string) {\n\tfmt.Println(\"\")\n\tfmt.Println(message)\n\tfmt.Println(\"\")\n}", "func (ml *MessageLog) PrintMessages(viewAreaX, viewAreaY, windowSizeX, windowSizeY, displayNum int) []string {\n\t// Print the latest five messages from the messageLog. These will be printed in reverse order (newest at the top),\n\t// to make it appear they are scrolling down the screen\n\tclearMessages(viewAreaX, viewAreaY, windowSizeX, windowSizeY, 1)\n\n\ttoShow := 0\n\n\tif len(ml.messages) <= displayNum {\n\t\t// Just loop through the messageLog, printing them in reverse order\n\t\ttoShow = len(ml.messages)\n\t} else {\n\t\t// If we have more than {displayNum} messages stored, just show the {displayNum} most recent\n\t\ttoShow = displayNum\n\t}\n\n\tprintedMessages := []string{}\n\n\tfor i := toShow; i > 0; i-- {\n\t\tPrintText(viewAreaX, (viewAreaY-1)+i, ml.messages[i-1], \"white\", \"\", 1, 0)\n\t\tprintedMessages = append(printedMessages, ml.messages[i-1])\n\t}\n\n\treturn printedMessages\n}", "func (sh *stmHelper) printMessage(msg string) (err error) {\n\terr = sh.ClearDisplay()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sh.PrintText(0, 0, stm.Foreground, msg)\n}", "func Print(messages ...string) {\n\tif !verbose {\n\t\treturn\n\t}\n\n\tfor _, msg := range messages {\n\t\tfmt.Fprint(vDest, msg)\n\t}\n}", "func printMsg(msg string) {\n\tfmt.Println(msg)\n}", "func printMessage(message string) {\n\tfor i := 0; i < 10; i++ {\n\t\tfmt.Println(message, \":\", i)\n\t}\n}", "func PrintMessage(texto string) {\n\tfmt.Println(texto)\n}", "func messagePrinter(ch chan chat.Message) {\n\tfor {\n\t\tm, ok := <-ch\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tfmt.Println(\"<\",m.Source,\"> \",m.Text)\n\t}\n}", "func printUserMessage() {\n\tgo func() {\n\t\tfor {\n\t\t\tm := <-MessageChannel\n\t\t\tswitch m.Level {\n\t\t\tcase messages.Info:\n\t\t\t\tfmt.Println(color.CyanString(\"\\n[i] %s\", m.Message))\n\t\t\tcase messages.Note:\n\t\t\t\tfmt.Println(color.YellowString(\"\\n[-] %s\", m.Message))\n\t\t\tcase messages.Warn:\n\t\t\t\tfmt.Println(color.RedString(\"\\n[!] %s\", m.Message))\n\t\t\tcase messages.Success:\n\t\t\t\tfmt.Println(color.GreenString(\"\\n[+] %s\", m.Message))\n\t\t\tcase messages.Plain:\n\t\t\t\tfmt.Println(\"\\n\" + m.Message)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(color.RedString(\"\\n[_-_] Invalid message level: %d\\r\\n%s\", m.Level, m.Message))\n\t\t\t}\n\t\t}\n\t}()\n}", "func (s IOStreams) Print(msg string) {\n\tif s.SpinnerActive() {\n\t\ts.StopSpinner()\n\t\tdefer s.StartSpinner()\n\t}\n\ts.Out.Write([]byte(msg))\n}", "func print(message string, err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Println(message)\n}", "func Println(messages ...string) {\n\tif !verbose {\n\t\treturn\n\t}\n\n\tPrint(messages...)\n\tPrint(\"\\n\")\n}", "func (state *State) Print(msg ...interface{}) {\n\tfmt.Fprint(state.Output, msg...)\n}", "func printOnScreen(message string, content []string) {\n\t// Message before the table\n\tfmt.Printf(\"\\n%s\\n\\n\", message)\n\n\t// Print the table format\n\tresult := columnize.SimpleFormat(content)\n\n\t// Print the results\n\tfmt.Println(result + \"\\n\")\n}", "func printMessage(ID int, message Message) {\n\tfmt.Println(\"\\n ---------------------------- \\n ---Message Confirmed Sent--- \\n ---------------------------- \\n\")\n\tfmt.Println(\"Message Sent to process:\" + strconv.Itoa(ID))\n\tfmt.Println(\"Message Content: \" + message.Content)\n\tfmt.Println(\"Confirmed sent at: \" + message.Time)\n\tfmt.Println(\"\\n --------------------------- \\n\")\n}", "func PrintMessage(infotype, message string) {\n\n\tswitch infotype {\n\tcase \"debug\":\n\t\tcolor.Set(color.FgHiYellow)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tcase \"success\":\n\t\tcolor.Set(color.FgHiGreen)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tcase \"error\":\n\t\tcolor.Set(color.FgHiRed)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tdefault:\n\t\tcolor.Set(color.FgHiWhite)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\t}\n}", "func printMessageError() {\n\tfmt.Println()\n\tfmt.Println(\"Please enter a message!\")\n\tfmt.Println()\n}", "func (er *ExecutionResult) Print() {\n\tfor _, m := range er.Message {\n\t\tfmt.Println(m)\n\t}\n}", "func Print(ms diag.Messages, format string, colorize bool) (string, error) {\n\tswitch format {\n\tcase LogFormat:\n\t\treturn printLog(ms, colorize), nil\n\tcase JSONFormat:\n\t\treturn printJSON(ms)\n\tcase YAMLFormat:\n\t\treturn printYAML(ms)\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"invalid format, expected one of %v but got %q\", MsgOutputFormatKeys, format)\n\t}\n}", "func (chp *Printer) Print(msg string) {\n\tchp.StringChannel <- msg\n}", "func Println(msg ...interface{}) {\n\trunAdapters(MessageLog, LineOut, msg...)\n}", "func Printf(msg ...interface{}) {\n\trunAdapters(MessageLog, FormattedOut, msg...)\n}", "func PrintToMessageArea(message string, viewAreaX, viewAreaY, windowSizeX, windowSizeY, layer int) {\n\tclearMessages(viewAreaX, viewAreaY, windowSizeX, windowSizeY, layer)\n\tPrintText(1, viewAreaY, message, \"white\", \"\", 1, 0)\n}", "func PrintCommands() {\n logger.Log(fmt.Sprintln(\"** Daemonized Commands **\"))\n for cmd, desc := range DaemonizedCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Information Commands **\"))\n for cmd, desc := range InfoCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n\n logger.Log(fmt.Sprintln(\"** Interactive Commands **\"))\n for cmd, desc := range InteractiveCommands() {\n logger.Log(fmt.Sprintf(\"%15s: %s\\n\", cmd, desc.description))\n }\n}", "func Print(message string) {\n\tfmt.Printf(\n\t\t\"%s | %s\\n\", now(), message,\n\t)\n}", "func printMsg(format string, a ...interface{}) {\n\tif _, err := fmt.Fprintf(os.Stderr, format, a...); err != nil {\n\t}\n}", "func displayMessage(s string) {\n\tfmt.Println(\"inside displayMessage function\")\n\tfmt.Println(\"Message is:\",s)\n\tfmt.Printf(\"%s\\n\",s) // c style print function\n}", "func consolePrint(tag string, c *color.Color, a ...interface{}) {\n\tprivateMutex.Lock()\n\tdefer privateMutex.Unlock()\n\n\tswitch tag {\n\tcase \"Debug\":\n\t\t// if no arguments are given do not invoke debug printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\toutput := color.Output\n\t\tcolor.Output = stderrColoredOutput\n\t\tif isatty.IsTerminal(os.Stderr.Fd()) {\n\t\t\tc.Print(ProgramName() + \": <DEBUG> \")\n\t\t\tc.Print(a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": <DEBUG> \")\n\t\t\tfmt.Fprint(color.Output, a...)\n\t\t}\n\t\tcolor.Output = output\n\tcase \"Fatal\":\n\t\tfallthrough\n\tcase \"Error\":\n\t\t// if no arguments are given do not invoke fatal and error printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\toutput := color.Output\n\t\tcolor.Output = stderrColoredOutput\n\t\tif isatty.IsTerminal(os.Stderr.Fd()) {\n\t\t\tc.Print(ProgramName() + \": <ERROR> \")\n\t\t\tc.Print(a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": <ERROR> \")\n\t\t\tfmt.Fprint(color.Output, a...)\n\t\t}\n\t\tcolor.Output = output\n\tcase \"Info\":\n\t\t// if no arguments are given do not invoke info printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\t\tc.Print(ProgramName() + \": \")\n\t\t\tc.Print(a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": \")\n\t\t\tfmt.Fprint(color.Output, a...)\n\t\t}\n\tdefault:\n\t\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\t\tc.Print(a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, a...)\n\t\t}\n\t}\n}", "func printMessage(message string) {\n\tdocument := js.Global().Get(\"document\")\n\tp := document.Call(\"createElement\", \"p\")\n\tp.Set(\"innerHTML\", message)\n\tdocument.Get(\"body\").Call(\"appendChild\", p)\n}", "func (this *MiniCon) Print(args ...interface{}) {\n\tline := fmt.Sprint(args...)\n\tthis.pending.addString(line)\n}", "func (rd *ratedisp) print(pfx string) {\n\telapsed := time.Since(rd.start).Seconds()\n\n\trd.b.Logf(\"%s: %s%d messages in %fs (%.0f msgs/s), %d bytes (%.3fMb/s)\",\n\t\trd.name, pfx, rd.cnt, elapsed, float64(rd.cnt)/elapsed,\n\t\trd.size, (float64(rd.size)/elapsed)/(1024*1024))\n}", "func (printer Plain) Print(message interface{}) {\n\tswitch x := message.(type) {\n\tcase []string:\n\t\tfor _, item := range x {\n\t\t\t_, _ = fmt.Fprintf(printer.writer, \"%+v\\n\", item)\n\t\t}\n\tdefault:\n\t\t_, _ = fmt.Fprintf(printer.writer, \"%+v\\n\", x)\n\t}\n}", "func (t *trs80) writeMessages() {\n\tfor i := 0; i < int(t.pb.Header.NumMessages); i++ {\n\t\tfmt.Fprintf(t.out, \"\\\"%s\\\"\\n\", t.pb.Messages[i])\n\t}\n}", "func (wa *WaitingArea) print() {\n\tvar sb strings.Builder\n\tfor _, row := range wa.seats {\n\t\tfor _, s := range row {\n\t\t\tsb.WriteString(string(s.status))\n\t\t}\n\t\tsb.WriteString(\"\\n\")\n\t}\n\tfmt.Println(sb.String())\n}", "func Console(in chan string,\n\ttitle string,\n\tlimit int) {\n\tvar s string\n\tvar i int = 0\n\tfmt.Printf(\"%v\\n\", title)\n\tfor i < limit {\n\t\ts = <-in\n\t\tfmt.Printf(\"%v\\n\", s)\n\t\ti = i + 1\n\t}\n\tfmt.Println(\"%v\\n\", \"Console Output Finished\")\n}", "func (m *TextMessage) PrintMessage(e Event) {\n\te.TargetRoom.OnNotify(e)\n\tfmt.Printf(\"Message from %s to Room %s: %s\\n\", e.Sender.Name, e.TargetRoom.ID, m.message)\n}", "func (logger *StdLogger) Print(sessionID string, message interface{}) {\n\tlog.Printf(\"%s %s\", sessionID, message)\n}", "func printMsg(format string, a ...interface{}) {\n\tif _, err := fmt.Fprintf(os.Stderr, format, a...); err != nil {}\n}", "func printScreen() {\n\tsimpleansi.ClearScreen() // Clear the screen before we print\n\n\t// Print the maze\n\tfor _, line := range maze {\n\t\tfor _, chr := range line {\n\t\t\tswitch chr {\n\t\t\tcase '#':\n\t\t\t\t//fmt.Print(simpleansi.WithBlueBackground(cfg.Wall)) // Print wall from struct\n\t\t\t\tfmt.Print(cfg.Wall) // Print wall from struct\n\t\t\tcase '.':\n\t\t\t\tfmt.Print(cfg.Dot)\n\t\t\tcase 'X':\n\t\t\t\tfmt.Print(cfg.Pill)\n\t\t\tdefault:\n\t\t\t\tfmt.Print(cfg.Space)\n\t\t\t}\n\t\t}\n\t\tfmt.Println()\n\t}\n\n\t// Draw player\n\tmoveCursor(player.row, player.col)\n\tfmt.Print(cfg.Player)\n\n\t// Draw ghosts\n\tghostStatusMx.RLock() // Lock Read lock\n\tfor _, g := range ghosts {\n\t\tmoveCursor(g.position.row, g.position.col)\n\t\tif g.status == GhostStatusNormal {\n\t\t\tfmt.Print(cfg.Ghost)\n\t\t} else if g.status == GhostStatusBlue {\n\t\t\tfmt.Print(cfg.GhostBlue)\n\t\t}\n\t}\n\tghostStatusMx.RUnlock() // Unlock Read lock\n\n\t// Move cursor outside of maze drawing area\n\tmoveCursor(len(maze)+1, 0)\n\n\tlivesRemaining := strconv.Itoa(lives) // Converts lives int to a string\n\tif cfg.UseEmoji { // If use_emoji flag set\n\t\tlivesRemaining = getLivesAsEmoji() // Convert to emoji\n\t}\n\n\tfmt.Println(\"Score: \", score, \"\\tLives: \", livesRemaining) // Print score and lives\n}", "func printClientMessage(msg message.Message) {\n\tfmt.Println(\"CLIENT MESSAGE \" + msg.Text)\n}", "func Print(args ...interface{}) {\n\tglobal.Print(args...)\n}", "func (printer JSON) Print(message interface{}) {\n\ts, _ := prettyjson.Marshal(message)\n\t_, _ = fmt.Fprintf(printer.writer, \"%v\\n\", string(s))\n}", "func (l *Clogger) Print(a ...interface{}) {\n\tdefer func() {\n\t\t// catch panic(\"write on closed channel\")\n\t\trecover()\n\t\treturn\n\t}()\n\tl.in <- fmt.Sprint(a...)\n\treturn\n}", "func testPrintMsg(t *testing.T, msg string, status int, out, err string,\n\toutbuf, errbuf *bytes.Buffer) {\n\tioCmp(t, \"printMsg\", printMsg(msg), status, out, err, outbuf, errbuf)\n}", "func (cp ChanPrinter) Print(v ...interface{}) {\n\tcp <- fmt.Sprint(v...)\n}", "func (logger *Logger) Print(args ...interface{}) {\n\tlogger.std.Log(args...)\n}", "func printer(c <-chan string) {\n\tfor {\n\t\t// print msg recived on channel\n\t\tfmt.Println(<-c)\n\t\ttime.Sleep(time.Second * 1)\n\t}\n}", "func PrintMessage(w http.ResponseWriter, ResponseArray interface{}, status int) {\n\tw.WriteHeader(status)\n\tjson.NewEncoder(w).Encode(ResponseArray)\n\treturn\n}", "func printMessage(message string, arr []string) {\n\tvar nameString = strings.Join(arr, \" \")\n\tfmt.Println(message, nameString)\n}", "func StartupMessages(msgs *AppMessages) {\n\tfmt.Println(msgs.startMsg)\n\tfmt.Println(msgs.escapeMsg)\n\tfmt.Println(msgs.spaceMsg)\n}", "func PrintMsgToCmd(a ...interface{}) {\n\tfmt.Println(a...)\n}", "func Print(vs ...interface{}) {\n\tstd.Print(vs...)\n}", "func (cli *CLI) PrintCommands() {\n\tfor _, command := range cli.commands {\n\t\tfmt.Printf(\" slackcli %s\", command.Name)\n\t\tfor _, param := range command.Params {\n\t\t\tfmt.Printf(\" [%s]\", param)\n\t\t}\n\t\tfmt.Println(\" \" + command.Help)\n\t}\n}", "func Print(v ...interface{}) {\n\tcheckInit()\n\ts := fmt.Sprint(v...)\n\tstd.Report(s)\n\tlog.Print(s)\n}", "func (t *Terminal) printAll() {\n\n\t//Update printing-related variables\n\tt.updateSize()\n\n\t//Clear buffer\n\tt.buffer = make([]termbox.Cell, t.width*t.height)\n\n\t//Print actual chars\n\tt.printTabs()\n\tt.printSeps()\n\n\t//Copy buffer to termbox\n\tt.updateBuffer()\n\n}", "func (cmd *CLI) Print(a ...interface{}) {\n\tfmt.Fprint(cmd.StdOut(), a...)\n}", "func Printer() {\n\tfmt.Println(\"Printing . . \")\n\n}", "func print(till int, message string) {\n\tfor i := 0; i < till; i++ {\n\t\tfmt.Println((i + 1), message)\n\t}\n}", "func Print(values ...any) {\n\tmux.Lock()\n\tdefer mux.Unlock()\n\n\tfor _, v := range values {\n\t\tWrite(os.Stdout, v)\n\t\tos.Stdout.Write(newLine)\n\t}\n}", "func main() {\n\tprint(\"test ok! (print)\\n\")\n\tfmt.Println(\"test ok! (fmt)\")\n}", "func printSimpleMessage(msg message.SimpleMessage) {\n\tfmt.Printf(\"SIMPLE MESSAGE origin %s from %s contents %s\\n\", msg.OriginalName, msg.RelayPeerAddr, msg.Contents)\n}", "func (M *ConnectionManager) handleMessages() {\n\tfor {\n\t\tselect {\n\t\tcase msg := <-M.Messages:\n\t\t\tterr.VerbPrint(outputTo, 5, verb, M.ID, \"RECIEVED:\", msg)\n\t\t}\n\t}\n}", "func (c *Client) PrintMessage(m *discordgo.Message) {\n\tc.PrintMessageComplex(m, c.Conf)\n}", "func Print(v ...interface{}) {\n\tstd.Output(std.callDepth, fmt.Sprint(v...), std.level)\n}", "func (cw *ConsoleWriter) WriteMsg(msg string, skip, level int) error {\r\n\tif cw.Level > level {\r\n\t\treturn nil\r\n\t}\r\n\tif runtime.GOOS == \"windows\" {\r\n\t\tcw.lg.Println(msg)\r\n\t} else {\r\n\t\tcw.lg.Println(colors[level](msg))\r\n\t}\r\n\treturn nil\r\n}", "func TestMessages(t *testing.T) {\n\tt.Parallel()\n\tdefer logging.HideLogs(t)()\n\n\tnewWait := func(exitStatus uint32) *wait.Wait {\n\t\treturn &wait.Wait{\n\t\t\tShell: &shell.Shell{\n\t\t\t\tCheckStmt: \"test\",\n\t\t\t\tStatus: &shell.CommandResults{\n\t\t\t\t\tExitStatus: exitStatus,\n\t\t\t\t},\n\t\t\t},\n\t\t\tRetrier: &wait.Retrier{},\n\t\t}\n\t}\n\n\tt.Run(\"passed message\", func(t *testing.T) {\n\t\twait := newWait(0)\n\t\tassert.Equal(t, 1, len(wait.Messages()))\n\n\t\tt.Run(\"failed messages\", func(t *testing.T) {\n\t\t\tassert.Regexp(t, regexp.MustCompile(\"^Passed after\"), wait.Messages()[0])\n\t\t})\n\t})\n\n\tt.Run(\"failed messages\", func(t *testing.T) {\n\t\twait := newWait(1)\n\t\tassert.Equal(t, 2, len(wait.Messages()))\n\n\t\tt.Run(\"failed after\", func(t *testing.T) {\n\t\t\tassert.Regexp(t, regexp.MustCompile(\"^Failed after\"), wait.Messages()[0])\n\t\t})\n\n\t\tt.Run(\"last attempt\", func(t *testing.T) {\n\t\t\tassert.Regexp(t, regexp.MustCompile(\"^Last attempt\"), wait.Messages()[1])\n\t\t})\n\t})\n}", "func PrintScreen(screen [][]bool) {\n\tpoint := 0\n\tfor x, superArr := range screen {\n\t\tfor y, b := range superArr {\n\t\t\tif b {\n\t\t\t\ttermbox.SetCell(x+point, y, ' ', termbox.ColorDefault, termbox.ColorWhite)\n\t\t\t\ttermbox.SetCell(x+point+1, y, ' ', termbox.ColorDefault, termbox.ColorWhite)\n\t\t\t}\n\t\t}\n\t\tpoint++\n\t}\n}", "func printInfo(message string, args ...interface{}) {\n\tif silent {\n\t\treturn\n\t}\n\tfmt.Printf(\"INFO Slack - \"+message+\"\\n\", args...)\n}", "func (b *BaseCmd) Println(message string) {\n\tfmt.Println(message)\n}", "func (p4 *impl) Print(args ...string) (string, error) {\n\tcmd := []string{\"print\"}\n\tcmd = append(cmd, args...)\n\treturn p4.ExecCmd(cmd...)\n}", "func (c *Client) println(v ...interface{}) {\n\tif c.verbose {\n\t\tlog.Println(v...)\n\t}\n}", "func (l *Logger) Print(args ...interface{}) {\n\tl.print.Print(args...)\n}", "func printCmdline(g *gocui.Gui, format string, s ...interface{}) {\n\tg.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(\"cmdline\")\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Set focus on cmdline view failed: %s\", err)\n\t\t}\n\t\tv.Clear()\n\t\tfmt.Fprintf(v, format, s...)\n\n\t\t// Clear the message after 1 second. Use timer here because it helps to show message a constant time and avoid blinking.\n\t\tif format != \"\" {\n\t\t\t// When user pushes buttons quickly and messages should be displayed a constant period of time, in that case\n\t\t\t// if there is a non-expired timer, refresh it (just stop existing and create new one)\n\t\t\tif cmdTimer != nil {\n\t\t\t\tcmdTimer.Stop()\n\t\t\t}\n\t\t\tcmdTimer = time.NewTimer(time.Second)\n\t\t\tgo func() {\n\t\t\t\t<-cmdTimer.C\n\t\t\t\tprintCmdline(g, \"\") // timer expired - wipe message.\n\t\t\t}()\n\t\t}\n\n\t\treturn nil\n\t})\n}", "func (o *Output) Print() {\n\tlogMsg := strings.Builder{}\n\tfor _, msg := range o.Output {\n\t\tlogMsg.WriteString(msg.Prettify(true))\n\t}\n\tlog.Printf(\"\\nParsing errors: %d\\n%sNumber Of Errors: %d\\n%sOutput:\\n%s\", len(o.ParseError.Message), o.ParseError.Prettify(true), len(o.Error.Message), o.Error.Prettify(true), logMsg.String())\n}", "func Print(args ...interface{}) {\n\tNewDefaultEntry().Print(args...)\n}", "func (m *Msg) PrintMsg(w io.Writer) (n int, err error) {\n\tif len(m.Body) == 0 {\n\t\treturn 0, nil\n\t}\n\n\tif m.Body[len(m.Body)-1] != '\\n' {\n\t\treturn fmt.Fprintln(w, m.Body)\n\t}\n\treturn fmt.Fprint(w, m.Body)\n}", "func (self *Subscribe) debugPrint() {\n\tself.dprint(\"\", 0)\n}", "func printer(c <-chan string) {\n\tfor {\n\t\tmsg := <- c\n\t\tfmt.Println(\"received\", msg)\n\t}\n}", "func console() {\r\n\tfor {\r\n\t\t<-ConsoleUp\r\n\t}\r\n}", "func DisplayMessage(msg string) {\n\tcolor.Set(color.FgRed)\n\tfmt.Println(msg)\n\tcolor.Unset()\n}", "func Print(args ...interface{}) {\n\tLogger.Print(args...)\n}", "func (p *Prompt) Print() {\n\tfor i := 0; i < len(p.Items); i++ {\n\t\tif i != 0 {\n\t\t\tp.Items[i].Prefix()\n\t\t}\n\t\tfmt.Print(p.Items[i])\n\t}\n}", "func printer(c <- chan string, d chan int){\n\tfor{\n\t\tmsg := <- c\n\t\tfmt.Println(msg)\n\t\t//fmt.Println(<- d)\n\t\ttime.Sleep(time.Second*1)\n\t}\n}", "func Print() {\n\tfmt.Printf(\"Version: %s\\n\", Version)\n\tfmt.Printf(\"Commit: %s\\n\", Commit)\n\tfmt.Printf(\"Build Date: %s\\n\", Date)\n}", "func (logger *FTPLogger) Print(sessionID string, message interface{}) {\n\tlogrus.WithFields(logrus.Fields{\"time\": time.Now(), \"session\": sessionID, \"message\": message}).Debug(\"FTP:\", message)\n}", "func consolePrintf(tag string, c *color.Color, format string, a ...interface{}) {\n\tprivateMutex.Lock()\n\tdefer privateMutex.Unlock()\n\n\tswitch tag {\n\tcase \"Debug\":\n\t\t// if no arguments are given do not invoke debug printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\toutput := color.Output\n\t\tcolor.Output = stderrColoredOutput\n\t\tif isatty.IsTerminal(os.Stderr.Fd()) {\n\t\t\tc.Print(ProgramName() + \": <DEBUG> \")\n\t\t\tc.Printf(format, a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": <DEBUG> \")\n\t\t\tfmt.Fprintf(color.Output, format, a...)\n\t\t}\n\t\tcolor.Output = output\n\tcase \"Fatal\":\n\t\tfallthrough\n\tcase \"Error\":\n\t\t// if no arguments are given do not invoke fatal and error printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\toutput := color.Output\n\t\tcolor.Output = stderrColoredOutput\n\t\tif isatty.IsTerminal(os.Stderr.Fd()) {\n\t\t\tc.Print(ProgramName() + \": <ERROR> \")\n\t\t\tc.Printf(format, a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": <ERROR> \")\n\t\t\tfmt.Fprintf(color.Output, format, a...)\n\t\t}\n\t\tcolor.Output = output\n\tcase \"Info\":\n\t\t// if no arguments are given do not invoke info printer.\n\t\tif len(a) == 0 {\n\t\t\treturn\n\t\t}\n\t\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\t\tc.Print(ProgramName() + \": \")\n\t\t\tc.Printf(format, a...)\n\t\t} else {\n\t\t\tfmt.Fprint(color.Output, ProgramName()+\": \")\n\t\t\tfmt.Fprintf(color.Output, format, a...)\n\t\t}\n\tdefault:\n\t\tif isatty.IsTerminal(os.Stdout.Fd()) {\n\t\t\tc.Printf(format, a...)\n\t\t} else {\n\t\t\tfmt.Fprintf(color.Output, format, a...)\n\t\t}\n\t}\n}", "func (s *Screen) Print() {\n\tfor _, row := range s.Pixels {\n\t\tfor _, col := range row {\n\t\t\tif col {\n\t\t\t\tfmt.Print(\"#\")\n\t\t\t} else {\n\t\t\t\tfmt.Print(\".\")\n\t\t\t}\n\t\t}\n\t\tfmt.Print(\"\\n\")\n\t}\n\tfmt.Print(\"\\n\")\n}", "func (adapter *Shell) WriteMessage(message string) {\n\tfmt.Fprintln(adapter.output, message)\n}", "func (m *MyLagacyPrinter) Print(s string) (newMsg string) {\n\tnewMsg = fmt.Sprintf(\"Legacy Printer: %s\\n\", s)\n\tfmt.Println(newMsg)\n\treturn\n}", "func (b *printer) Print(args ...interface{}) {\n\t_, _ = Fprint(&b.buf, args...)\n}", "func printError(message string) {\n\tcolor.Set(color.FgRed) // set color for the logging\n\tlog.Printf(\"%s\", message)\n\tcolor.Unset() // Don't forget to unset\n}", "func (results *Results) Print() {\n\tif verbose {\n\t\tfor _, result := range results.List {\n\t\t\tresult.Print()\n\t\t}\n\t}\n\n\tvar state string\n\tif results.Passed {\n\t\tstate = \"OK\"\n\t} else {\n\t\tstate = \"FAIL\"\n\t}\n\n\tif !verbose {\n\t\tfmt.Println(state)\n\t} else {\n\t\tfmt.Printf(\"--- %s %v\", state, results.Duration)\n\t}\n}", "func ExamplePrint() {\n\tsetup()\n\n\tlog.Print(\"hello world\")\n\t// Output: {\"level\":\"debug\",\"time\":1199811905,\"message\":\"hello world\"}\n}", "func Print(args ...interface{}) {\n\t_, err := fmt.Fprint(globalOptions.stdout, args...)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, \"unable to write to stdout: %v\\n\", err)\n\t}\n}", "func print(args ...interface{}) {\n\tok := logLevel <= 1\n\n\tif ok {\n\t\tprintf(\"%s\", fmt.Sprint(args...))\n\t}\n}" ]
[ "0.7248072", "0.6614557", "0.6585811", "0.65408134", "0.6454384", "0.6397477", "0.63343596", "0.62438166", "0.6239294", "0.61894053", "0.6165839", "0.615925", "0.61148924", "0.6012079", "0.589406", "0.5827574", "0.5804627", "0.57899857", "0.5774568", "0.57707804", "0.57528526", "0.56596935", "0.5654795", "0.56366783", "0.56221205", "0.5605277", "0.5584208", "0.55432606", "0.5504466", "0.5501651", "0.5496013", "0.5490836", "0.54867715", "0.5472396", "0.545529", "0.544623", "0.54393554", "0.5422179", "0.5419932", "0.54136205", "0.5412063", "0.5403172", "0.53825605", "0.5370386", "0.5357974", "0.53317004", "0.53147006", "0.53124964", "0.52998114", "0.529359", "0.52774626", "0.52726394", "0.52531075", "0.52439564", "0.52355474", "0.52311033", "0.5230282", "0.5227437", "0.5218056", "0.5211668", "0.5208767", "0.52075166", "0.52072996", "0.520428", "0.5199212", "0.51905054", "0.5184999", "0.51814884", "0.5179149", "0.5161991", "0.5147653", "0.5146086", "0.5139517", "0.51354164", "0.51352495", "0.5132929", "0.5130806", "0.51202303", "0.51158583", "0.511277", "0.51064926", "0.5097644", "0.50819075", "0.50771934", "0.5067769", "0.50671494", "0.50618863", "0.5053953", "0.5048194", "0.5045202", "0.504329", "0.5043178", "0.50372183", "0.50355345", "0.5024762", "0.5019089", "0.50183713", "0.4999087", "0.49959242", "0.49912152" ]
0.68781453
1
printWelcomeMessage will print the welcome message to the console
func printWelcomeMessage() { welcomeMessage := ` |--------------------------------| | Hi there | | Welcome to | | The Local Shopping Mall | |--------------------------------| ` fmt.Println(welcomeMessage) }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (guild *Guild) PrintWelcome(user *discordgo.User) error {\n\tif !guild.IsManaged() {\n\t\treturn ERR_NOT_MANAGED\n\t}\n\n\tif guild.Settings.Welcome == \"\" {\n\t\treturn ERR_NO_WELCOME\n\t}\n\n\twelcomeChannel, err := guild.GetChannelID(\"welcome\")\n\tif err != nil {\n\t\treturn &botError{ERR_MISSING_CHANNEL, \"welcome\"}\n\t}\n\n\tvar messageStrReplace = map[string]string{\n\t\t\"{mention}\": user.Mention(),\n\t\t\"{guild}\": guild.Name,\n\t\t\"{user}\": user.Username,\n\t}\n\n\tmessage := guild.Settings.Welcome\n\tfor str, rep := range messageStrReplace {\n\t\tmessage = strings.Replace(message, str, rep, -1)\n\t}\n\n\t_, _ = goBot.ChannelMessageSend(welcomeChannel, message)\n\n\treturn nil\n}", "func TestConsoleWelcome(t *testing.T) {\n\t// Start a lachesis console, make sure it's cleaned up and terminate the console\n\tcli := exec(t,\n\t\t\"--port\", \"0\", \"--maxpeers\", \"0\", \"--nodiscover\", \"--nat\", \"none\",\n\t\t\"console\")\n\n\t// Gather all the infos the welcome message needs to contain\n\tcli.SetTemplateFunc(\"goos\", func() string { return runtime.GOOS })\n\tcli.SetTemplateFunc(\"goarch\", func() string { return runtime.GOARCH })\n\tcli.SetTemplateFunc(\"gover\", runtime.Version)\n\tcli.SetTemplateFunc(\"version\", func() string { return params.VersionWithCommit(\"\", \"\") })\n\tcli.SetTemplateFunc(\"niltime\", genesisStart)\n\tcli.SetTemplateFunc(\"apis\", func() string { return ipcAPIs })\n\n\t// Verify the actual welcome message to the required template\n\tcli.Expect(`\nWelcome to the Lachesis JavaScript console!\n\ninstance: go-lachesis/v{{version}}/{{goos}}-{{goarch}}/{{gover}}\ncoinbase: {{.Coinbase}}\nat block: 0 ({{niltime}})\n datadir: {{.Datadir}}\n modules: {{apis}}\n\n> {{.InputLine \"exit\"}}\n`)\n\tcli.ExpectExit()\n}", "func welcome(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome\")\n}", "func Welcome() {\r\n\tfmt.Printf(\"\\nWelcome to Hangman!\\n\\n\")\r\n}", "func displayWelcomeMessage() {\n\tart :=\n\t\t` \t\n================================================================================================ \n ___ __ __ _ _ ___ ___ __ ___ __ ___ __ ___ ___ \n| | |__ | / ' / \\ | \\/ | |__ | / \\ |\\ | |__ / \\ /__ / \\ |__ | \n|/\\| |___ |___\\__, \\__/ | | |___ | \\__/ | \\| |___ \\__/ ___/ \\__/ | | \n\n================================================================================================= \n\t \n\t\n\t`\n\tfmt.Println(art)\n\tquitMessage := \"\\nPress Ctrl + C to stop the tracker..\"\n\tfmt.Println(quitMessage)\n\n}", "func (o *Org_Example_Demo) WelcomeMessage(ctx context.Context) (outputMessage string, err error) {\n\terr = o.object.CallWithContext(ctx, InterfaceOrg_Example_Demo+\".WelcomeMessage\", 0).Store(&outputMessage)\n\treturn\n}", "func Welcome(name string) string {\n\treturn fmt.Sprintf(\"Welcome to my party, %s!\", name)\n}", "func DrawWelcome() {\n\tfmt.Println(`\n\t\t\t____. .___ __________ .___ \n\t\t\t| | ____ __ _____ ___ __| _/_ __ \\______ \\ ____ ____ __| _/_ __ \n\t\t\t| |/ __ \\| | \\ \\/ / / __ | | \\ | ___// __ \\ / \\ / __ | | \\\n\t\t/\\__| \\ ___/| | /> < / /_/ | | / | | \\ ___/| | \\/ /_/ | | /\n\t\t\\________|\\___ >____//__/\\_ \\ \\____ |____/ |____| \\___ >___| /\\____ |____/ \n\t\t\t\t\t\\/ \\/ \\/ \\/ \\/ \\/ \n\t`)\n}", "func Welcome(name string) string {\n\treturn fmt.Sprintf(Message, name)\n}", "func welcomeMessage() {\n\tfmt.Println(\"Number adding started\")\n}", "func WelcomeMessage(customer string) string {\n\treturn fmt.Sprintf(\"Welcome to the Tech Palace, %s\", strings.ToUpper(customer))\n\n}", "func WelcomeUser(opts display.Options) {\n\tfmt.Printf(`\n\n %s\n\n Pulumi helps you create, deploy, and manage infrastructure on any cloud using\n your favorite language. You can get started today with Pulumi at:\n\n https://www.pulumi.com/docs/get-started/\n\n %s Resources you create with Pulumi are given unique names (a randomly\n generated suffix) by default. To learn more about auto-naming or customizing resource\n names see https://www.pulumi.com/docs/intro/concepts/resources/#autonaming.\n\n\n`,\n\t\topts.Color.Colorize(colors.SpecHeadline+\"Welcome to Pulumi!\"+colors.Reset),\n\t\topts.Color.Colorize(colors.SpecSubHeadline+\"Tip:\"+colors.Reset))\n}", "func (s *Switch) Welcome() string {\n\treturn s.welcome\n}", "func GetWelcomeMessage() string {\n\treturn getRandMessage(welcomeMessages)\n}", "func printGreeting() {\n\tfmt.Println(greeting)\n}", "func PrintGreeting() {\n\tfmt.Println(greeting)\n}", "func (tm *TelegramMessenger) SendWelcome(ID int64, name string) {\n\tgenericSend(tm, ID, fmt.Sprintf(common.TelegramWelcomeMessage, name))\n}", "func GetWelcomeMessage() string {\n\ttmpl, _ := template.New(\"welcome_message\").Parse(WelcomeMessageTmpl)\n\tresult := bytes.Buffer{}\n\ttmpl.Execute(&result, version.Get())\n\treturn result.String()\n}", "func (c *context) testWelcome(t *testing.T) {\n\texpected := \"...and now my watch begins for cluster 'test-cluster-1'! :crossed_swords:\"\n\n\tif c.TestEnv.Config.Communications.Slack.Enabled {\n\n\t\t// Get last seen slack message\n\t\tlastSeenMsg := c.GetLastSeenSlackMessage()\n\n\t\t// Convert text message into Slack message structure\n\t\tm := slack.Message{}\n\t\terr := json.Unmarshal([]byte(*lastSeenMsg), &m)\n\t\tassert.NoError(t, err, \"message should decode properly\")\n\t\tassert.Equal(t, c.TestEnv.Config.Communications.Slack.Channel, m.Channel)\n\t\tassert.Equal(t, expected, m.Text)\n\t}\n}", "func greet(w http.ResponseWriter, req *http.Request) {\n\tfmt.Fprintf(w, \"Welcome\")\n}", "func (app *MgmtApp) defaultWelcomeUser(client Client) {\n client.Send(AppendText(\"Welcome to the machine\", \"red\"))\n client.Send(SetEchoOn(true))\n client.Send(SetPrompt(\"Enter Username: \"))\n client.Send(SetAuthenticated(false))\n client.Send(SetHistoryMode(false))\n}", "func Welcome(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\t_, _ = w.Write([]byte(`{\"success\":\"Welcome to the Beneficiary Claims Data API!\"}`))\n}", "func ClearWelcomeMessageDisplayed(session *sessions.Session) {\n\tsessionClear(session, sessionKeyWelcomeMessageDisplayed)\n}", "func PrintMessage(message string) {\n\tfmt.Println(\"\")\n\tfmt.Println(message)\n\tfmt.Println(\"\")\n}", "func printInfo(message string, args ...interface{}) {\n\tif silent {\n\t\treturn\n\t}\n\tfmt.Printf(\"INFO Slack - \"+message+\"\\n\", args...)\n}", "func (guild *Guild) SetWelcome(msg string) error {\n\tguild.Settings.Welcome = msg\n\tguildSettings.add(guild).save(config.GuildFile)\n\treturn nil\n}", "func handleWelcomes(rootId string, recents *RecentList, toWelcome chan arbor.Writer) {\n\tfor client := range toWelcome {\n\t\tmsg := arbor.ProtocolMessage{\n\t\t\tType: arbor.WelcomeType,\n\t\t\tRoot: rootId,\n\t\t\tMajor: 0,\n\t\t\tMinor: 2,\n\t\t}\n\t\tmsg.Recent = recents.Data()\n\n\t\terr := client.Write(&msg)\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\tcontinue\n\t\t}\n\t\tlog.Println(\"Welcome message: \", msg.String())\n\n\t}\n}", "func PrintMessage(texto string) {\n\tfmt.Println(texto)\n}", "func main() {\n\t// Println prints the phrase on the standard output and also break a line.\n\tfmt.Println(\"Hello Gophers!!\")\n}", "func Greet(s string) string {\n\treturn fmt.Sprint(\"Welcome my dear \", s)\n}", "func randomPrint() {\r\n\tfmt.Println(\"Starting Server!\")\r\n}", "func PrintGreetings(name string) string {\n\treturn greetingsString + \"-\" + name\n}", "func PrintHelloWorld() {\n\tfmt.Printf(\"Hello, world.\\n\")\n}", "func WelcomePrompt(echoRequest *skillserver.EchoRequest) (response *skillserver.EchoResponse) {\n\tresponse = skillserver.NewEchoResponse()\n\n\tresponse.OutputSpeech(\"Welcome Guardian, would you like to equip max light, unload engrams, or transfer an item to a specific character, \" +\n\t\t\"find out how many of an item you have, or ask about Trials of Osiris?\").\n\t\tReprompt(\"Do you want to equip max light, unload engrams, transfer an item, find out how much of an item you have, or ask about Trials of Osiris?\").\n\t\tEndSession(false)\n\n\treturn\n}", "func (a *App) PrintHello() error {\n\tfmt.Println(\"Hellooooooo\", strconv.Itoa(a.lastHello))\n\ta.lastHello++\n\treturn nil\n}", "func Welcome(w http.ResponseWriter, r *http.Request) {\n\t// We can obtain the session token from the requests cookies, which come with every request\n\tc, err := r.Cookie(\"token\")\n\tif err != nil {\n\t\tif err == http.ErrNoCookie {\n\t\t\t// If the cookie is not set, return on unauthorized status\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\t// For any other type of error, return a bad request status\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\t// Get the JWT string from the cookie\n\ttknStr := c.Value\n\n\t// Initialize a new instance of `Claims`\n\tclaims := &Claims{}\n\n\t// Parse the JWT string and store the result in `claims`.\n\t// Note that we are passing the key in this method as well. This method will return an error\n\t// if the token is invalid (if it has expired according to the expiration time we set on sign in),\n\t// or if the signature does not match\n\ttkn, err := jwt.ParseWithClaims(tknStr, claims, func(token *jwt.Token) (interface{}, error) {\n\t\treturn jwtKey, nil\n\t})\n\tif err != nil {\n\t\tif err == jwt.ErrSignatureInvalid {\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\tif !tkn.Valid {\n\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\treturn\n\t}\n\n\t// Finally, return the welcome message to the user, along with their\n\t// username given in the token\n\tw.Write([]byte(fmt.Sprintf(\"Welcome %s!\", claims.Username)))\n}", "func handleWelcome(w http.ResponseWriter, r *http.Request) {\n\t// Generate a UUID.\n\thasher := md5.New()\n\thasher.Write([]byte(strconv.FormatInt(time.Now().Unix(), 10)))\n\tuuid := hex.EncodeToString(hasher.Sum(nil))\n\n\t// Create a session for this UUID\n\tsessions[uuid] = Session{}\nUser.UUID = uuid\n\tfmt.Println(User)\n\tw.Header().Add(\"Authorization\", uuid)\n\tfmt.Println(w.Header())\n\t// Write a JSON containg the welcome message and the generated UUID\n\twriteJSON(w, JSON{\n\t\t\"uuid\": uuid,\n\t\t\"message\": WelcomeMessage,\n\t})\n}", "func Printhello() (int, error) {\n\tvar buf bytes.Buffer\n\tlogger := log.New(&buf, \"logger: \", log.LstdFlags)\n\tlogger.Print(\"hello world\")\n\treturn fmt.Print(&buf)\n}", "func (guild *Guild) PrintGoodbye(user *discordgo.User) error {\n\tif !guild.IsManaged() {\n\t\treturn ERR_NOT_MANAGED\n\t}\n\n\tif guild.Settings.Goodbye == \"\" {\n\t\treturn ERR_NO_GOODBYE\n\t}\n\n\twelcomeChannel, err := guild.GetChannelID(\"welcome\")\n\tif err != nil {\n\t\treturn &botError{ERR_MISSING_CHANNEL, \"welcome\"}\n\t}\n\n\tvar messageStrReplace = map[string]string{\n\t\t\"{mention}\": user.Mention(),\n\t\t\"{guild}\": guild.Name,\n\t\t\"{user}\": user.Username,\n\t}\n\n\tmessage := guild.Settings.Goodbye\n\tfor str, rep := range messageStrReplace {\n\t\tmessage = strings.Replace(message, str, rep, -1)\n\t}\n\n\t_, _ = goBot.ChannelMessageSend(welcomeChannel, message)\n\n\treturn nil\n}", "func WelcomeCallback(con *irc.Connection) {\n\tcon.AddCallback(\"001\", func(e *irc.Event) {\n\t\tcon.Privmsgf(\"NickServ\", \"identify %s\", config.IRCNickPass)\n\t\ttime.Sleep(time.Second * 15) // Need to wait a little for the registration to take effect\n\n\t\tfor _, room := range config.IRCChannels {\n\t\t\tcon.Join(room)\n\t\t\tlog.Printf(\"Connected to channel %s\\n\", room)\n\t\t}\n\t})\n}", "func GetWelcome() string {\n\tmessage := []byte(`__________________________________________________________________________________________________________________________________\n _____/\\\\\\\\\\\\\\\\\\____________________________________________________________/\\\\\\\\\\\\\\\\\\_________________________________/\\\\\\_________\n ___/\\\\\\\\\\\\\\\\\\\\\\\\\\________________________________________________________/\\\\\\\\\\\\\\\\\\\\\\\\\\______________________________\\/\\\\\\_________\n __/\\\\\\/////////\\\\\\___________________/\\\\\\_______________________________/\\\\\\/////////\\\\\\___________________/\\\\\\______\\/\\\\\\_________\n _\\/\\\\\\_______\\/\\\\\\__/\\\\\\____/\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\_____/\\\\\\\\\\______________\\/\\\\\\_______\\/\\\\\\__/\\\\\\____/\\\\\\__/\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\_________\n _\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\___\\/\\\\\\_\\////\\\\\\////____/\\\\\\///\\\\\\____________\\/\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\_\\/\\\\\\___\\/\\\\\\_\\////\\\\\\////__\\/\\\\\\\\\\\\\\\\\\\\__\n _\\/\\\\\\/////////\\\\\\_\\/\\\\\\___\\/\\\\\\____\\/\\\\\\_______/\\\\\\__\\//\\\\\\___________\\/\\\\\\/////////\\\\\\_\\/\\\\\\___\\/\\\\\\____\\/\\\\\\______\\/\\\\\\/////\\\\\\_\n _\\/\\\\\\_______\\/\\\\\\_\\/\\\\\\___\\/\\\\\\____\\/\\\\\\_/\\\\__\\//\\\\\\__/\\\\\\____________\\/\\\\\\_______\\/\\\\\\_\\/\\\\\\___\\/\\\\\\____\\/\\\\\\_/\\\\__\\/\\\\\\___\\/\\\\\\_\n _\\/\\\\\\_______\\/\\\\\\_\\//\\\\\\\\\\\\\\\\\\_____\\//\\\\\\\\\\____\\///\\\\\\\\\\/_____________\\/\\\\\\_______\\/\\\\\\_\\//\\\\\\\\\\\\\\\\\\_____\\//\\\\\\\\\\___\\/\\\\\\___\\/\\\\\\_\n _\\///________\\///___\\/////////_______\\/////_______\\/////_______________\\///________\\///___\\/////////_______\\/////____\\///____\\///__\n ___________________________________________________________________________________________________________________________________\n _____________________________________________________________________________ https://www.github.com/pepodev/autoauth _____________\n\t\t \nAutoAuth is CLI to create preset and start automatic authentication web portal for internet access like Public-Wifi\n`)\n\treturn string(message)\n}", "func PrintInfo(msg interface{}) {\n\tif os.Getenv(\"GHORG_QUIET\") == \"true\" {\n\t\treturn\n\t}\n\n\tswitch os.Getenv(\"GHORG_COLOR\") {\n\tcase \"enabled\":\n\t\tcolor.New(color.FgYellow).Println(msg)\n\tdefault:\n\t\tfmt.Println(msg)\n\t}\n}", "func main() {\n\t// Get a greeting message and print it.\n\t//Access the Hello function in the greetings package\n\tmessage := greetings.Hello(\"Gladys\")\n\tfmt.Println(message)\n}", "func ExamplePrint() {\n\tsetup()\n\n\tlog.Print(\"hello world\")\n\t// Output: {\"level\":\"debug\",\"time\":1199811905,\"message\":\"hello world\"}\n}", "func main() {\n\tfmt.Print(HelloWorld(\"Gopher\"))\n}", "func printHelp() {\n\tfmt.Printf(helpMessage)\n\tos.Exit(0)\n}", "func GetWelcomeHandler(w http.ResponseWriter, r *http.Request) {\n\tcommon.RenderJSON(w, r, welcomeStruct{Message: \"Hello World\"})\n\n}", "func SayHi(name string) {\n fmt.Printf(\"Hi, %s\\n\", name)\n}", "func printGreeting(b bot) {\n\tfmt.Println(b.getGreeting())\n}", "func index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func PrintMessage(args ...interface{}) {\n\tfmt.Println()\n\tfmt.Println(\"---------------------------------------------------------------\")\n\tfmt.Println(args...)\n\tfmt.Println(\"---------------------------------------------------------------\")\n\tfmt.Println()\n}", "func Greeting(str string) {\n\tfmt.Printf(\"Greeting %s\\n\", str);\n}", "func (mp *messagePrinter) printMessage(message string) {\n\tprintln(message)\n}", "func PrintSuccess(msg interface{}) {\n\tswitch os.Getenv(\"GHORG_COLOR\") {\n\tcase \"enabled\":\n\t\tcolor.New(color.FgGreen).Println(msg)\n\tdefault:\n\t\tfmt.Println(msg)\n\t}\n}", "func SendWelcomeEmail(to string, code string) error {\n\tsubject := \"Welcome to TrekNext!\"\n\thtml := fmt.Sprintf(\"<h4>Thanks for signing up!</h4><p>Please follow this link to confirm your email: %s/confirm/%s </p>\", environment.CLIENT_URL, code)\n\tfrom := \"[email protected]\"\n\treturn send(to, subject, html, from)\n}", "func GetWelcomeHandler(w http.ResponseWriter, r *http.Request) {\r\n\tcommon.RenderJSON(w, r, entity.Welcome{Message: \"Hello World\"})\r\n}", "func SayHello() {\n\tfmt.Println(\"Hello\")\n}", "func (sh *stmHelper) printMessage(msg string) (err error) {\n\terr = sh.ClearDisplay()\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn sh.PrintText(0, 0, stm.Foreground, msg)\n}", "func printUserMessage() {\n\tgo func() {\n\t\tfor {\n\t\t\tm := <-MessageChannel\n\t\t\tswitch m.Level {\n\t\t\tcase messages.Info:\n\t\t\t\tfmt.Println(color.CyanString(\"\\n[i] %s\", m.Message))\n\t\t\tcase messages.Note:\n\t\t\t\tfmt.Println(color.YellowString(\"\\n[-] %s\", m.Message))\n\t\t\tcase messages.Warn:\n\t\t\t\tfmt.Println(color.RedString(\"\\n[!] %s\", m.Message))\n\t\t\tcase messages.Success:\n\t\t\t\tfmt.Println(color.GreenString(\"\\n[+] %s\", m.Message))\n\t\t\tcase messages.Plain:\n\t\t\t\tfmt.Println(\"\\n\" + m.Message)\n\t\t\tdefault:\n\t\t\t\tfmt.Println(color.RedString(\"\\n[_-_] Invalid message level: %d\\r\\n%s\", m.Level, m.Message))\n\t\t\t}\n\t\t}\n\t}()\n}", "func main() {\n\tfmt.Println(\"Hello, my name is Jordan\")\n}", "func renderWelcomePage(w http.ResponseWriter, r *http.Request, status *dpstatus) {\n welcomeTemplate.ExecuteTemplate(w, \"WelcomePage\",\n struct {\n Style template.HTML\n Statusok bool\n Giterr error\n Wd, Prefix string\n } { servicestyle, status.ok, status.giterror, status.workingdir, \"/\"+status.usersets.controlprefix })\n}", "func Greet() {\n\tfmt.Println(\"helllo\")\n}", "func (pf PrintFunc) SayHello() {\n\tif pf != nil {\n\t\tpf(\"Hello\")\n\t} else {\n\t\tfmt.Println(\"Hello from the default printer\")\n\t}\n}", "func main() {\n\tfmt.Println(\"Hello World\") // Print a line with hello world\n}", "func SayHello() string {\n\treturn \"Hello wolrd $$!@%#$@!#\"\n}", "func TestPrintStartupMessage(t *testing.T) {\n\tobj, fsDir, err := prepareFS()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(fsDir)\n\tif err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tapiEndpoints := []string{\"http://127.0.0.1:9000\"}\n\tprintStartupMessage(apiEndpoints, nil)\n}", "func (uh *UserHandler) WelcomePage(w http.ResponseWriter, r *http.Request) {\n\tuh.Temp.ExecuteTemplate(w, \"WelcomePage.html\", nil)\n}", "func PrintInfo(version, commit, date string) {\n\tfmt.Println(\"🔥 Heamon version:\", version)\n\tfmt.Println(\"🛠️ Commit:\", commit)\n\tfmt.Println(\"📅 Release Date:\", date)\n}", "func PrintSuccess(message string) {\n\tfmt.Printf(green + \"✔ \" + message + noFormat + \"\\n\")\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprint(w, \"Welcome!\\n\")\n}", "func Greet() string {\n\treturn \"Hello Github Action, Jacob is awesome\"\n}", "func main() {\n\t// Uncomment the following lines to customize the chatbot\n\t// chatbot.WelcomeMessage = \"What's your name?\"\n\t// chatbot.ProcessFunc(chatbotProcess)\n\n\t// Use the PORT environment variable\n\tfmt.Println(\"Hello World \")\n}", "func TestPrintStartupMessage(t *testing.T) {\n\tobj, fsDir, err := prepareFS()\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\tdefer os.RemoveAll(fsDir)\n\tif err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tapiEndpoints := []string{\"http://127.0.0.1:9000\"}\n\tprintStartupMessage(apiEndpoints)\n}", "func Index(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintln(w, \"Welcome!\")\n}", "func (h *Human) SayHi() {\n\tfmt.Printf(\"Hi, I am %s you can call me on %s\\n\", h.name, h.phone)\n}", "func Hi(name string) {\n\tfmt.Println(\"Hi\", name)\n}", "func SayHi() {\n\tfmt.Println(\"Hi from go-module-test-b! This is version 1.2.0\")\n}", "func printMessage(message string) {\n\tdocument := js.Global().Get(\"document\")\n\tp := document.Call(\"createElement\", \"p\")\n\tp.Set(\"innerHTML\", message)\n\tdocument.Get(\"body\").Call(\"appendChild\", p)\n}", "func printHeading(content string) {\n\tfmt.Printf(\"\\n====== %s\\n\", content)\n}", "func printMsg(msg string) {\n\tfmt.Println(msg)\n}", "func Welcome(userID string) map[string]string {\n\t// Generate a UUID.\n\t// bygeeb time stamp unix format and represent it in base 10\n\thasher := md5.New()\n\thasher.Write([]byte(strconv.FormatInt(time.Now().Unix(), 10)))\n\tuuid := hex.EncodeToString(hasher.Sum(nil))\n\t// fmt.Println(uuid)\n\n\tsessionModel := controllers.NewSessionModel(db.GetSession())\n\tdefer sessionModel.DBSession.Close()\n\n\t// check if the user has an already opened session\n\tsession, err1 := sessionModel.GetSession(userID)\n\t// if there is an error this means that this user has no sessions opened\n\tif err1 != nil {\n\t\tfmt.Println(err1)\n\t\t// Create a session for this UUID and added it to the database\n\t\tNewSession, err := sessionModel.InsertNewSession(uuid, userID)\n\n\t\tif err != nil {\n\t\t\treturn map[string]string{\n\t\t\t\t\"error\": \"Could not create a session key \" + err.Error(),\n\t\t\t\t\"message\": \"\",\n\t\t\t}\n\t\t}\n\n\t\tsessions[NewSession.UUID] = Session{}\n\t\t// Write a JSON containg the welcome message and the generated UUID\n\t\treturn map[string]string{\n\t\t\t\"uuid\": NewSession.UUID,\n\t\t\t\"message\": WelcomeMessage,\n\t\t}\n\n\t\tsessions[session.UUID] = Session{}\n\t\t// Write a JSON containg the welcome message and the generated UUID\n\t\treturn map[string]string{\n\t\t\t\"uuid\": session.UUID,\n\t\t\t\"message\": WelcomeMessage,\n\t\t}\n\t}\n\n\tsessions[session.UUID] = Session{}\n\t// Write a JSON containg the welcome message and the generated UUID\n\treturn map[string]string{\n\t\t\"uuid\": session.UUID,\n\t\t\"message\": WelcomeMessage,\n\t}\n\n}", "func (chp *Printer) Print(msg string) {\n\tchp.StringChannel <- msg\n}", "func main() {\n\tfmt.Println(\"Welcome Gophers ☺\") //no semicolon\n}", "func Hello(name string) {\n\tfmt.Printf(\"Hello, %s!\\n\", name)\n}", "func mainHandler(w http.ResponseWriter, r *http.Request) {\n fmt.Fprintf(w, \"Welcome to the home page!\")\n}", "func Greet() {\n\tfmt.Println(\"Hello, World!\")\n}", "func Greet() {\n\tfmt.Println(\"Hello World!\")\n}", "func WelcomeUser(u datastore.User) {\n\n\tbody := `<h3>Welcome, %s!</h3>\n <p>Please click on this link to activate your account:</p>\n\t\t\t <p><a href=\"%s\" target=\"_blank\">Activate my account</a></p>\n\t\t\t <p>Happy RTCL-ing</p>`\n\tlink := os.Getenv(\"API_URL\") + \"/users/\" + u.ID.Hex() + \"/confirm/\" + u.KeyGen()\n\tbody = fmt.Sprintf(body, u.FirstName, link)\n\n\te := New()\n\te.FromEmail = \"[email protected]\"\n\te.FromName = \"RTCL Notifier\"\n\te.Subject = \"Welcome to RTCL\"\n\te.ToEmail = u.Email\n\te.ToName = u.FirstName + \" \" + u.LastName\n\te.PlainContent = \"Confirmation link: \" + link\n\te.HTMLContent = body\n\te.Send()\n}", "func Println() {\n\tfmt.Println(\"Hello world from test.go\")\n}", "func PrintMessage(infotype, message string) {\n\n\tswitch infotype {\n\tcase \"debug\":\n\t\tcolor.Set(color.FgHiYellow)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tcase \"success\":\n\t\tcolor.Set(color.FgHiGreen)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tcase \"error\":\n\t\tcolor.Set(color.FgHiRed)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\tdefault:\n\t\tcolor.Set(color.FgHiWhite)\n\t\tdefer color.Unset()\n\t\tfmt.Println(message)\n\t}\n}", "func PrintPrompt(g *gocui.Gui) {\n\tpromptString := \"[w,a,s,d,e,?] >>\"\n\n\tg.Update(func(g *gocui.Gui) error {\n\t\tv, err := g.View(Prompt)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tv.Clear()\n\t\tv.MoveCursor(0, 0, true)\n\n\t\tif consecutiveError == 0 {\n\t\t\tfmt.Fprintf(v, color.Green(color.Regular, promptString))\n\t\t} else {\n\t\t\tfmt.Fprintf(v, color.Red(color.Regular, promptString))\n\t\t}\n\t\treturn nil\n\t})\n}", "func greet(w http.ResponseWriter, r *http.Request) {\n\t// this print hello world when someone vists the endpoint\n\tfmt.Fprint(w, \"Hello World\")\n}", "func ready(session *discordgo.Session, ready *discordgo.Ready) {\n\n\t// Display name of bot to user\n\tlog.Println(\"Logged in as\", session.State.User, \"press CTRL-C to exit\")\n}", "func home(w http.ResponseWriter, r *http.Request) {\n\tfmt.Fprintf(w, \"Welcome home!\")\n}", "func PrintInfo(message string) {\n\tfmt.Printf(cSkyyblue + message + noFormat + \"\\n\")\n}", "func greet(name string, greeting string) {\n\tfmt.Println(greeting, name)\n}", "func (adapter *Shell) WriteMessage(message string) {\n\tfmt.Fprintln(adapter.output, message)\n}", "func main() {\n\tfmt.Println(\"Welcome to Golang World\")\n\n\tvar name string // declaring variable\n\tfmt.Print(\"Enter your name: \")\n\tfmt.Scanln(&name) // accepting user input\n\n\tgreeting(name)\n}", "func Print(greet, name string) {\n\tfmt.Printf(\"%v, %v!\\n\", greet, name)\n}", "func printMessageError() {\n\tfmt.Println()\n\tfmt.Println(\"Please enter a message!\")\n\tfmt.Println()\n}" ]
[ "0.7378225", "0.7258111", "0.69423187", "0.6925658", "0.6914729", "0.6817779", "0.678318", "0.67272013", "0.6720024", "0.661769", "0.64663804", "0.638798", "0.63207567", "0.6128446", "0.60683733", "0.6051768", "0.6019674", "0.5966153", "0.5941388", "0.5847426", "0.5793717", "0.573117", "0.5720896", "0.56940126", "0.56793743", "0.5590686", "0.5576878", "0.555106", "0.5541163", "0.55348265", "0.55251914", "0.55060446", "0.5495959", "0.5494639", "0.5484321", "0.54686636", "0.54441404", "0.5434916", "0.5424392", "0.5395269", "0.53729063", "0.537074", "0.53400075", "0.5316794", "0.53121704", "0.53030527", "0.5290336", "0.5285909", "0.5285698", "0.5279272", "0.5274216", "0.5273719", "0.52595276", "0.5251247", "0.524728", "0.5222162", "0.52206737", "0.5220509", "0.52177703", "0.5214092", "0.51982623", "0.5174842", "0.51718915", "0.5148738", "0.5139285", "0.51387906", "0.5117705", "0.51096064", "0.5101377", "0.5097812", "0.5093192", "0.5091123", "0.50879556", "0.50844", "0.5058994", "0.50497323", "0.5043558", "0.5035905", "0.50267553", "0.50202286", "0.50121146", "0.5003673", "0.49988332", "0.49966624", "0.49732414", "0.49597022", "0.49586308", "0.49571013", "0.49409276", "0.49352846", "0.49306297", "0.49199355", "0.4916889", "0.49155864", "0.49124408", "0.49046516", "0.48997593", "0.48942047", "0.48922026", "0.4884872" ]
0.77726763
0
printCurrentProducts will print the current list of products and their prices
func printCurrentProducts(products Products) { currentProducts := ` =============================== = Here is a list of = = our current products = =============================== ` fmt.Println(currentProducts) for _, product := range products { fmt.Printf("Product: %v \n", product.Name) fmt.Printf("Price: £%.2f \n\n", product.Price) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printDiscountProducts(discounts Discounts, products Products) {\n\tcurrentDiscounts :=\n\t\t`\n===============================\n= Here is a list of =\n= our current discounts =\n===============================\n\t\t`\n\tfmt.Println(currentDiscounts)\n\tfor _, discount := range discounts {\n\t\tproduct := findProduct(products, discount.Code)\n\t\tfmt.Printf(\"%v Discount offer: %v \\n\\n\", product.Name, discount.Description)\n\t}\n}", "func (prod *Product) printData() {\n\tfmt.Printf(\"ID: %v\\n\", prod.id)\n\tfmt.Printf(\"Title: %v\\n\", prod.title)\n\tfmt.Printf(\"Description: %v\\n\", prod.description)\n\tfmt.Printf(\"Price: $%.2f\\n\", prod.price)\n}", "func (ps productsService) ListProducts(ctx context.Context, offset, limit int) (ProductPage, error) {\n\treturn ps.products.GetProducts(ctx, offset, limit)\n}", "func (i *ResolvedProductIter) Current() (*ResolvedProduct, error) {\n\tif i.err != nil {\n\t\treturn nil, i.err\n\t}\n\treturn &i.page[i.i], nil\n}", "func GetProducts(c *fiber.Ctx) error {\n\tdb := database.Connection()\n\treturn models.GetProducts(db, c)\n}", "func (p *ProductDlv) GetProducts(c context.Context) ([]entity.Product, error) {\n\tvar res []entity.Product\n\tqs := map[string]string{}\n\n\tactive := qs[\"active\"]\n\tfmt.Println(active)\n\n\tcreatedAt := qs[\"created_at\"]\n\tfmt.Println(createdAt)\n\n\tdiscount := qs[\"discount\"]\n\tfmt.Println(discount)\n\n\tid := qs[\"id\"]\n\tfmt.Println(id)\n\n\tname := qs[\"name\"]\n\tfmt.Println(name)\n\n\tprice := qs[\"price\"]\n\tfmt.Println(price)\n\n\tstatus := qs[\"status\"]\n\tfmt.Println(status)\n\n\treturn res, nil\n}", "func ViewAllProducts(c *gin.Context) {\n\tvar prod []Products\n\tdb := DbConn()\n\terr := db.Find(&prod).Error\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tc.JSON(http.StatusServiceUnavailable, err)\n\t}\n\n\tc.JSON(http.StatusOK, prod)\n}", "func (p *Products) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tlp := data.GetProducts()\n\n\terr := data.ToJSON(lp, w)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Unable to marshal json\", http.StatusInternalServerError)\n\t}\n\n}", "func GetProducts() Products {\n\treturn productsList\n}", "func (ph *Handler) ListProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : GET /app/product API hit!\")\n\treq := ListProductRequest{\n\t\tLimit: DefaultListProductLimit,\n\t\tOffset: DefaultOffset,\n\t}\n\trequest, err := validateListProductRequest(&req, r)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.ValidationErrorCode, err.Error())\n\t\treturn\n\t}\n\tproducts, err := ph.ps.ListProduct(r.Context(), request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : products listed!\")\n\tutils.Send(w, 200, products)\n}", "func (c *ProductsApiController) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tquery := r.URL.Query()\n\tproductType := query.Get(\"productType\")\n\tlimit, err := parseInt32Parameter(query.Get(\"limit\"))\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcursor := query.Get(\"cursor\")\n\tenhance, _ := strconv.ParseBool(query.Get(\"enhance\"))\n\txTRACEID := r.Header.Get(\"X-TRACE-ID\")\n\txTOKEN := r.Header.Get(\"X-TOKEN\")\n\tresult, err := c.service.GetProducts(r.Context(), productType, limit, cursor, enhance, xTRACEID, xTOKEN)\n\t//If an error occured, encode the error with the status code\n\tif err != nil {\n\t\tEncodeJSONResponse(err.Error(), &result.Code, w)\n\t\treturn\n\t}\n\t//If no error, encode the body and the result code\n\tEncodeJSONResponse(result.Body, &result.Code, w)\n\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func (s *Service) Products(ctx context.Context) ([]*types.Products, error) {\n\n\titems := make([]*types.Products, 0)\n\tsql := `SELECT id, name, price, qty FROM products WHERE active = true ORDER BY id LIMIT 500;`\n\trows, err := s.pool.Query(ctx, sql)\n\n\tif errors.Is(err, pgx.ErrNoRows) {\n\t\treturn items, nil\n\t}\n\n\tif err != nil {\n\t\treturn nil, ErrInternal\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\titem := &types.Products{}\n\t\terr = rows.Scan(&item.ID, &item.Name, &item.Price, &item.Qty)\n\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\treturn items, nil\n}", "func (om *Sdk) AvailableProducts() ([]api.ProductInfo, error) {\n\tproducts, err := om.api.ListAvailableProducts()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn products.ProductsList, nil\n}", "func (opsmgr *OpsMgr) GetProducts() (products *Products, err error) {\n\treq, err := http.NewRequest(\"GET\", opsmgr.apiURL(\"/api/products\"), nil)\n\tif err != nil {\n\t\treturn\n\t}\n\treq.SetBasicAuth(opsmgr.Username, opsmgr.Password)\n\n\tresp, err := opsmgr.httpClient().Do(req)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer resp.Body.Close()\n\n\tproductsResp := []struct {\n\t\tName string `json:\"name\"`\n\t\tVersion string `json:\"product_version\"`\n\t}{}\n\terr = json.NewDecoder(resp.Body).Decode(&productsResp)\n\n\tproducts = &Products{}\n\tfor _, productVersion := range productsResp {\n\t\tname := productVersion.Name\n\t\tif name == \"p-bosh\" {\n\t\t\tcontinue\n\t\t}\n\t\tproduct := (*products)[name]\n\t\tif product == nil {\n\t\t\tproduct = &Product{}\n\t\t}\n\t\tproduct.Name = name\n\t\tversion, err := version.NewVersion(productVersion.Version)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Error parsing product version %s for %s product\\n\", productVersion.Version, name)\n\t\t\tproduct.RawVersions = append(product.RawVersions, productVersion.Version)\n\t\t} else {\n\t\t\tproduct.Versions = append(product.Versions, version)\n\t\t}\n\t\t(*products)[name] = product\n\t}\n\n\t// Sort the product versions so we can determine latest\n\t// TODO: sorting non-semver (e.g. p-bosh '1.6.7.0')\n\tfor _, product := range *products {\n\t\tif len(product.Versions) > 0 {\n\t\t\tsort.Sort(version.Collection(product.Versions))\n\t\t\tproduct.LatestVersion = product.Versions[len(product.Versions)-1].String()\n\t\t} else {\n\t\t\tproduct.LatestVersion = product.RawVersions[0]\n\t\t}\n\t\tfmt.Println(\"Latest version\", product.Name, product.LatestVersion)\n\t}\n\n\treturn\n}", "func (p *Products) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"[DEBUG] Handle GET products\")\n\t// fetch the products from the data storage\n\tproductList := data.GetProducts()\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// serialize the list to JSON\n\terr := data.ToJSON(productList, w)\n\tif err != nil {\n\t\thttp.Error(w, \"[ERROR] Unable to marshal json\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func GetProducts() ProductsList {\n\treturn productsList\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET products\")\n\n\t//fetch products from data store\n\tlp := data.GetProducts()\n\n\t//serialise list to JSON\n\terr := data.ToJSON(lp, rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal JSON\", http.StatusInternalServerError)\n\t}\n}", "func (s *Service) GetAllActiveProducts(ctx context.Context) ([]*types.Product, error) {\n\tproducts := []*types.Product{}\n\trowsProducts, err := s.pool.Query(ctx, `SELECT id, name, category_id, description, qty, price FROM products WHERE active = true`)\n\tif err == pgx.ErrNoRows {\n\t\tlog.Println(err)\n\t\treturn nil, ErrNotFound\n\t}\n\n\tdefer rowsProducts.Close()\n\n\tfor rowsProducts.Next() {\n\t\tproduct := &types.Product{}\n\t\tif err := rowsProducts.Scan(\n\t\t\t&product.ID, &product.Name, &product.CategoryID, &product.Description, &product.Qty, &product.Price,\n\t\t); err != nil {\n\t\t\tlog.Println(err)\n\t\t}\n\n\t\trowsPhotos, err := s.pool.Query(ctx, `SELECT name FROM photos WHERE product_id = $1`, product.ID)\n\t\tif err == pgx.ErrNoRows {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\n\t\tdefer rowsPhotos.Close()\n\n\t\tfor rowsPhotos.Next() {\n\t\t\turl := \"http://localhost:9999/images/\"\n\t\t\tphoto := &types.Photo{}\n\t\t\tif err := rowsPhotos.Scan(&photo.Name); err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t\tproduct.PhotosURL = append(product.PhotosURL, url+photo.Name)\n\t\t}\n\n\t\terr = rowsPhotos.Err()\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn products, ErrInternal\n\t\t}\n\n\t\tproducts = append(products, product)\n\t}\n\terr = rowsProducts.Err()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn products, ErrInternal\n\t}\n\n\treturn products, nil\n}", "func (s GetProductsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (o ApplicationPlanOutput) Product() pulumi.StringOutput {\n\treturn o.ApplyT(func(v ApplicationPlan) string { return v.Product }).(pulumi.StringOutput)\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET Products\")\n\tlp := data.GetProducts()\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal json\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (o AnalyticsSolutionPlanOutput) Product() pulumi.StringOutput {\n\treturn o.ApplyT(func(v AnalyticsSolutionPlan) string { return v.Product }).(pulumi.StringOutput)\n}", "func (retProduct) List(ctx context.Context, db *sqlx.DB) ([]Product, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.product.list\")\n\tdefer span.End()\n\n\tproducts := []Product{}\n\tconst q = `SELECT\n\t\t\tp.*,\n\t\t\tCOALESCE(SUM(s.quantity) ,0) AS sold,\n\t\t\tCOALESCE(SUM(s.paid), 0) AS revenue\n\t\tFROM products AS p\n\t\tLEFT JOIN sales AS s ON p.product_id = s.product_id\n\t\tGROUP BY p.product_id`\n\n\tif err := db.SelectContext(ctx, &products, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting products\")\n\t}\n\n\treturn products, nil\n}", "func (fapi *FyndiqAPI) GetProducts() (*ProductList, error) {\n\tresp, err := httpRequest(\"GET\", fapi.productsURL(RequestParams{}), nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvar result *ProductList\n\treturn result, json.Unmarshal(resp.body, &result)\n}", "func (s *service) ListProducts(ctx context.Context, r *productrpc.ListProductsRequest) (*productrpc.ListProductsResponse, error) {\n\treturn &productrpc.ListProductsResponse{Products: s.s.Products()}, nil\n}", "func (obj *Global) QTProduct(ctx context.Context) (string, error) {\n\tresult := &struct {\n\t\tReturn string `json:\"qReturn\"`\n\t}{}\n\terr := obj.RPC(ctx, \"QTProduct\", result)\n\treturn result.Return, err\n}", "func ListProducts(w http.ResponseWriter, r *http.Request) {\n\tproducts, err := repo.ListProducts(r.Context())\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, products, http.StatusOK)\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tlp := data.GetProducts()\n\trw.Header().Add(\"Content-Type\", \"application/json\")\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to convert data.\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (o LicenseOutput) Product() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.Product }).(pulumi.StringOutput)\n}", "func (o *ExportProductsUsingGETParams) WithCurrentPage(currentPage *int32) *ExportProductsUsingGETParams {\n\to.SetCurrentPage(currentPage)\n\treturn o\n}", "func (p *Products) getProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.log.Println(\"Handle GET Products\")\n\n\t// fetch the products from the datastore\n\tlp := data.GetProducts()\n\n\t// serialize the list to JSON\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal json\", http.StatusInternalServerError)\n\t}\n}", "func GetProducts(c echo.Context) error {\n\tdata, err := db.GetAllProducts()\n\tif err != nil {\n\t\treturn c.JSON(http.StatusNotFound, types.ParseStatus(\"NOT_FOUND\", err.Error()))\n\t}\n\treturn c.JSON(http.StatusOK, data)\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET Products\")\n\n\t// Fetch the products from the datastore.\n\tlp := data.GetProducts()\n\n\t// Convert (serialize) the list to JSON.\n\terr := lp.ToJSON(rw)\n\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal json\", http.StatusInternalServerError)\n\t}\n}", "func JSONPrintTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\ttabelproduct := []entities.TabelProduct{}\n\tsqlProduct := `SELECT * FROM tabelproduct;`\n\tdataList := models.ListTblProduct(Db, sqlProduct)\n\ttabelproduct = dataList\n\tDb.Close()\n\tc.JSON(http.StatusOK, tabelproduct)\n}", "func GetProducts(c *gin.Context) {\n\tvar product []Models.Product\n\terr := Models.GetAllProducts(&product)\n\tif err != nil {\n\t\tc.AbortWithStatus(http.StatusNotFound)\n\t} else {\n\t\tc.JSON(http.StatusOK, product)\n\t}\n}", "func (a *AzureInfoer) GetCurrentPrices(region string) (map[string]productinfo.Price, error) {\n\treturn nil, errors.New(\"azure prices cannot be queried on the fly\")\n}", "func (o KubernetesClusterExtensionPlanOutput) Product() pulumi.StringOutput {\n\treturn o.ApplyT(func(v KubernetesClusterExtensionPlan) string { return v.Product }).(pulumi.StringOutput)\n}", "func (pr *Product) String() string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(\"Product(\")\n\tbuilder.WriteString(fmt.Sprintf(\"id=%v\", pr.ID))\n\tbuilder.WriteString(\", versionId=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", pr.VersionId))\n\tbuilder.WriteString(\", versionName=\")\n\tbuilder.WriteString(pr.VersionName)\n\tbuilder.WriteString(\", productId=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", pr.ProductId))\n\tbuilder.WriteString(\", productName=\")\n\tbuilder.WriteString(pr.ProductName)\n\tbuilder.WriteString(\", price=\")\n\tbuilder.WriteString(fmt.Sprintf(\"%v\", pr.Price))\n\tbuilder.WriteString(\", attr=\")\n\tbuilder.WriteString(pr.Attr)\n\tbuilder.WriteString(\", productDesc=\")\n\tbuilder.WriteString(pr.ProductDesc)\n\tbuilder.WriteString(\", addtime=\")\n\tbuilder.WriteString(pr.Addtime.Format(time.ANSIC))\n\tbuilder.WriteString(\", mtime=\")\n\tbuilder.WriteString(pr.Mtime.Format(time.ANSIC))\n\tbuilder.WriteByte(')')\n\treturn builder.String()\n}", "func (w *ServerInterfaceWrapper) ListProducts(ctx echo.Context) error {\n\tvar err error\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.ListProducts(ctx)\n\treturn err\n}", "func main() {\n\n\tfmt.Print(products([]int{1, 2, 3, 4, 5}))\n}", "func (p *Base) Product() string { // 管理ページ\n\treturn \"https://admin.thebase.in/shop_admin/items/add\"\n}", "func GetProducts() ProductUseCase {\n\tclient := repository.GetPostgresSession()\n\tservices := services.NewController(client)\n\n\treturn &productUseCase{services}\n}", "func (s *ProductsService) List(ctx context.Context) (*OneTimeProducts, *http.Response, error) {\n\tu := \"2.0/product/get_products\"\n\treq, err := s.client.NewRequest(\"POST\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tproductsResponse := new(ProductsResponse)\n\tresponse, err := s.client.Do(ctx, req, productsResponse)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\n\treturn productsResponse.Response, response, nil\n}", "func (c *cloudChannelRESTClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator {\n\tit := &ProductIterator{}\n\treq = proto.Clone(req).(*channelpb.ListProductsRequest)\n\tunm := protojson.UnmarshalOptions{AllowPartial: true, DiscardUnknown: true}\n\tit.InternalFetch = func(pageSize int, pageToken string) ([]*channelpb.Product, string, error) {\n\t\tresp := &channelpb.ListProductsResponse{}\n\t\tif pageToken != \"\" {\n\t\t\treq.PageToken = pageToken\n\t\t}\n\t\tif pageSize > math.MaxInt32 {\n\t\t\treq.PageSize = math.MaxInt32\n\t\t} else if pageSize != 0 {\n\t\t\treq.PageSize = int32(pageSize)\n\t\t}\n\t\tbaseUrl, err := url.Parse(c.endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, \"\", err\n\t\t}\n\t\tbaseUrl.Path += fmt.Sprintf(\"/v1/products\")\n\n\t\tparams := url.Values{}\n\t\tparams.Add(\"$alt\", \"json;enum-encoding=int\")\n\t\tparams.Add(\"account\", fmt.Sprintf(\"%v\", req.GetAccount()))\n\t\tif req.GetLanguageCode() != \"\" {\n\t\t\tparams.Add(\"languageCode\", fmt.Sprintf(\"%v\", req.GetLanguageCode()))\n\t\t}\n\t\tif req.GetPageSize() != 0 {\n\t\t\tparams.Add(\"pageSize\", fmt.Sprintf(\"%v\", req.GetPageSize()))\n\t\t}\n\t\tif req.GetPageToken() != \"\" {\n\t\t\tparams.Add(\"pageToken\", fmt.Sprintf(\"%v\", req.GetPageToken()))\n\t\t}\n\n\t\tbaseUrl.RawQuery = params.Encode()\n\n\t\t// Build HTTP headers from client and context metadata.\n\t\thds := append(c.xGoogHeaders, \"Content-Type\", \"application/json\")\n\t\theaders := gax.BuildHeaders(ctx, hds...)\n\t\te := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {\n\t\t\tif settings.Path != \"\" {\n\t\t\t\tbaseUrl.Path = settings.Path\n\t\t\t}\n\t\t\thttpReq, err := http.NewRequest(\"GET\", baseUrl.String(), nil)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\thttpReq.Header = headers\n\n\t\t\thttpRsp, err := c.httpClient.Do(httpReq)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tdefer httpRsp.Body.Close()\n\n\t\t\tif err = googleapi.CheckResponse(httpRsp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tbuf, err := io.ReadAll(httpRsp.Body)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tif err := unm.Unmarshal(buf, resp); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\treturn nil\n\t\t}, opts...)\n\t\tif e != nil {\n\t\t\treturn nil, \"\", e\n\t\t}\n\t\tit.Response = resp\n\t\treturn resp.GetProducts(), resp.GetNextPageToken(), nil\n\t}\n\n\tfetch := func(pageSize int, pageToken string) (string, error) {\n\t\titems, nextPageToken, err := it.InternalFetch(pageSize, pageToken)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tit.items = append(it.items, items...)\n\t\treturn nextPageToken, nil\n\t}\n\n\tit.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)\n\tit.pageInfo.MaxSize = int(req.GetPageSize())\n\tit.pageInfo.Token = req.GetPageToken()\n\n\treturn it\n}", "func Print() {\n\tlog.Println(jsonFromItems(items))\n}", "func ReadProducts() {\n\tvar myProduct = make([]Product, 0)\n\tstorage.DB().Find(&myProduct)\n\tfor _, product := range myProduct {\n\t\tfmt.Printf(\"ID: %+v | Name: %+v | Price: %+v | Observations: %+v | CreatedAt: %+v | UpdatedAt: %+v | DeletedAt: %+v \\n\\n\", product.ID, product.Name, product.Price, product.Observations.String, product.CreatedAt, product.UpdatedAt, product.DeletedAt.Time)\n\t}\n}", "func (products *Products) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tproductsCollections := data.GetProducts()\n\terr := productsCollections.ToJSON(w)\n\tif err != nil {\n\t\thttp.Error(w, \"unable to marshal json\", http.StatusInternalServerError)\n\t}\n}", "func (c *Commerce) Product() string {\n\treturn c.pick(commercePrefix + \"/product_name/product\")\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func ListProductPath() string {\n\treturn \"/api/product\"\n}", "func (c *CloudChannelClient) ListProducts(ctx context.Context, req *channelpb.ListProductsRequest, opts ...gax.CallOption) *ProductIterator {\n\treturn c.internalClient.ListProducts(ctx, req, opts...)\n}", "func (p Product) String() string {\n\treturn fmt.Sprintf(\"Id = %d, Name = %s, Cost = %f, Units = %d, Category = %s\", p.Id, p.Name, p.Cost, p.Units, p.Category)\n}", "func (s *itemStack) Print() {\n\tfmt.Println(s.items)\n}", "func (o LookupAppResultOutput) ApiProducts() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v LookupAppResult) []string { return v.ApiProducts }).(pulumi.StringArrayOutput)\n}", "func GetAllAvailableProducts(db *sql.DB) []Product {\n\treturn ParseProducts(\"SELECT product_id, title, price, inventory_count FROM products_view WHERE inventory_count > 0\", db)\n}", "func (c *PAPIClient) Products(contractID string) ([]ProductSummary, error) {\n\tprods := &Products{}\n\terr := resourceRequest(c, \"GET\", papiProductsEndpoint(c.GetCredentials(), contractID), nil, prods)\n\tif err != nil {\n\t\treturn []ProductSummary{}, err\n\t}\n\treturn prods.Products.Items, err\n}", "func (h *CategoryHandler) ListProducts(ctx iris.Context) {\n\tid := ctx.Params().GetInt64Default(\"id\", 0)\n\n\t// NOTE: could add cache here too.\n\n\tq := ctx.Request().URL.Query()\n\topts := sql.ParseListOptions(q).Where(\"category_id\", id)\n\topts.Table = \"products\"\n\tif opts.OrderByColumn == \"\" {\n\t\topts.OrderByColumn = \"updated_at\"\n\t}\n\n\tvar products entity.Products\n\terr := h.service.List(ctx.Request().Context(), &products, opts)\n\tif err != nil && err != sql.ErrNoRows {\n\t\tdebugf(\"CategoryHandler.ListProducts(DB) (table=%s where=%s=%v limit=%d offset=%d): %v\",\n\t\t\topts.Table, opts.WhereColumn, opts.WhereValue, opts.Limit, opts.Offset, err)\n\n\t\twriteInternalServerError(ctx)\n\t\treturn\n\t}\n\n\tctx.JSON(products)\n}", "func (c *Commerce) ProductName() string {\n\treturn fmt.Sprintf(\"%s %s %s\", c.ProductAdjective(), c.ProductMaterial(), c.Product())\n}", "func (s Product) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (r *ProductsService) List(source string) *ProductsListCall {\n\tc := &ProductsListCall{s: r.s, opt_: make(map[string]interface{})}\n\tc.source = source\n\treturn c\n}", "func (v *Kounta) GetProducts(token string, company string, categoryID string) (KountaProducts, error) {\n\n\tu, _ := url.ParseRequestURI(baseURL)\n\tu.Path = fmt.Sprintf(categoriesProductsURL, company, categoryID)\n\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tresults := new(KountaProducts)\n\n\tfor urlStr != \"\" {\n\n\t\tresp := new(KountaProducts)\n\n\t\t*resp, _, urlStr = v.callProduct(urlStr, token)\n\n\t\t*results = append(*results, *resp...)\n\n\t\tfmt.Println(\"X-Next-Page\", urlStr, len(*results))\n\t}\n\n\treturn *results, nil\n}", "func GetAllProducts(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tvar products models.Products\n\tproducts.FindAll()\n\tmodels.SendData(w, products)\n}", "func (p *Products) ListAll(rw http.ResponseWriter, req *http.Request) {\n\tp.log.Println(\"[GET] /products\")\n\n\tlistOfProducts := data.GetProducts()\n\n\terr := data.ToJSON(listOfProducts, rw)\n\tif err != nil {\n\t\thttp.Error(rw, err.Error(), http.StatusInternalServerError)\n\t}\n}", "func (a *AzureInfoer) GetCurrentPrices(region string) (map[string]types.Price, error) {\n\treturn nil, errors.New(\"azure prices cannot be queried on the fly\")\n}", "func printCurrentSchedule() {\n\tfmt.Println(weeklySchedule)\n}", "func PrintMessages(products Products, discounts Discounts) {\n\tprintWelcomeMessage()\n\tprintCurrentProducts(products)\n\tprintDiscountProducts(discounts, products)\n}", "func (client ProductsClient) List(ctx context.Context, resourceGroup string, registrationName string) (result ProductListPage, err error) {\n\tif tracing.IsEnabled() {\n\t\tctx = tracing.StartSpan(ctx, fqdn+\"/ProductsClient.List\")\n\t\tdefer func() {\n\t\t\tsc := -1\n\t\t\tif result.pl.Response.Response != nil {\n\t\t\t\tsc = result.pl.Response.Response.StatusCode\n\t\t\t}\n\t\t\ttracing.EndSpan(ctx, sc, err)\n\t\t}()\n\t}\n\tresult.fn = client.listNextResults\n\treq, err := client.ListPreparer(ctx, resourceGroup, registrationName)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"List\", nil, \"Failure preparing request\")\n\t\treturn\n\t}\n\n\tresp, err := client.ListSender(req)\n\tif err != nil {\n\t\tresult.pl.Response = autorest.Response{Response: resp}\n\t\terr = autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"List\", resp, \"Failure sending request\")\n\t\treturn\n\t}\n\n\tresult.pl, err = client.ListResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"azurestack.ProductsClient\", \"List\", resp, \"Failure responding to request\")\n\t}\n\n\treturn\n}", "func (c *ProductsClient) List(ctx context.Context, opts *ProductsListOpts) *ResolvedProductIter {\n\titer := ResolvedProductIter{\n\t\tfirst: true,\n\t\ti: -1,\n\t}\n\n\tp := \"/products/\"\n\n\tvar q url.Values\n\tif opts != nil {\n\t\tq = make(url.Values)\n\t\tif opts.ProviderID != nil {\n\t\t\tb, err := opts.ProviderID.MarshalText()\n\t\t\tif err != nil {\n\t\t\t\treturn &iter\n\t\t\t}\n\t\t\tq.Set(\"provider_id\", string(b))\n\t\t}\n\n\t\tif opts.IncludePlans != nil {\n\t\t\tq.Set(\"include_plans\", strconv.FormatBool(*opts.IncludePlans))\n\t\t}\n\t}\n\n\tvar req *http.Request\n\treq, iter.err = c.backend.NewRequest(http.MethodGet, p, q, nil)\n\tif iter.err != nil {\n\t\treturn &iter\n\t}\n\n\t_, iter.err = c.backend.Do(ctx, req, &iter.page, func(code int) error {\n\t\tswitch code {\n\t\tcase 400, 500:\n\t\t\treturn &Error{}\n\t\tdefault:\n\t\t\treturn nil\n\t\t}\n\t})\n\treturn &iter\n}", "func (k Keeper) GetAllProduct(ctx sdk.Context) (list []types.Product) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ProductKey))\n\titerator := sdk.KVStorePrefixIterator(store, []byte{})\n\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar val types.Product\n\t\tk.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val)\n\t\tlist = append(list, val)\n\t}\n\n\treturn\n}", "func (m *ProductModel) AllProducts() ([]Product, error) {\n\tvar products []Product\n\terr := db.C(PRODUCT).Find(bson.M{}).All(&products)\n\treturn products, err\n}", "func GetAllProducts(db *sql.DB) []Product {\n\treturn ParseProducts(\"SELECT product_id, title, price, inventory_count FROM products_view\", db)\n}", "func (s Product) String() string {\n\tres := make([]string, 5)\n\tres[0] = \"ProductID: \" + reform.Inspect(s.ProductID, true)\n\tres[1] = \"PartyID: \" + reform.Inspect(s.PartyID, true)\n\tres[2] = \"CreatedAt: \" + reform.Inspect(s.CreatedAt, true)\n\tres[3] = \"Serial: \" + reform.Inspect(s.Serial, true)\n\tres[4] = \"Addr: \" + reform.Inspect(s.Addr, true)\n\treturn strings.Join(res, \", \")\n}", "func ActionProduct(w http.ResponseWriter, r *http.Request) {\n\tif !Auth(w, r) {\n\t\treturn\n\t}\n\n\tif !AllowOnlyGET(w, r) {\n\t\treturn\n\t}\n\n\tOutputJSON(w, GetProducts())\n}", "func (p *Products) List(w http.ResponseWriter, r *http.Request) {\n\tlist := []Product{}\n\n\tconst q = `SELECT * FROM products`\n\n\tif err := p.db.Select(&list, q); err != nil {\n\t\tlog.Printf(\"error: selecting products: %s\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(list)\n\tif err != nil {\n\t\tlog.Println(\"error marshalling result\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(data); err != nil {\n\t\tlog.Println(\"error writing result\", err)\n\t}\n}", "func (a *AzureInfoer) GetProducts(regionId string) ([]productinfo.VmInfo, error) {\n\tlog.Debugf(\"getting product info [region=%s]\", regionId)\n\tvar vms []productinfo.VmInfo\n\tvmSizes, err := a.vmSizesClient.List(context.TODO(), regionId)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfor _, v := range *vmSizes.Value {\n\t\tvms = append(vms, productinfo.VmInfo{\n\t\t\tType: *v.Name,\n\t\t\tCpus: float64(*v.NumberOfCores),\n\t\t\tMem: float64(*v.MemoryInMB) / 1024,\n\t\t\t// TODO: netw perf\n\t\t})\n\t}\n\n\tlog.Debugf(\"found vms: %#v\", vms)\n\treturn vms, nil\n}", "func AllProductsEndpoint(w http.ResponseWriter, r *http.Request) {\n\tproducts, err := dao.FindAllProducts()\n\tif err != nil {\n\t\trespondWithError(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\trespondWithJson(w, http.StatusOK, products)\n}", "func (s SearchProductsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func getProducts(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println()\n\tfmt.Println(\"pulling products\")\n\tfmt.Println()\n\t//Set header content tyep to application/json\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tenableCors(&w)\n\t//Init Products var as a slice Product struct\n\tproducts := []Product{}\n\t//query sent to DB\n\tquery := \"SELECT * FROM products\"\n\n\t//rows = results of the query\n\trows, err := db.Query(query)\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\treturn\n\t\t// panic(err.Error())\n\t}\n\t// if there is NOT an error do this\n\tfor rows.Next() {\n\t\t// create a new variable and set its value to our existing struct\n\t\t//Create new struct for each rown\n\t\tvar product Product\n\t\t//scan the rows and check for discrepancies and store in \"err\" so we know what the error was for\n\t\terr := rows.Scan(&product.ProductID, &product.Name, &product.Price, &product.Description, &product.Console, &product.ImgLink, &product.ImgAlt, &product.ImgSrc)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t\t// panic(err.Error())\n\t\t}\n\t\t// append the returned values to our products variable\n\t\tproducts = append(products, product)\n\t}\n\n\tjson.NewEncoder(w).Encode(products)\n}", "func GetAllProducts(rw http.ResponseWriter, r *http.Request) {\n\tproducts, err := services.GetAllProducts()\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n\terr = json.NewEncoder(rw).Encode(products)\n\n\tif err != nil {\n\t\trw.WriteHeader(500)\n\t\terrorMessage := helper.ErrorMessage(err.Error())\n\t\tjson.NewEncoder(rw).Encode(errorMessage)\n\t\treturn\n\t}\n}", "func (context *Context) Print() error {\n\t// fmt.Println(\"==> context: \", context)\n\tb, err := json.Marshal(context)\n\tif err != nil {\n\t\treturn err\n\t}\n\tos.Stdout.Write(b)\n\treturn nil\n}", "func NewProducts(logger *log.Logger) *Products {\n\treturn &Products{logger}\n}", "func (o ServiceLinkedRoleOutput) ProductName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ServiceLinkedRole) pulumi.StringOutput { return v.ProductName }).(pulumi.StringOutput)\n}", "func (e Endpoints) List(ctx context.Context) (products []io.Product, err error) {\n\trequest := ListRequest{}\n\tresponse, err := e.ListEndpoint(ctx, request)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn response.(ListResponse).Products, response.(ListResponse).Err\n}", "func (p *Products) ListAll(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET all products\")\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\tprodList, err := p.dbConnection.GetAllProducts()\n\tif err != nil {\n\t\tp.l.Println(err)\n\t}\n\terr = prodList.ToJSON(w)\n\tif err != nil {\n\t\thttp.Error(w, \"Unable to marshal json.\", http.StatusInternalServerError)\n\t}\n\n}", "func (p *ProductsDB) GetProducts(currency string) (Products, error) {\n\tif currency == \"\" {\n\t\treturn productList, nil\n\t}\n\n\trate, err := p.getRate(currency)\n\tif err != nil {\n\t\tp.log.Error(\"unable to get rate\", \"currency\", currency, \"error\", err)\n\t\treturn nil, err\n\t}\n\n\tpr := Products{}\n\tfor _, prod := range productList {\n\t\tnp := *prod\n\t\tnp.Price = math.Round(np.Price * rate * 10) / 10\n\t\tpr = append(pr, &np)\n\t}\n\treturn pr, nil\n}", "func printSubscriptions(namespace string) error {\n\t// print subscription details\n\tctx := context.TODO()\n\tsubscriptionList := eventingv1alpha1.SubscriptionList{}\n\tif err := k8sClient.List(ctx, &subscriptionList, client.InNamespace(namespace)); err != nil {\n\t\tlogf.Log.V(1).Info(\"error while getting subscription list\", \"error\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"subscriptions: %+v\\n\", subscriptionList)\n\treturn nil\n}", "func (m *Backend) Products() product.Repository {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"Products\")\n\tret0, _ := ret[0].(product.Repository)\n\treturn ret0\n}", "func (o ApplicationPlanPtrOutput) Product() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ApplicationPlan) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Product\n\t}).(pulumi.StringPtrOutput)\n}", "func (o AnalyticsSolutionPlanPtrOutput) Product() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsSolutionPlan) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Product\n\t}).(pulumi.StringPtrOutput)\n}", "func (a *App) GetProducts() ([]*model.Product, *model.AppErr) {\n\treturn a.Srv().Store.Product().GetAll()\n}", "func (s *ApplicationServer) getProductsHandler() func(*gin.Context) {\n\treturn func(c *gin.Context) {\n\t\tpaginationDetails := s.getPaginationDetails(c)\n\n\t\tproductData, err := warehouse.GetFullProductResponse(s.State.DB, paginationDetails.Limit, paginationDetails.Offset)\n\t\tif err != nil {\n\t\t\tlog.Println(err.Error())\n\t\t\tc.AbortWithStatusJSON(http.StatusInternalServerError, ApplicationServerResponse{\n\t\t\t\tMessage: infrastructure.GetMessageForHTTPStatus(http.StatusInternalServerError),\n\t\t\t\tError: err.Error(),\n\t\t\t\tUnixTimestamp: time.Now().Unix(),\n\t\t\t})\n\n\t\t\treturn\n\t\t}\n\n\t\tc.JSON(http.StatusOK, products.GetProductsHandlerResponse{\n\t\t\tData: productData.Data,\n\t\t\tSort: productData.Sort,\n\t\t})\n\t}\n}", "func (s GetProductsInput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (nos *NewOrderServiceImpl) Print(o *models.NewOrderOutput) {\n\tvar newOrderString strings.Builder\n\n\tnewOrderString.WriteString(fmt.Sprintf(\"Customer Identifier => W_ID = %d, D_ID = %d, C_ID = %d \\n\", o.Customer.WarehouseID, o.Customer.DistrictID, o.Customer.CustomerID))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Customer Info => Last Name: %s , Credit: %s , Discount: %0.6f \\n\", o.Customer.LastName, o.Customer.Credit, o.Customer.Discount))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Order Details: O_ID = %d , O_ENTRY_D = %s \\n\", o.OrderID, o.OrderTimestamp))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Total Unique Items: %d \\n\", o.UniqueItems))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Total Amount: %.2f \\n\", o.TotalOrderAmount))\n\n\tnewOrderString.WriteString(fmt.Sprintf(\" # \\t ID \\t Name (Supplier, Qty, Amount, Stock) \\n\"))\n\tidx := 1\n\tfor key, value := range o.OrderLineItems {\n\t\tnewOrderString.WriteString(fmt.Sprintf(\" %02d \\t %d \\t %s (%d, %d, %.2f, %d) \\n\",\n\t\t\tidx,\n\t\t\tkey,\n\t\t\tvalue.Name,\n\t\t\tvalue.SupplierWarehouseID,\n\t\t\tvalue.Quantity,\n\t\t\tvalue.Price*float64(value.Quantity),\n\t\t\tvalue.FinalStock,\n\t\t))\n\t\tidx++\n\t}\n\n\tfmt.Println(newOrderString.String())\n}", "func GetProducts() (types.Products, error) {\n\n\tdb := Load(\"products\")\n\n\tbn, _ := json.Marshal(db.From(\"products\").Get())\n\n\tproducts := types.Products{}\n\n\tjson.Unmarshal(bn, &products)\n\n\treturn products, nil\n}" ]
[ "0.65584576", "0.62532926", "0.5745887", "0.57454187", "0.5673429", "0.56686604", "0.56188077", "0.5616091", "0.56135803", "0.5601323", "0.55943567", "0.55834025", "0.55834025", "0.55834025", "0.55834025", "0.55590945", "0.5546655", "0.5545198", "0.55402243", "0.55227035", "0.5521641", "0.5510694", "0.54965657", "0.54914325", "0.5478968", "0.5457369", "0.5447059", "0.54165745", "0.5409387", "0.54084015", "0.54033846", "0.539197", "0.5391238", "0.53904", "0.538305", "0.5373456", "0.5358745", "0.535022", "0.53451544", "0.5339522", "0.5323662", "0.5315308", "0.53096217", "0.5281038", "0.5274152", "0.5267117", "0.52591974", "0.5255602", "0.5232958", "0.5229942", "0.5221802", "0.5213743", "0.5210845", "0.5210845", "0.5210845", "0.52021205", "0.52012515", "0.5194846", "0.5183563", "0.5173473", "0.5165051", "0.5152194", "0.5149019", "0.51380074", "0.51379794", "0.5134615", "0.51253897", "0.51145315", "0.5107569", "0.5102206", "0.50818175", "0.5067952", "0.5064529", "0.5059062", "0.5044013", "0.50334036", "0.5028949", "0.50280654", "0.5022377", "0.50171924", "0.5013787", "0.5012911", "0.5008413", "0.50040036", "0.5003042", "0.49903628", "0.49873853", "0.49827227", "0.49803355", "0.49798462", "0.49790812", "0.4974956", "0.49709684", "0.49694467", "0.49508405", "0.49491978", "0.49340844", "0.49337667", "0.4928044", "0.49279302" ]
0.8942465
0
printDiscountProducts will print the current list of products and their prices
func printDiscountProducts(discounts Discounts, products Products) { currentDiscounts := ` =============================== = Here is a list of = = our current discounts = =============================== ` fmt.Println(currentDiscounts) for _, discount := range discounts { product := findProduct(products, discount.Code) fmt.Printf("%v Discount offer: %v \n\n", product.Name, discount.Description) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func printCurrentProducts(products Products) {\n\tcurrentProducts :=\n\t\t`\n===============================\n= Here is a list of =\n= our current products =\n===============================\n\t\t`\n\tfmt.Println(currentProducts)\n\tfor _, product := range products {\n\t\tfmt.Printf(\"Product: %v \\n\", product.Name)\n\t\tfmt.Printf(\"Price: £%.2f \\n\\n\", product.Price)\n\t}\n}", "func (prod *Product) printData() {\n\tfmt.Printf(\"ID: %v\\n\", prod.id)\n\tfmt.Printf(\"Title: %v\\n\", prod.title)\n\tfmt.Printf(\"Description: %v\\n\", prod.description)\n\tfmt.Printf(\"Price: $%.2f\\n\", prod.price)\n}", "func PrintMessages(products Products, discounts Discounts) {\n\tprintWelcomeMessage()\n\tprintCurrentProducts(products)\n\tprintDiscountProducts(discounts, products)\n}", "func printOrderReceipt(orderNo int, orderSlice []order.OrderItem, totalCost float64) {\r\n\r\n\tprintDividerLine()\r\n\tfmt.Println(\"* RECEIPT *\")\r\n\tfmt.Println()\r\n\r\n\tfmt.Println(\"Order No: \", orderNo)\r\n\tfmt.Println()\r\n\r\n\tpizzaTotal := 0.0\r\n\r\n\tfor _, v := range orderSlice {\r\n\t\tpizzaOrder, _ := pizzaList.SearchPizza(v.PizzaNo)\r\n\t\tpizzaTotal = float64(v.OrderQty) * pizzaOrder.PizzaPrice\r\n\r\n\t\tfmt.Printf(\"%d x %s\\t$%.2f\\n\", v.OrderQty, pizzaOrder.PizzaName, pizzaTotal)\r\n\t}\r\n\r\n\tfmt.Println(\"\\t\\t\\t--------\")\r\n\tfmt.Printf(\"TOTAL PAYMENT\\t\\t$%.2f\\n\", totalCost)\r\n\tfmt.Println(\"\\t\\t\\t--------\")\r\n}", "func (retProduct) List(ctx context.Context, db *sqlx.DB) ([]Product, error) {\n\tctx, span := global.Tracer(\"service\").Start(ctx, \"internal.data.retrieve.product.list\")\n\tdefer span.End()\n\n\tproducts := []Product{}\n\tconst q = `SELECT\n\t\t\tp.*,\n\t\t\tCOALESCE(SUM(s.quantity) ,0) AS sold,\n\t\t\tCOALESCE(SUM(s.paid), 0) AS revenue\n\t\tFROM products AS p\n\t\tLEFT JOIN sales AS s ON p.product_id = s.product_id\n\t\tGROUP BY p.product_id`\n\n\tif err := db.SelectContext(ctx, &products, q); err != nil {\n\t\treturn nil, errors.Wrap(err, \"selecting products\")\n\t}\n\n\treturn products, nil\n}", "func PrintLicenseList() error {\n\tkeys, err := GetLicenseKeys()\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tprintln(\"key : id : name\")\n\tfor _, key := range keys {\n\t\tfmt.Printf(\"%s : %s : %s\\n\", key.Key, key.SpdxID, key.Name)\n\t}\n\treturn nil\n}", "func printList(licenses []License) {\n\tsort.Sort(ByLicenseKey(licenses))\n\n\tfmt.Print(\"Available licenses:\\n\\n\")\n\tfor _, l := range licenses {\n\t\tfmt.Printf(\"%s%-14s(%s)\\n\", indent, l.Key, l.Name)\n\t}\n\tfmt.Println()\n}", "func (nos *NewOrderServiceImpl) Print(o *models.NewOrderOutput) {\n\tvar newOrderString strings.Builder\n\n\tnewOrderString.WriteString(fmt.Sprintf(\"Customer Identifier => W_ID = %d, D_ID = %d, C_ID = %d \\n\", o.Customer.WarehouseID, o.Customer.DistrictID, o.Customer.CustomerID))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Customer Info => Last Name: %s , Credit: %s , Discount: %0.6f \\n\", o.Customer.LastName, o.Customer.Credit, o.Customer.Discount))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Order Details: O_ID = %d , O_ENTRY_D = %s \\n\", o.OrderID, o.OrderTimestamp))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Total Unique Items: %d \\n\", o.UniqueItems))\n\tnewOrderString.WriteString(fmt.Sprintf(\"Total Amount: %.2f \\n\", o.TotalOrderAmount))\n\n\tnewOrderString.WriteString(fmt.Sprintf(\" # \\t ID \\t Name (Supplier, Qty, Amount, Stock) \\n\"))\n\tidx := 1\n\tfor key, value := range o.OrderLineItems {\n\t\tnewOrderString.WriteString(fmt.Sprintf(\" %02d \\t %d \\t %s (%d, %d, %.2f, %d) \\n\",\n\t\t\tidx,\n\t\t\tkey,\n\t\t\tvalue.Name,\n\t\t\tvalue.SupplierWarehouseID,\n\t\t\tvalue.Quantity,\n\t\t\tvalue.Price*float64(value.Quantity),\n\t\t\tvalue.FinalStock,\n\t\t))\n\t\tidx++\n\t}\n\n\tfmt.Println(newOrderString.String())\n}", "func (p *ProductDlv) GetProducts(c context.Context) ([]entity.Product, error) {\n\tvar res []entity.Product\n\tqs := map[string]string{}\n\n\tactive := qs[\"active\"]\n\tfmt.Println(active)\n\n\tcreatedAt := qs[\"created_at\"]\n\tfmt.Println(createdAt)\n\n\tdiscount := qs[\"discount\"]\n\tfmt.Println(discount)\n\n\tid := qs[\"id\"]\n\tfmt.Println(id)\n\n\tname := qs[\"name\"]\n\tfmt.Println(name)\n\n\tprice := qs[\"price\"]\n\tfmt.Println(price)\n\n\tstatus := qs[\"status\"]\n\tfmt.Println(status)\n\n\treturn res, nil\n}", "func GetPrices(tx db.Tx, w http.ResponseWriter, r *http.Request) {\n\tvar (\n\t\tsource model.OrderSource\n\t\tsession *model.Session\n\t\tproductIDs []string\n\t\tcoupon string\n\t\tcouponMatch bool\n\t\tpdata []*getPricesData\n\t\tproduct *model.Product\n\t\tmasterSKU *model.SKU\n\t\tjw json.Writer\n\t)\n\t// Get the request source and authorization.\n\tswitch source = model.OrderSource(r.FormValue(\"source\")); source {\n\tcase \"\":\n\t\tsource = model.OrderFromPublic\n\tcase model.OrderFromPublic:\n\t\t// no-op\n\tcase model.OrderFromMembers:\n\t\tif session = auth.GetSessionMembersAuth(tx, w, r, r.FormValue(\"auth\")); session == nil {\n\t\t\treturn\n\t\t}\n\tdefault:\n\t\tapi.BadRequestError(tx, w, \"invalid source\")\n\t\treturn\n\t}\n\t// Read the request details from the request.\n\tproductIDs = r.Form[\"p\"]\n\tif coupon = r.FormValue(\"coupon\"); coupon == \"\" {\n\t\tcouponMatch = true\n\t}\n\t// Look up the prices for each product.\n\tfor _, pid := range productIDs {\n\t\tvar (\n\t\t\tsku *model.SKU\n\t\t\tpd getPricesData\n\t\t)\n\t\t// Get the product. Skip nonexistent ones.\n\t\tif product = tx.FetchProduct(model.ProductID(pid)); product == nil {\n\t\t\tcontinue\n\t\t}\n\t\tpd.id = product.ID\n\t\tpd.name = product.ShortName\n\t\tpd.options = product.Options\n\t\t// Find the best SKU for this product.\n\t\tfor _, s := range product.SKUs {\n\t\t\tif !api.MatchingSKU(s, coupon, source, true) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif s.Coupon == coupon {\n\t\t\t\tcouponMatch = true\n\t\t\t}\n\t\t\tsku = api.BetterSKU(s, sku)\n\t\t}\n\t\tif sku == nil {\n\t\t\t// No applicable SKUs; ignore product.\n\t\t\tcontinue\n\t\t}\n\t\t// Generate the product data to return.\n\t\tif !api.ProductHasCapacity(tx, product) {\n\t\t\tpd.message = \"This event is sold out.\"\n\t\t} else if pd.message = noSalesMessage(sku); pd.message == \"\" {\n\t\t\tpd.price = sku.Price\n\t\t}\n\t\tpdata = append(pdata, &pd)\n\t\t// The masterSKU determines the message to be shown in lieu of\n\t\t// the purchase button if none of the products are available for\n\t\t// sale.\n\t\tmasterSKU = api.BetterSKU(sku, masterSKU)\n\t}\n\tapi.Commit(tx)\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\tjw = json.NewWriter(w)\n\tif len(pdata) == 0 {\n\t\t// No products available for sale, or even with messages to\n\t\t// display, so we return a null.\n\t\tjw.Null()\n\t} else if message := noSalesMessage(masterSKU); message != \"\" {\n\t\t// No products available for sale, but we do have a message to\n\t\t// display.\n\t\tjw.String(message)\n\t} else {\n\t\t// Return the product data.\n\t\temitGetPrices(jw, session, couponMatch, pdata)\n\t}\n\tjw.Close()\n}", "func (l Slist) Print() {\n\ts := l.listToSlice()\n\tfmt.Printf(\"%v\\n\", s)\n}", "func (c productController) list(ctx *routing.Context) error {\n\n\titems, err := c.Service.List(ctx.Request.Context())\n\tif err != nil {\n\t\tif err == apperror.ErrNotFound {\n\t\t\tc.Logger.With(ctx.Request.Context()).Info(err)\n\t\t\treturn errorshandler.NotFound(\"\")\n\t\t}\n\t\tc.Logger.With(ctx.Request.Context()).Error(err)\n\t\treturn errorshandler.InternalServerError(\"\")\n\t}\n\tctx.Response.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\treturn ctx.Write(items)\n}", "func (ps productsService) ListProducts(ctx context.Context, offset, limit int) (ProductPage, error) {\n\treturn ps.products.GetProducts(ctx, offset, limit)\n}", "func ViewAllProducts(c *gin.Context) {\n\tvar prod []Products\n\tdb := DbConn()\n\terr := db.Find(&prod).Error\n\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tc.JSON(http.StatusServiceUnavailable, err)\n\t}\n\n\tc.JSON(http.StatusOK, prod)\n}", "func (p *Porter) PrintInstallations(ctx context.Context, opts ListOptions) error {\n\tdisplayInstallations, err := p.ListInstallations(ctx, opts)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch opts.Format {\n\tcase printer.FormatJson:\n\t\treturn printer.PrintJson(p.Out, displayInstallations)\n\tcase printer.FormatYaml:\n\t\treturn printer.PrintYaml(p.Out, displayInstallations)\n\tcase printer.FormatPlaintext:\n\t\t// have every row use the same \"now\" starting ... NOW!\n\t\tnow := time.Now()\n\t\ttp := dtprinter.DateTimePrinter{\n\t\t\tNow: func() time.Time { return now },\n\t\t}\n\n\t\trow :=\n\t\t\tfunc(v interface{}) []string {\n\t\t\t\tcl, ok := v.(DisplayInstallation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn []string{cl.Namespace, cl.Name, cl.Status.BundleVersion, cl.DisplayInstallationState, cl.DisplayInstallationStatus, tp.Format(cl.Status.Modified)}\n\t\t\t}\n\t\treturn printer.PrintTable(p.Out, displayInstallations, row,\n\t\t\t\"NAMESPACE\", \"NAME\", \"VERSION\", \"STATE\", \"STATUS\", \"MODIFIED\")\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid format: %s\", opts.Format)\n\t}\n}", "func (s *itemStack) Print() {\n\tfmt.Println(s.items)\n}", "func (vs *Vulnerabilities) Print() {\n\tfor _, v := range *vs {\n\t\tv.PrintPackageNameVersion()\n\t}\n}", "func (ph *Handler) ListProduct(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"App : GET /app/product API hit!\")\n\treq := ListProductRequest{\n\t\tLimit: DefaultListProductLimit,\n\t\tOffset: DefaultOffset,\n\t}\n\trequest, err := validateListProductRequest(&req, r)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 400, utils.ValidationErrorCode, err.Error())\n\t\treturn\n\t}\n\tproducts, err := ph.ps.ListProduct(r.Context(), request)\n\tif err != nil {\n\t\tlog.Println(\"Error : \", err.Error())\n\t\tutils.Fail(w, 500, utils.DatabaseErrorCode, err.Error())\n\t\treturn\n\t}\n\tlog.Println(\"App : products listed!\")\n\tutils.Send(w, 200, products)\n}", "func (pd ActualManager) GetProductsWithDiscount(filters ...products.Filter) ([]Product, error) {\n\tpp, err := pd.products.Find(filters...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn pd.discountApplier.ApplyToList(pp), nil\n}", "func (n money) print() {\n\tfmt.Printf(\"%.2f\", n)\n}", "func (o LicenseOutput) Product() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *License) pulumi.StringOutput { return v.Product }).(pulumi.StringOutput)\n}", "func (*ProductsListResponse_Discount) Descriptor() ([]byte, []int) {\n\treturn file_protobuf_proto_productslist_products_list_proto_rawDescGZIP(), []int{1, 0}\n}", "func main() {\n\n\tfmt.Print(products([]int{1, 2, 3, 4, 5}))\n}", "func ListDrinks(db *sql.DB, counter int) {\n\tindex, name, stock, brand := GetDrinks(db)\n\n\tif counter == 0 {\n\t\tfmt.Println(\"Welcome to the \", brand, \"vending machine!\")\n\t}\n\n\tfor i := range stock {\n\t\tif stock[i] > 0 {\n\t\t\tfmt.Println(\"[\" + index[i] + \"] \" + name[i])\n\t\t} else {\n\t\t\tfmt.Println(\"[\" + index[i] + \"] empty\")\n\t\t}\n\t}\n}", "func (db database) list(w http.ResponseWriter, req *http.Request) {\n\tfor item, price := range db {\n\t\tfmt.Fprintf(w, \"%s: %s\\n\", item, price)\n\t}\n}", "func (db database) list(w http.ResponseWriter, req *http.Request) {\n\tfor item, price := range db {\n\t\tfmt.Fprintf(w, \"%s: %s\\n\", item, price)\n\t}\n}", "func (d database) list(w http.ResponseWriter, r *http.Request) {\n\tfor item, price := range d {\n\t\tfmt.Fprintf(w, \"item: %s, price: %s\\n\", item, price)\n\t}\n}", "func (d deck) print() {\n\tfor _, card := range d {\n\t\tfmt.Println(card)\n\t}\n}", "func ReadProducts() {\n\tvar myProduct = make([]Product, 0)\n\tstorage.DB().Find(&myProduct)\n\tfor _, product := range myProduct {\n\t\tfmt.Printf(\"ID: %+v | Name: %+v | Price: %+v | Observations: %+v | CreatedAt: %+v | UpdatedAt: %+v | DeletedAt: %+v \\n\\n\", product.ID, product.Name, product.Price, product.Observations.String, product.CreatedAt, product.UpdatedAt, product.DeletedAt.Time)\n\t}\n}", "func (d deck) print() {\n\t// iterate over cards\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func Print() {\n\tlog.Println(jsonFromItems(items))\n}", "func (l *LinkedList) Display() {\n\tif l.count == 0 {\n\t\tfmt.Println(\"No items in the stock\")\n\t} else {\n\t\tfmt.Println(\"..........The stock report is......\")\n\t\tcurrentPost := l.head\n\t\tfor currentPost != nil {\n\t\t\tfmt.Println(\"\\n-----------------------------------------\\n\")\n\t\t\tfmt.Printf(\"\\nName : %s\", currentPost.Name)\n\t\t\tfmt.Printf(\"\\nShare_Price : %d\", currentPost.Share_price)\n\t\t\tfmt.Printf(\"\\nShares : %d\", currentPost.Number_of_shares)\n\t\t\tfmt.Println(\"\\n----------------------------------------\\n\")\n\t\t\tcurrentPost = currentPost.next\n\t\t}\n\t}\n}", "func (b *Blockchain) Print() {\n\tspew.Dump(b.Blocks)\n}", "func (d deck) print () {\n\tfor i, card := range d {\n\t\tfmt.Println(i, \"card:\", card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i+1, card)\n\t}\n\tfmt.Println(\"----------------\")\n}", "func ListProducts(w http.ResponseWriter, r *http.Request) {\n\tproducts, err := repo.ListProducts(r.Context())\n\tif err != nil {\n\t\trespondWithError(w, err)\n\t\treturn\n\t}\n\n\trespondWithJSON(w, products, http.StatusOK)\n}", "func (p *Products) List(w http.ResponseWriter, r *http.Request) {\n\tlist := []Product{}\n\n\tconst q = `SELECT * FROM products`\n\n\tif err := p.db.Select(&list, q); err != nil {\n\t\tlog.Printf(\"error: selecting products: %s\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tdata, err := json.Marshal(list)\n\tif err != nil {\n\t\tlog.Println(\"error marshalling result\", err)\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Header().Set(\"Content-Type\", \"application/json; charset=utf-8\")\n\tw.WriteHeader(http.StatusOK)\n\tif _, err := w.Write(data); err != nil {\n\t\tlog.Println(\"error writing result\", err)\n\t}\n}", "func (d deck) print() {\n\tfor index, card := range d {\n\t\tfmt.Println(index, card)\n\t}\n}", "func (d deck) print() {\n\t// loop declaration to iterate over slice till its range\n\tfor index, cards := range d {\n\t\tfmt.Println(index, cards)\n\t}\n}", "func PrintOperations(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Add(\"Content-type\", \"application/pdf\")\n\toperationBarcodes := []string{\n\t\t\"palet sursa\",\n\t\t\"palet dest1\",\n\t\t\"palet dest2\",\n\t\t\"palet dest3\",\n\t\t\"palet dest4\",\n\t\t\"print sursa\",\n\t\t\"print dest1\",\n\t\t\"print dest2\",\n\t\t\"print dest3\",\n\t\t\"print dest4\",\n\t\t\"palet nou\"}\n\tpdf.GenerateSimplePDF(operationBarcodes, \"Operatii paleti\", httputil.NewChunkedWriter(w))\n}", "func (d deck) print() {\n\tfor i, v := range d {\n\t\tfmt.Println(i, v)\n\t}\n}", "func (s *Selector) Print() string {\n\tvar reqs []string\n\tfor ii := range s.Requirements {\n\t\treqs = append(reqs, s.Requirements[ii].Print())\n\t}\n\treturn strings.Join(reqs, \",\")\n}", "func (d deck) print() {\n\n\t// assign index and value of every element in cards slice to the variables, idx and card.\n\tfor idx, card := range d {\n\t\tfmt.Println(idx, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (d deck) print() {\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func (s GetProductsOutput) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (p Product) String() string {\n\treturn fmt.Sprintf(\"Id = %d, Name = %s, Cost = %f, Units = %d, Category = %s\", p.Id, p.Name, p.Cost, p.Units, p.Category)\n}", "func (p *Porter) PrintInstallations(opts ListOptions) error {\n\tdisplayInstallations, err := p.ListInstallations()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch opts.Format {\n\tcase printer.FormatJson:\n\t\treturn printer.PrintJson(p.Out, displayInstallations)\n\tcase printer.FormatYaml:\n\t\treturn printer.PrintYaml(p.Out, displayInstallations)\n\tcase printer.FormatTable:\n\t\t// have every row use the same \"now\" starting ... NOW!\n\t\tnow := time.Now()\n\t\ttp := dtprinter.DateTimePrinter{\n\t\t\tNow: func() time.Time { return now },\n\t\t}\n\n\t\trow :=\n\t\t\tfunc(v interface{}) []interface{} {\n\t\t\t\tcl, ok := v.(DisplayInstallation)\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t\treturn []interface{}{cl.Name, tp.Format(cl.Created), tp.Format(cl.Modified), cl.Action, cl.Status}\n\t\t\t}\n\t\treturn printer.PrintTable(p.Out, displayInstallations, row,\n\t\t\t\"NAME\", \"CREATED\", \"MODIFIED\", \"LAST ACTION\", \"LAST STATUS\")\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid format: %s\", opts.Format)\n\t}\n}", "func PrintData(ticker Ticker) {\n\t// Just print it out for now\n\tfor _, coin := range ticker.Coins {\n\t\tfmt.Println(\"Symbol: '\"+coin.Symbol+\"', Name: '\"+\n\t\t\tcoin.Name+\"', Price Bitcoin: '\",\n\t\t\tcoin.PriceBTC, \"', Price EUR: '\", coin.PriceEUR, \"'\")\n\t}\n}", "func discountInfo(d *storage.Discount) string {\n\tif d == nil {\n\t\treturn \",,,,,\"\n\t}\n\tresult := fmt.Sprintf(\"%.2f,\", d.Total) + getFloatValues(d.PrevContribution, d.CeilRetention, d.IncomeTax) + getMapTotal(d.Others)\n\treturn result\n}", "func (p *Products) getProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.log.Println(\"Handle GET Products\")\n\n\t// fetch the products from the datastore\n\tlp := data.GetProducts()\n\n\t// serialize the list to JSON\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal json\", http.StatusInternalServerError)\n\t}\n}", "func GetProducts(c *fiber.Ctx) error {\n\tdb := database.Connection()\n\treturn models.GetProducts(db, c)\n}", "func (s *ProductsService) List(ctx context.Context) (*OneTimeProducts, *http.Response, error) {\n\tu := \"2.0/product/get_products\"\n\treq, err := s.client.NewRequest(\"POST\", u, nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tproductsResponse := new(ProductsResponse)\n\tresponse, err := s.client.Do(ctx, req, productsResponse)\n\tif err != nil {\n\t\treturn nil, response, err\n\t}\n\n\treturn productsResponse.Response, response, nil\n}", "func (w *ServerInterfaceWrapper) ListProducts(ctx echo.Context) error {\n\tvar err error\n\n\t// Invoke the callback with all the unmarshalled arguments\n\terr = w.Handler.ListProducts(ctx)\n\treturn err\n}", "func (ps PlanSlice) Print() {\n\tfor _, p := range ps {\n\t\tconsole.Println(p.NameVersion(), human.ByteSize(p.Size))\n\t}\n\tconsole.Flush()\n}", "func (s *service) ListProducts(ctx context.Context, r *productrpc.ListProductsRequest) (*productrpc.ListProductsResponse, error) {\n\treturn &productrpc.ListProductsResponse{Products: s.s.Products()}, nil\n}", "func scrapeProducts(pChan chan *product.Product, pSelector *goquery.Selection) {\n\tvar wg sync.WaitGroup\n\twg.Add(pSelector.Size())\n\tpSelector.Each(func(i int, s *goquery.Selection) {\n\t\ttitle := s.Find(\"h3\")\n\t\turl, _ := title.Find(\"a\").Attr(\"href\")\n\t\tprice := s.Find(\".pricePerUnit\").Text()\n\t\tgo func(pChan chan *product.Product) {\n\t\t\tdefer wg.Done()\n\t\t\tpChan <- product.New(title.Text(), price, url)\n\n\t\t}(pChan)\n\t})\n\twg.Wait()\n}", "func (p *Products) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tlp := data.GetProducts()\n\n\terr := data.ToJSON(lp, w)\n\n\tif err != nil {\n\t\thttp.Error(w, \"Unable to marshal json\", http.StatusInternalServerError)\n\t}\n\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET products\")\n\n\t//fetch products from data store\n\tlp := data.GetProducts()\n\n\t//serialise list to JSON\n\terr := data.ToJSON(lp, rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal JSON\", http.StatusInternalServerError)\n\t}\n}", "func (k Keeper) GetAllProduct(ctx sdk.Context) (list []types.Product) {\n\tstore := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.ProductKey))\n\titerator := sdk.KVStorePrefixIterator(store, []byte{})\n\n\tdefer iterator.Close()\n\n\tfor ; iterator.Valid(); iterator.Next() {\n\t\tvar val types.Product\n\t\tk.cdc.MustUnmarshalBinaryBare(iterator.Value(), &val)\n\t\tlist = append(list, val)\n\t}\n\n\treturn\n}", "func GetProducts() Products {\n\treturn productsList\n}", "func ListProductCustomers(c *gin.Context) {\n\tdb := c.MustGet(\"db\").(*mgo.Database)\n\tvar product models.Product\n\tvar customers []models.Customer\n\tvar customer models.Customer\n\n\terr := db.C(models.CollectionProduct).\n\t\tFindId(bson.ObjectIdHex(c.Param(\"_id\"))).\n\t\tOne(&product)\n\n\tif err != nil {\n\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\"status\": 500,\n\t\t\t\"msg\": err.Error(),\n\t\t})\n\t\treturn\n\t}\n\n\tfor _, id := range product.CustomerID {\n\t\terr := db.C(models.CollectionCustomer).\n\t\t\tFindId(id).\n\t\t\tOne(&customer)\n\n\t\tif err != nil {\n\t\t\tc.JSON(http.StatusInternalServerError, gin.H{\n\t\t\t\t\"status\": 500,\n\t\t\t\t\"msg\": err.Error(),\n\t\t\t})\n\t\t\treturn\n\t\t} else {\n\t\t\tcustomers = append(customers, customer)\n\t\t}\n\t}\n\n\tc.JSON(http.StatusOK, gin.H{\n\t\t\"status\": 200,\n\t\t\"msg\": \"Success\",\n\t\t\"data\": customers,\n\t})\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func GetProducts() Products {\n\treturn productList\n}", "func (p *Base) Product() string { // 管理ページ\n\treturn \"https://admin.thebase.in/shop_admin/items/add\"\n}", "func (p *Products) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"[DEBUG] Handle GET products\")\n\t// fetch the products from the data storage\n\tproductList := data.GetProducts()\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\t// serialize the list to JSON\n\terr := data.ToJSON(productList, w)\n\tif err != nil {\n\t\thttp.Error(w, \"[ERROR] Unable to marshal json\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tp.l.Println(\"Handle GET Products\")\n\tlp := data.GetProducts()\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to marshal json\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func NewProducts(l *log.Logger) *Products {\n\treturn &Products{l}\n}", "func printSubscriptions(namespace string) error {\n\t// print subscription details\n\tctx := context.TODO()\n\tsubscriptionList := eventingv1alpha1.SubscriptionList{}\n\tif err := k8sClient.List(ctx, &subscriptionList, client.InNamespace(namespace)); err != nil {\n\t\tlogf.Log.V(1).Info(\"error while getting subscription list\", \"error\", err)\n\t\treturn err\n\t}\n\tfmt.Printf(\"subscriptions: %+v\\n\", subscriptionList)\n\treturn nil\n}", "func GetProducts() ProductsList {\n\treturn productsList\n}", "func (vector *Vector) PrintVector() {\n\tfor i := 0; i < len(*vector); i++ {\n\t\tfmt.Println(\"vector[\", i, \"] = \", (*vector)[i])\n\t}\n}", "func (d deck) print() { //notice the receiver (d deck), variable d of type deck, d is similar to this. By convention the variable receiver\n\tfor i, card := range d {\n\t\tfmt.Println(i, card)\n\t}\n}", "func GetAllProducts(w http.ResponseWriter, r *http.Request, p httprouter.Params) {\n\tvar products models.Products\n\tproducts.FindAll()\n\tmodels.SendData(w, products)\n}", "func (list linkedList) printList() {\n\tcurrent := list.head\n\n\tfmt.Printf(\"%v -> \", current.data)\n\n\tfor current.next != list.head {\n\t\tcurrent = current.next\n\t\tfmt.Printf(\"%v -> \", current.data)\n\t}\n\n\tfmt.Println()\n}", "func JSONPrintTblProduct(c *gin.Context) {\n\tDb, err := config.DbConnect()\n\tif err != nil {\n\t\tpanic(\"Not Connect database\")\n\t}\n\ttabelproduct := []entities.TabelProduct{}\n\tsqlProduct := `SELECT * FROM tabelproduct;`\n\tdataList := models.ListTblProduct(Db, sqlProduct)\n\ttabelproduct = dataList\n\tDb.Close()\n\tc.JSON(http.StatusOK, tabelproduct)\n}", "func (s *Subscriber) ApplyDiscount() {\n\ts.rate = 4.99\n}", "func (di pdfDocInfo) print() {\n\tfmt.Printf(\"Filename: %s\\n\", di.Filename)\n\tfmt.Printf(\" Pages: %d\\n\", di.NumPages)\n\tfmt.Printf(\" Title: %s\\n\", di.Title)\n\tfmt.Printf(\" Author: %s\\n\", di.Author)\n\tfmt.Printf(\" Subject: %s\\n\", di.Subject)\n\tfmt.Printf(\" Keywords: %s\\n\", di.Keywords)\n\tfmt.Printf(\" Creator: %s\\n\", di.Creator)\n\tfmt.Printf(\" Producer: %s\\n\", di.Producer)\n\tfmt.Printf(\" CreationDate: %s\\n\", di.CreationDate)\n\tfmt.Printf(\" ModDate: %s\\n\", di.ModDate)\n\tfmt.Printf(\" Trapped: %s\\n\", di.Trapped)\n\n\tif di.CustomInfo != nil {\n\t\tfor k, v := range di.CustomInfo {\n\t\t\tfmt.Printf(\" %s: %s\\n\", k, v)\n\t\t}\n\t}\n}", "func (al *LinkedList) PrintItems() {\n\thead := al.head\n\t\n\tfor head != nil {\n\t\tfmt.Println(head.Item)\n\t\thead = head.Next\n\t}\n}", "func PrintResults(i []ResultsGet) {\n\tvar isslice bool\n\tif len(i) != 0 {\n\t\tisslice = true\n\t} else {\n\t\tfmt.Printf(\"%v\\n\", i)\n\t}\n\n\tif isslice == true {\n\t\tfor _, b := range i {\n\t\t\tfmt.Printf(\"\\tID: %v\\n\", b.ID)\n\t\t\tif b.Name != \"\" {\n\t\t\t\tfmt.Printf(\"\\tName: %v\\n\", b.Name)\n\t\t\t}\n\t\t\tif b.Status != \"\" {\n\t\t\t\tfmt.Printf(\"\\tStatus: %v\\n\", b.Status)\n\t\t\t}\n\t\t\tif b.ExpiresAt != \"\" {\n\t\t\t\tfmt.Printf(\"\\tExpires at: %v\\n\", b.ExpiresAt)\n\t\t\t}\n\t\t\tif b.Regcode != \"\" {\n\t\t\t\tfmt.Printf(\"\\tRegistration Code: %v\\n\", b.Regcode)\n\t\t\t}\n\t\t\tif len(b.Productclasses) != 0 {\n\t\t\t\tfmt.Printf(\"\\tProduct Class: %#v\\n\", b.Productclasses)\n\t\t\t}\n\t\t\tif b.SystemsCount != 0 {\n\t\t\t\tfmt.Printf(\"\\tSystem Count: %v\\n\", b.SystemsCount)\n\t\t\t}\n\t\t\tif b.VirtualSystemsCount != 0 {\n\t\t\t\tfmt.Printf(\"\\tVirtual Count: %v\\n\", b.VirtualSystemsCount)\n\t\t\t}\n\t\t\tif b.Identifier != \"\" {\n\t\t\t\tfmt.Printf(\"\\tIdentifier: %v\\n\", b.Identifier)\n\t\t\t}\n\t\t\tif b.Version != \"\" {\n\t\t\t\tfmt.Printf(\"\\tVersion: %v\\n\", b.Version)\n\t\t\t}\n\t\t\tif b.Login != \"\" {\n\t\t\t\tfmt.Printf(\"\\tLogin: %v\\n\", b.Login)\n\t\t\t}\n\t\t\tif b.Password != \"\" {\n\t\t\t\tfmt.Printf(\"\\tPassword: %v\\n\", b.Password)\n\t\t\t}\n\t\t\tif b.LastSeenAt != \"\" {\n\t\t\t\tfmt.Printf(\"\\tLast see at: %v\\n\", b.LastSeenAt)\n\t\t\t}\n\n\t\t\tif b.DistroTarget != \"\" {\n\t\t\t\tfmt.Printf(\"\\tDistro Target: %v\\n\", b.DistroTarget)\n\t\t\t}\n\t\t\tif b.URL != \"\" {\n\t\t\t\tfmt.Printf(\"\\tUrl: %v\\n\", b.URL)\n\t\t\t}\n\t\t\tif b.InstallerUpdates {\n\t\t\t\tfmt.Printf(\"\\tInstaller Updates: %v\\n\", b.InstallerUpdates)\n\t\t\t}\n\n\t\t\tfmt.Println()\n\t\t}\n\t}\n}", "func main() {\n\n\thandler, err := NewHandler()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\t// p1 := &Product{\n\t// \tID: \"P2\",\n\t// \tName: \"IPHONE X\",\n\t// \tQuantity: 3,\n\t// }\n\n\t// newProd1, err := handler.SaveProduct(p1)\n\t// if err != nil {\n\t// \tfmt.Println(err)\n\t// \tos.Exit(1)\n\t// }\n\n\t// fmt.Println(newProd1)\n\n\t//=---------------------------\n\n\tproducts, err := handler.GetAllProduct()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n\n\tfor _, p := range products {\n\t\tfmt.Println(p)\n\t}\n}", "func (p *Printer) Print(a ...interface{}) {\n\tdoPrintV2(p.String(), fmt.Sprint(a...))\n}", "func ListDiscountController(discounter service.Discounter) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\n\t\tbearer := c.Request().Header.Get(\"Authorization\")\n\n\t\ttoken, err := service.ValidateToken(bearer[7:])\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusForbidden, \"token invalid\")\n\t\t}\n\n\t\tdiscounter.SetParkID(int(token.ID))\n\n\t\tinformation, err := discounter.ListDiscount(c)\n\t\tif err != nil {\n\t\t\treturn echo.NewHTTPError(http.StatusUnprocessableEntity, \"can not list discount\")\n\t\t}\n\n\t\treturn c.JSON(http.StatusOK, information)\n\t}\n}", "func (s Product) String() string {\n\treturn awsutil.Prettify(s)\n}", "func (s *Seriet) Print() {\n\tfmt.Println(s.serie)\n}", "func (p *Products) GetProducts(rw http.ResponseWriter, r *http.Request) {\n\tlp := data.GetProducts()\n\trw.Header().Add(\"Content-Type\", \"application/json\")\n\terr := lp.ToJSON(rw)\n\tif err != nil {\n\t\thttp.Error(rw, \"Unable to convert data.\", http.StatusInternalServerError)\n\t\treturn\n\t}\n}", "func (c *ProductsApiController) GetProducts(w http.ResponseWriter, r *http.Request) {\n\tquery := r.URL.Query()\n\tproductType := query.Get(\"productType\")\n\tlimit, err := parseInt32Parameter(query.Get(\"limit\"))\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tcursor := query.Get(\"cursor\")\n\tenhance, _ := strconv.ParseBool(query.Get(\"enhance\"))\n\txTRACEID := r.Header.Get(\"X-TRACE-ID\")\n\txTOKEN := r.Header.Get(\"X-TOKEN\")\n\tresult, err := c.service.GetProducts(r.Context(), productType, limit, cursor, enhance, xTRACEID, xTOKEN)\n\t//If an error occured, encode the error with the status code\n\tif err != nil {\n\t\tEncodeJSONResponse(err.Error(), &result.Code, w)\n\t\treturn\n\t}\n\t//If no error, encode the body and the result code\n\tEncodeJSONResponse(result.Body, &result.Code, w)\n\n}", "func (s *Service) Products(ctx context.Context) ([]*types.Products, error) {\n\n\titems := make([]*types.Products, 0)\n\tsql := `SELECT id, name, price, qty FROM products WHERE active = true ORDER BY id LIMIT 500;`\n\trows, err := s.pool.Query(ctx, sql)\n\n\tif errors.Is(err, pgx.ErrNoRows) {\n\t\treturn items, nil\n\t}\n\n\tif err != nil {\n\t\treturn nil, ErrInternal\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\titem := &types.Products{}\n\t\terr = rows.Scan(&item.ID, &item.Name, &item.Price, &item.Qty)\n\n\t\tif err != nil {\n\t\t\tlog.Println(err)\n\t\t\treturn nil, err\n\t\t}\n\t\titems = append(items, item)\n\t}\n\n\terr = rows.Err()\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn nil, err\n\t}\n\n\treturn items, nil\n}", "func GetProducts() ProductUseCase {\n\tclient := repository.GetPostgresSession()\n\tservices := services.NewController(client)\n\n\treturn &productUseCase{services}\n}" ]
[ "0.67963874", "0.6090965", "0.55673385", "0.5443993", "0.5396029", "0.5304157", "0.52153474", "0.51869905", "0.51072294", "0.5086069", "0.5071149", "0.505862", "0.5010435", "0.49991822", "0.4976426", "0.49716496", "0.49596134", "0.49588382", "0.49179962", "0.48800486", "0.4844401", "0.48405403", "0.48300186", "0.4818569", "0.48084742", "0.48084742", "0.48051593", "0.4801338", "0.4796572", "0.47944665", "0.4792172", "0.47877413", "0.47854188", "0.47788396", "0.47759002", "0.47700498", "0.47687584", "0.47671816", "0.4758818", "0.4756718", "0.4756692", "0.4747859", "0.4746432", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.47445875", "0.4742518", "0.4733005", "0.47302312", "0.4727591", "0.472457", "0.47100535", "0.47079745", "0.47067672", "0.46953663", "0.4683144", "0.46810532", "0.46632323", "0.46622485", "0.46524647", "0.46477917", "0.46331993", "0.46290666", "0.46255338", "0.46255338", "0.46255338", "0.46255338", "0.46163383", "0.46135437", "0.46082237", "0.46070945", "0.46070945", "0.46070945", "0.46012092", "0.45985502", "0.4594818", "0.45845696", "0.4580758", "0.45760387", "0.45755094", "0.4573386", "0.45645115", "0.45640317", "0.45621285", "0.45589018", "0.45566836", "0.45551202", "0.45533603", "0.45500734", "0.4549442", "0.4548775", "0.4548251", "0.4547827" ]
0.8453013
0
Filter is for filtering base on permission
func (bsg BillingSpendGraph) Filter(u permission.Interface) BillingSpendGraph { res := BillingSpendGraph{} res.ID = bsg.ID res.Spend = bsg.Spend return res }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (pd PublisherDetails) Filter(u permission.Interface) PublisherDetails {\n\taction := []string{}\n\tres := PublisherDetails{}\n\n\tres.Domain = pd.Domain\n\n\tres.Impression = pd.Impression\n\n\tres.Click = pd.Click\n\n\tres.ECPC = pd.ECPC\n\n\tres.ECTR = pd.ECTR\n\n\tres.ECPM = pd.ECPM\n\n\tres.Spend = pd.Spend\n\n\tres.Conversion = pd.Conversion\n\n\tres.ConversionRate = pd.ConversionRate\n\n\tres.CPA = pd.CPA\n\n\tres.Actions = pd.Actions\n\n\tres.Actions = strings.Join(action, \",\")\n\treturn res\n}", "func (f *accessControlDashboardPermissionFilter) Where() (string, []interface{}) {\n\treturn f.where.string, f.where.params\n}", "func (cl CampaignLog) Filter(u permission.Interface) CampaignLog {\n\taction := []string{}\n\tres := CampaignLog{}\n\n\tres.CreatedAt = cl.CreatedAt\n\n\tres.Action = cl.Action\n\n\tres.ImpersonatorEmail = cl.ImpersonatorEmail\n\n\tres.ManipulatorEmail = cl.ManipulatorEmail\n\n\tres.OwnerEmail = cl.OwnerEmail\n\n\tres.Data = cl.Data\n\n\tres.CampaignName = cl.CampaignName\n\n\tres.Kind = cl.Kind\n\n\tres.Strategy = cl.Strategy\n\n\tres.StartAt = cl.StartAt\n\n\tres.EndAt = cl.EndAt\n\n\tres.TotalBudget = cl.TotalBudget\n\n\tres.DailyBudget = cl.DailyBudget\n\n\tres.MaxBid = cl.MaxBid\n\n\tres.Actions = strings.Join(action, \",\")\n\treturn res\n}", "func GroupAdminFilter() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tguest := GetGuest(c)\n\t\tif !guest.Admin {\n\t\t\tc.JSON(403, http.StatusText(403))\n\t\t\tc.Abort()\n\t\t} else {\n\t\t\tc.Next()\n\t\t}\n\t}\n}", "func UserTypeFilter(filterTypes []accounts.AccountType, handler rest.HandlerFunc) rest.HandlerFunc {\n\treturn func(w rest.ResponseWriter, r *rest.Request) {\n\t\tauthInfo := GetAuthInfo(r)\n\t\tif authInfo != nil && len(filterTypes) > 0 {\n\t\t\tif _, found := find(filterTypes, authInfo.CallerType); !found {\n\t\t\t\tRestErrorWrapper(w, \"Type of user can't realize that action\", http.StatusForbidden)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t\thandler(w, r)\n\t}\n}", "func (sd *StreamData) AuthorizeWhere() {\n\tvar notAuthorize bool\n\tfor _, ip := range sd.ConnectionData.AccessControl.Where {\n\t\t// TODO : ip may contain zero padding!! org may restricted user to isp not subnet nor even device!!\n\t\tif ip == sd.UIP.SourceIPAddress {\n\t\t\tnotAuthorize = false\n\t\t\tbreak\n\t\t} else {\n\t\t\tnotAuthorize = true\n\t\t}\n\t}\n\tif notAuthorize == true {\n\t\t// sd.Err =\n\t\treturn\n\t}\n}", "func (f *aclFilter) filterIntentions(ixns *structs.Intentions) {\n\t// Management tokens can see everything with no filtering.\n\tif f.authorizer.ACLRead() {\n\t\treturn\n\t}\n\n\t// Otherwise, we need to see what the token has access to.\n\tret := make(structs.Intentions, 0, len(*ixns))\n\tfor _, ixn := range *ixns {\n\t\t// If no prefix ACL applies to this then filter it, since\n\t\t// we know at this point the user doesn't have a management\n\t\t// token, otherwise see what the policy says.\n\t\tprefix, ok := ixn.GetACLPrefix()\n\t\tif !ok || !f.authorizer.IntentionRead(prefix) {\n\t\t\tf.logger.Printf(\"[DEBUG] consul: dropping intention %q from result due to ACLs\", ixn.ID)\n\t\t\tcontinue\n\t\t}\n\n\t\tret = append(ret, ixn)\n\t}\n\n\t*ixns = ret\n}", "func (l LibsecurityRestful) toFilter() bool {\n\tif toFilterFlag == false {\n\t\tlogger.Info.Println(\"No filtering\")\n\t}\n\treturn toFilterFlag\n}", "func (gq *GrantQuery) Filter() *GrantFilter {\n\treturn &GrantFilter{gq}\n}", "func (r ApiGetHyperflexServiceAuthTokenListRequest) Filter(filter string) ApiGetHyperflexServiceAuthTokenListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (cd CampaignDetails) Filter(u permission.Interface) CampaignDetails {\n\taction := []string{}\n\tres := CampaignDetails{}\n\n\tres.ID = cd.ID\n\n\tres.Title = cd.Title\n\n\tres.Status = cd.Status\n\n\tres.Kind = cd.Kind\n\n\tres.TotalImp = cd.TotalImp\n\n\tres.TotalClick = cd.TotalClick\n\n\tres.ECTR = cd.ECTR\n\n\tres.ECPC = cd.ECPC\n\n\tres.ECPM = cd.ECPM\n\n\tres.TotalSpend = cd.TotalSpend\n\n\tres.MaxBid = cd.MaxBid\n\n\tres.Conversion = cd.Conversion\n\n\tres.TotalBudget = cd.TotalBudget\n\n\tres.TodaySpend = cd.TodaySpend\n\n\tres.CreatedAt = cd.CreatedAt\n\n\tres.StartAt = cd.StartAt\n\n\tres.EndAt = cd.EndAt\n\n\tres.TodayCTR = cd.TodayCTR\n\n\tres.TodayImp = cd.TodayImp\n\n\tres.TodayClick = cd.TodayClick\n\n\tres.Creative = cd.Creative\n\n\tres.OwnerEmail = cd.OwnerEmail\n\n\tres.ConversionRate = cd.ConversionRate\n\n\tres.CPA = cd.CPA\n\n\tres.Strategy = cd.Strategy\n\n\tres.Exchange = cd.Exchange\n\n\tres.Actions = cd.Actions\n\n\tif _, ok := u.HasOn(\"archive_campaign\", cd.OwnerID, cd.DomainID, false, false, permission.ScopeSelf, permission.ScopeGlobal); ok {\n\t\taction = append(action, \"archive\")\n\t}\n\n\tif _, ok := u.HasOn(\"copy_campaign\", cd.OwnerID, cd.DomainID, false, false, permission.ScopeSelf, permission.ScopeGlobal); ok {\n\t\taction = append(action, \"copy\")\n\t}\n\n\tif _, ok := u.HasOn(\"get_campaign\", cd.OwnerID, cd.DomainID, false, false, permission.ScopeSelf, permission.ScopeGlobal); ok {\n\t\taction = append(action, \"detail\")\n\t}\n\n\tif _, ok := u.HasOn(\"edit_campaign\", cd.OwnerID, cd.DomainID, false, false, permission.ScopeSelf, permission.ScopeGlobal); ok {\n\t\taction = append(action, \"edit\")\n\t}\n\n\tres.Actions = strings.Join(action, \",\")\n\treturn res\n}", "func filterOutPermissions(permList, filterOutList []string) []string {\n\tfilteredPerms := []string{}\n\tfor _, perm := range permList {\n\t\tfilterOut := false\n\t\tfor _, filterPerm := range filterOutList {\n\t\t\tif perm == filterPerm {\n\t\t\t\tfilterOut = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\tif filterOut {\n\t\t\tcontinue\n\t\t}\n\t\tfilteredPerms = append(filteredPerms, perm)\n\t}\n\treturn filteredPerms\n}", "func (r ApiGetHyperflexProtectedClusterListRequest) Filter(filter string) ApiGetHyperflexProtectedClusterListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (m *GrantMutation) Filter() *GrantFilter {\n\treturn &GrantFilter{m}\n}", "func (o *OptionsFilter) Filter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tif \"OPTIONS\" != req.Request.Method {\n\t\tchain.ProcessFilter(req, resp)\n\t\treturn\n\t}\n\n\tarchs := req.Request.Header.Get(restful.HEADER_AccessControlRequestHeaders)\n\t//methods := strings.Join(o.getContainer().ComputeAllowedMethods(req), \",\")\n\torigin := req.Request.Header.Get(restful.HEADER_Origin)\n\tif len(origin) == 0 {\n\t\torigin = \"*\"\n\t}\n\tlog.Printf(\"request >> origin:%s\\n\", origin)\n\tresp.AddHeader(restful.HEADER_Allow, \"*\")\n\tresp.AddHeader(restful.HEADER_AccessControlAllowOrigin, origin)\n\tresp.AddHeader(restful.HEADER_AccessControlAllowHeaders, archs)\n\tresp.AddHeader(restful.HEADER_AccessControlAllowMethods, \"*\")\n\tresp.AddHeader(restful.HEADER_AccessControlAllowCredentials, \"true\")\n}", "func (res *Resource) Filter(filter *Filter) {\n\tfilter.Resource = res\n\n\tif filter.Label == \"\" {\n\t\tfilter.Label = utils.HumanizeString(filter.Name)\n\t}\n\n\tif filter.Config != nil {\n\t\tfilter.Config.ConfigureQORAdminFilter(filter)\n\t}\n\n\tif filter.Handler == nil {\n\t\t// generate default handler\n\t\tfilter.Handler = func(db *gorm.DB, filterArgument *FilterArgument) *gorm.DB {\n\t\t\tif metaValue := filterArgument.Value.Get(\"Value\"); metaValue != nil {\n\t\t\t\treturn defaultFieldFilter(res, []string{filter.Name}, utils.ToString(metaValue.Value), db, filterArgument.Context)\n\t\t\t}\n\t\t\treturn db\n\t\t}\n\t}\n\n\tif filter.Type != \"\" {\n\t\tres.filters = append(res.filters, filter)\n\t} else {\n\t\tutils.ExitWithMsg(\"Invalid filter definition %v for resource %v\", filter.Name, res.Name)\n\t}\n}", "func (m Manager) Filter(clauses ...sol.Clause) Manager {\n\treturn m.FilterDelete(clauses...).FilterUpdate(clauses...).FilterSelect(clauses...)\n}", "func (r ApiGetHyperflexDatastoreStatisticListRequest) Filter(filter string) ApiGetHyperflexDatastoreStatisticListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexLocalCredentialPolicyListRequest) Filter(filter string) ApiGetHyperflexLocalCredentialPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (cm *CasbinModule) AuthzFilter(c *revel.Controller, fc []revel.Filter) {\n\tif !CheckPermission(cm.enforcer, c.Request) {\n\t\tc.Result = c.Forbidden(\"Access denied by the Authz plugin.\")\n\t\treturn\n\t} else {\n\t\tfc[0](c, fc[1:])\n\t}\n}", "func (r ApiGetHyperflexClusterProfileListRequest) Filter(filter string) ApiGetHyperflexClusterProfileListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (a UsersAPI) Filter(filter string) (u []ScimUser, err error) {\n\tvar users UserList\n\treq := map[string]string{}\n\tif filter != \"\" {\n\t\treq[\"filter\"] = filter\n\t}\n\terr = a.client.Scim(a.context, http.MethodGet, \"/preview/scim/v2/Users\", req, &users)\n\tif err != nil {\n\t\treturn\n\t}\n\tu = users.Resources\n\treturn\n}", "func (r ApiGetResourcepoolPoolMemberListRequest) Filter(filter string) ApiGetResourcepoolPoolMemberListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (cd CampaignDaily) Filter(u permission.Interface) CampaignDaily {\n\taction := []string{}\n\tres := CampaignDaily{}\n\n\tres.Date = cd.Date\n\n\tres.Impression = cd.Impression\n\n\tres.Click = cd.Click\n\n\tres.ECTR = cd.ECTR\n\n\tres.ECPC = cd.ECPC\n\n\tres.ECPM = cd.ECPM\n\n\tres.Spend = cd.Spend\n\n\tres.Conversion = cd.Conversion\n\n\tres.ConversionRate = cd.ConversionRate\n\n\tres.CPA = cd.CPA\n\n\tres.Actions = strings.Join(action, \",\")\n\treturn res\n}", "func (c *TokenFilterConditional) Filter(filter ...string) *TokenFilterConditional {\n\tc.filter = append(c.filter, filter...)\n\treturn c\n}", "func (r ApiDatacentersLansGetRequest) Filter(key string, value string) ApiDatacentersLansGetRequest {\n\tfilterKey := fmt.Sprintf(FilterQueryParam, key)\n\tr.filters[filterKey] = []string{value}\n\treturn r\n}", "func _filter() {\n\n}", "func (r ApiGetResourcepoolUniverseListRequest) Filter(filter string) ApiGetResourcepoolUniverseListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func AuthFilter(c *revel.Controller, fc []revel.Filter) {\n\tif !revel.Config.BoolDefault(AUTHENTICATED_CONF, false) {\n\t\tfc[0](c, fc[1:])\n\t\treturn\n\t}\n\t//appSecret := revel.Config.StringDefault(\"app.secret\", \"dummy_secret\")\n\tif strings.Index(strings.TrimRight(c.Request.GetPath(), \"/\"), \"/ui\") == 0 {\n\t\tfc[0](c, fc[1:])\n\t\treturn\n\t}\n\tredirect := c.Params.Query.Get(\"redirect\")\n\tif strings.TrimRight(c.Request.GetPath(), \"/\") == AUTH_LOGIN_PATH {\n\t\tvar user models.User\n\t\tusername := c.Params.Form.Get(\"username\")\n\t\tif DB.Where(&models.User{Username: username}).First(&user).RecordNotFound() {\n\t\t\tar := util.AppResponse{http.StatusUnauthorized, \"username or password incorrect\", nil}\n\t\t\tar.ApplyFilter(c.Response)\n\t\t\treturn\n\t\t}\n\t\tpassword := c.Params.Form.Get(\"password\")\n\t\tif err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(password)); err != nil {\n\t\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\t\tc.Response.GetWriter().Write([]byte(\"username or password incorrect\"))\n\t\t\treturn\n\t\t}\n\t\troles := new([]models.Role)\n\t\tperms := new([]models.Permission)\n\t\tDB.Model(&user).Related(roles, \"Roles\")\n\t\tnewPerms := new([]models.Permission)\n\t\tfor _, r := range *roles {\n\t\t\tDB.Model(&r).Related(newPerms, \"Permissions\")\n\t\t\t*perms = append(*perms, *newPerms...)\n\t\t}\n\t\tsecretUsername := &strings.Builder{}\n\t\tencoder := base32.NewEncoder(base32.StdEncoding, secretUsername)\n\t\tencoder.Write([]byte(username))\n\t\tdefer encoder.Close()\n\t\totp, err := hotp.GenerateCode(secretUsername.String(), user.Counter)\n\t\tif err != nil {\n\t\t\tc.Response.SetStatus(http.StatusInternalServerError)\n\t\t\tc.Response.GetWriter().Write([]byte(\"error generating one time password\" + err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\ttoken := jwt.NewWithClaims(jwt.SigningMethodRS256, jwt.MapClaims{\n\t\t\tUSER_ID: username,\n\t\t\tOTP: otp,\n\t\t\tROLES: roles,\n\t\t\tPERMS: perms,\n\t\t\t\"nbf\": time.Now().Unix(),\n\t\t\t\"exp\": time.Now().Add(time.Hour * 24).Unix(),\n\t\t})\n\n\t\ttokenString, err := token.SignedString(signKey)\n\t\tif err != nil {\n\t\t\tc.Response.SetStatus(http.StatusInternalServerError)\n\t\t\tc.Response.GetWriter().Write([]byte(\"error generating token \" + err.Error()))\n\t\t\treturn\n\t\t}\n\t\tc.Response.Out.Header().Set(AUTHORIZATION_HEADER, fmt.Sprintf(\"Bearer %s\", tokenString))\n\t\tAuthCounter[username] = uint64(user.Counter)\n\t\tif redirect != \"\" {\n\t\t\tc.Redirect(redirect)\n\t\t\treturn\n\t\t}\n\t\tc.Response.SetStatus(http.StatusOK)\n\t\treturn\n\t}\n\n\tvar username string\n\tvar otp string\n\tif strings.TrimRight(c.Request.GetPath(), \"/\") == AUTH_REGISTER_PATH {\n\t\tvar user models.User\n\t\tusername := c.Params.Form.Get(\"username\")\n\t\tif !DB.Where(&models.User{Username: username}).First(&user).RecordNotFound() {\n\t\t\tc.Response.SetStatus(http.StatusBadRequest)\n\t\t\tc.Response.GetWriter().Write([]byte(\"username already exists\"))\n\t\t\treturn\n\t\t}\n\t\tpassword := c.Params.Form.Get(\"password\")\n\t\thashedPassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)\n\t\tif err != nil {\n\t\t\tc.Response.SetStatus(http.StatusInternalServerError)\n\t\t\tc.Response.GetWriter().Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\t\temail := c.Params.Form.Get(\"email\")\n\t\tuser.Username = username\n\t\tuser.Password = string(hashedPassword)\n\t\tuser.Email = email\n\t\tuser.Counter = 1\n\t\tDB.Create(&user)\n\n\t\trole := models.Role{\n\t\t\tName: \"user\",\n\t\t}\n\t\tDB.Model(&role).Association(\"Users\").Append([]*models.User{&user})\n\t\tDB.Model(&user).Association(\"Roles\").Append([]*models.Role{&role})\n\n\t\tc.Response.SetStatus(http.StatusOK)\n\t\tif redirect != \"\" {\n\t\t\tc.Redirect(redirect)\n\t\t\treturn\n\t\t}\n\t\treturn\n\t}\n\theaderData := c.Request.Header.Get(AUTHORIZATION_HEADER)\n\theaders := strings.Split(headerData, \" \")\n\tif len(headers) != 2 {\n\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\tc.Response.GetWriter().Write([]byte(AUTHORIZATION_HEADER + \" format invalid\"))\n\t\treturn\n\t}\n\tif headers[0] != \"Bearer\" {\n\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\tc.Response.GetWriter().Write([]byte(AUTHORIZATION_HEADER + \" format invalid; 'Bearer' missing\"))\n\t\treturn\n\t}\n\ttokenString := headers[1]\n\ttoken, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {\n\t\tif _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {\n\t\t\treturn nil, fmt.Errorf(\"Unexpected signing method: %v\", token.Header[\"alg\"])\n\t\t}\n\t\treturn verifyKey, nil\n\t})\n\tif err != nil {\n\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\tc.Response.GetWriter().Write([]byte(err.Error()))\n\t\treturn\n\t}\n\tif !token.Valid {\n\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\tc.Response.GetWriter().Write([]byte(\"invalid token\"))\n\t\treturn\n\t}\n\tif claims, ok := token.Claims.(jwt.MapClaims); ok {\n\t\tuserId := claims[USER_ID]\n\t\tif uname, ok := userId.(string); !ok {\n\t\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\t\tc.Response.GetWriter().Write([]byte(\"no username found in claim\"))\n\t\t\treturn\n\t\t} else {\n\t\t\tusername = uname\n\t\t}\n\t\totpInt := claims[OTP]\n\t\tif p, ok := otpInt.(string); !ok {\n\t\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\t\tc.Response.GetWriter().Write([]byte(\"OTP not found\"))\n\t\t\treturn\n\t\t} else {\n\t\t\totp = p\n\t\t}\n\t\tsecretUsername := &strings.Builder{}\n\t\tencoder := base32.NewEncoder(base32.StdEncoding, secretUsername)\n\t\tencoder.Write([]byte(username))\n\t\tdefer encoder.Close()\n\t\tif AuthCounter[username] == 0 {\n\t\t\tvar user models.User\n\t\t\tif DB.Where(&models.User{Username: username}).First(&user).RecordNotFound() {\n\t\t\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\t\t\tc.Response.GetWriter().Write([]byte(\"Username is invalid\"))\n\t\t\t}\n\t\t\tAuthCounter[username] = user.Counter\n\t\t}\n\t\tif !hotp.Validate(otp, AuthCounter[username], secretUsername.String()) {\n\t\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\t\tc.Response.GetWriter().Write([]byte(\"OTP is invalid\"))\n\t\t\treturn\n\t\t}\n\t\tc.Args[USER_ID] = username\n\t\trevel.AppLog.Debugf(\"id=%s, roles=%+v perms=%+v\", username, claims[ROLES], claims[PERMS])\n\t\tc.Args[ROLES] = claims[ROLES]\n\t\tc.Args[PERMS] = claims[PERMS]\n\t} else {\n\t\tc.Response.SetStatus(http.StatusUnauthorized)\n\t\tc.Response.GetWriter().Write([]byte(\"invalid token claim\"))\n\t\treturn\n\t}\n\tif strings.TrimRight(c.Request.GetPath(), \"/\") == AUTH_LOGOUT_PATH {\n\t\tvar user models.User\n\t\tif DB.Where(&models.User{Username: username}).First(&user).RecordNotFound() {\n\t\t\tc.Response.SetStatus(http.StatusBadRequest)\n\t\t\tc.Response.GetWriter().Write([]byte(\"invalid username\"))\n\t\t\treturn\n\t\t}\n\t\tuser.Counter = user.Counter + 1\n\t\tAuthCounter[username] = AuthCounter[username] + 1\n\t\tDB.Model(&user).Update(user)\n\t\tc.Response.SetStatus(http.StatusOK)\n\t\treturn\n\t}\n\n\tfc[0](c, fc[1:])\n}", "func (model *Permissions) FindFilter(limit int, offset int, orderby []string, sort []string, filter interface{}) (interface{}, error) {\n\trole := []Permissions{}\n\n\treturn basemodel.FindFilter(&role, orderby, sort, limit, offset, filter)\n}", "func NewAccessControlDashboardPermissionFilter(user *user.SignedInUser, permissionLevel dashboards.PermissionType, queryType string, features featuremgmt.FeatureToggles, recursiveQueriesAreSupported bool) *accessControlDashboardPermissionFilter {\n\tneedEdit := permissionLevel > dashboards.PERMISSION_VIEW\n\n\tvar folderActions []string\n\tvar dashboardActions []string\n\tif queryType == searchstore.TypeFolder {\n\t\tfolderActions = append(folderActions, dashboards.ActionFoldersRead)\n\t\tif needEdit {\n\t\t\tfolderActions = append(folderActions, dashboards.ActionDashboardsCreate)\n\t\t}\n\t} else if queryType == searchstore.TypeDashboard {\n\t\tdashboardActions = append(dashboardActions, dashboards.ActionDashboardsRead)\n\t\tif needEdit {\n\t\t\tdashboardActions = append(dashboardActions, dashboards.ActionDashboardsWrite)\n\t\t}\n\t} else if queryType == searchstore.TypeAlertFolder {\n\t\tfolderActions = append(\n\t\t\tfolderActions,\n\t\t\tdashboards.ActionFoldersRead,\n\t\t\taccesscontrol.ActionAlertingRuleRead,\n\t\t)\n\t\tif needEdit {\n\t\t\tfolderActions = append(\n\t\t\t\tfolderActions,\n\t\t\t\taccesscontrol.ActionAlertingRuleCreate,\n\t\t\t)\n\t\t}\n\t} else {\n\t\tfolderActions = append(folderActions, dashboards.ActionFoldersRead)\n\t\tdashboardActions = append(dashboardActions, dashboards.ActionDashboardsRead)\n\t\tif needEdit {\n\t\t\tfolderActions = append(folderActions, dashboards.ActionDashboardsCreate)\n\t\t\tdashboardActions = append(dashboardActions, dashboards.ActionDashboardsWrite)\n\t\t}\n\t}\n\n\tf := accessControlDashboardPermissionFilter{user: user, folderActions: folderActions, dashboardActions: dashboardActions, features: features,\n\t\trecursiveQueriesAreSupported: recursiveQueriesAreSupported,\n\t}\n\n\tf.buildClauses()\n\n\treturn &f\n}", "func (r ApiDatacentersLansNicsGetRequest) Filter(key string, value string) ApiDatacentersLansNicsGetRequest {\n\tfilterKey := fmt.Sprintf(FilterQueryParam, key)\n\tr.filters[filterKey] = []string{value}\n\treturn r\n}", "func (aaq *APIAuditQuery) Filter() *APIAuditFilter {\n\treturn &APIAuditFilter{aaq}\n}", "func (r ApiGetHyperflexClusterStoragePolicyListRequest) Filter(filter string) ApiGetHyperflexClusterStoragePolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexProxySettingPolicyListRequest) Filter(filter string) ApiGetHyperflexProxySettingPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiDatacentersGetRequest) Filter(key string, value string) ApiDatacentersGetRequest {\n\tfilterKey := fmt.Sprintf(FilterQueryParam, key)\n\tr.filters[filterKey] = []string{value}\n\treturn r\n}", "func (r ApiGetHyperflexClusterBackupPolicyListRequest) Filter(filter string) ApiGetHyperflexClusterBackupPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (o FolderBucketViewOutput) Filter() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FolderBucketView) pulumi.StringOutput { return v.Filter }).(pulumi.StringOutput)\n}", "func (r ApiGetHyperflexAlarmListRequest) Filter(filter string) ApiGetHyperflexAlarmListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func authorizationFilter(host service.Host) FilterFunc {\n\treturn func(ctx context.Context, w http.ResponseWriter, r *http.Request, next Handler) {\n\t\tfxctx := &fxcontext.Context{\n\t\t\tContext: ctx,\n\t\t}\n\n\t\tif err := host.AuthClient().Authorize(fxctx); err != nil {\n\t\t\thost.Metrics().SubScope(\"http\").SubScope(\"auth\").Counter(\"fail\").Inc(1)\n\t\t\tfxctx.Logger().Error(auth.ErrAuthorization, \"error\", err)\n\t\t\tw.WriteHeader(http.StatusUnauthorized)\n\t\t\tfmt.Fprintf(w, \"Unauthorized access: %+v\", err)\n\t\t\treturn\n\t\t}\n\t\tnext.ServeHTTP(fxctx, w, r)\n\t}\n}", "func (s *Service) isAllowed(entry ytfeed.Entry, fi FeedInfo) (ok bool, err error) {\n\n\tmatchedIncludeFilter := true\n\tif fi.Filter.Include != \"\" {\n\t\tmatchedIncludeFilter, err = regexp.MatchString(fi.Filter.Include, entry.Title)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"failed to check if entry %s matches include filter\", entry.VideoID)\n\t\t}\n\t}\n\n\tmatchedExcludeFilter := false\n\tif fi.Filter.Exclude != \"\" {\n\t\tmatchedExcludeFilter, err = regexp.MatchString(fi.Filter.Exclude, entry.Title)\n\t\tif err != nil {\n\t\t\treturn false, errors.Wrapf(err, \"failed to check if entry %s matches exclude filter\", entry.VideoID)\n\t\t}\n\t}\n\n\treturn matchedIncludeFilter && !matchedExcludeFilter, nil\n}", "func (_MonsterOwnership *MonsterOwnershipFilterer) FilterApproval(opts *bind.FilterOpts) (*MonsterOwnershipApprovalIterator, error) {\n\n\tlogs, sub, err := _MonsterOwnership.contract.FilterLogs(opts, \"Approval\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MonsterOwnershipApprovalIterator{contract: _MonsterOwnership.contract, event: \"Approval\", logs: logs, sub: sub}, nil\n}", "func (_Erc777 *Erc777Filterer) FilterAuthorizedOperator(opts *bind.FilterOpts, operator []common.Address, tokenHolder []common.Address) (*Erc777AuthorizedOperatorIterator, error) {\n\n\tvar operatorRule []interface{}\n\tfor _, operatorItem := range operator {\n\t\toperatorRule = append(operatorRule, operatorItem)\n\t}\n\tvar tokenHolderRule []interface{}\n\tfor _, tokenHolderItem := range tokenHolder {\n\t\ttokenHolderRule = append(tokenHolderRule, tokenHolderItem)\n\t}\n\n\tlogs, sub, err := _Erc777.contract.FilterLogs(opts, \"AuthorizedOperator\", operatorRule, tokenHolderRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Erc777AuthorizedOperatorIterator{contract: _Erc777.contract, event: \"AuthorizedOperator\", logs: logs, sub: sub}, nil\n}", "func (r ApiGetHyperflexUcsmConfigPolicyListRequest) Filter(filter string) ApiGetHyperflexUcsmConfigPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexSysConfigPolicyListRequest) Filter(filter string) ApiGetHyperflexSysConfigPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func Filter(handlerFunc http.HandlerFunc) http.HandlerFunc {\n\treturn func(writer http.ResponseWriter, request *http.Request) {\n\n\t\t// Verify the JWT token\n\t\t_, err := ExtractToken(request)\n\t\tif err != nil {\n\t\t\thttp2.HandleUnauthorizedError(writer, request.RequestURI, err)\n\t\t\treturn\n\t\t}\n\n\t\t// Call the next filter\n\t\thandlerFunc(writer, request)\n\t}\n}", "func (r ApiGetHyperflexExtFcStoragePolicyListRequest) Filter(filter string) ApiGetHyperflexExtFcStoragePolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (model *Permissions) FilterSearchSingle(filter interface{}) error {\n\terr := basemodel.SingleFindFilter(&model, filter)\n\treturn err\n}", "func GetPermissionTypeFilterMap() map[string]kafkainstanceclient.AclPermissionTypeFilter {\n\treturn permissionTypeFilterMap\n}", "func (r *ACLResolver) filterACL(token string, subj interface{}) error {\n\t// Get the ACL from the token\n\tauthorizer, err := r.ResolveToken(token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Fast path if ACLs are not enabled\n\tif authorizer == nil {\n\t\treturn nil\n\t}\n\n\treturn r.filterACLWithAuthorizer(authorizer, subj)\n}", "func (rr ACLRulesPipe) Filter(t func(r ACLRule) bool) (cout ACLRulesPipe) {\n\tch := make(chan ACLRule)\n\tcout = ch\n\tgo func() {\n\t\tfor r := range rr {\n\t\t\tif t(r) {\n\t\t\t\tch <- r\n\t\t\t}\n\t\t}\n\t\tclose(ch)\n\t}()\n\treturn cout\n}", "func (g *genControllerUtils) Filter(c *generator.Context, t *types.Type) bool {\n\tret := !g.controllerGenerated\n\tg.controllerGenerated = true\n\treturn ret\n}", "func (r ApiGetHyperflexSoftwareVersionPolicyListRequest) Filter(filter string) ApiGetHyperflexSoftwareVersionPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexClusterNetworkPolicyListRequest) Filter(filter string) ApiGetHyperflexClusterNetworkPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetIqnpoolPoolMemberListRequest) Filter(filter string) ApiGetIqnpoolPoolMemberListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexSoftwareDistributionEntryListRequest) Filter(filter string) ApiGetHyperflexSoftwareDistributionEntryListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexNodeListRequest) Filter(filter string) ApiGetHyperflexNodeListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetIqnpoolUniverseListRequest) Filter(filter string) ApiGetIqnpoolUniverseListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (App) Permissions() []evo.Permission { return []evo.Permission{} }", "func (c *authorizer) FilterOn() *api.Filter {\n\treturn &c.config.FilterOn\n}", "func Filtered(t stackvm.Tracer, p action.Predicate) stackvm.Tracer {\n\tswitch p {\n\tcase nil:\n\t\treturn nil\n\tcase action.Never:\n\t\treturn nil\n\tcase action.Always:\n\t\treturn t\n\tdefault:\n\t\treturn filter{t, p}\n\t}\n}", "func (r ApiGetHyperflexHealthListRequest) Filter(filter string) ApiGetHyperflexHealthListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetBulkSubRequestObjListRequest) Filter(filter string) ApiGetBulkSubRequestObjListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (ccs CampaignCreativeStatus) Filter(u permission.Interface) CampaignCreativeStatus {\n\taction := []string{}\n\tres := CampaignCreativeStatus{}\n\n\tres.ID = ccs.ID\n\n\tres.Title = ccs.Title\n\n\tres.Kind = ccs.Kind\n\n\tres.CreativeCount = ccs.CreativeCount\n\n\tres.OwnerEmail = ccs.OwnerEmail\n\n\tres.OwnerMobile = ccs.OwnerMobile\n\n\tres.CreatedAt = ccs.CreatedAt\n\n\tres.Actions = ccs.Actions\n\n\tif _, ok := u.HasOn(\"change_creatives_status\", ccs.OwnerID, ccs.DomainID, false, true); ok {\n\t\taction = append(action, \"accept_reject\")\n\t}\n\n\tif _, ok := u.HasOn(\"change_creative_status\", ccs.OwnerID, ccs.DomainID, false, true); ok {\n\t\taction = append(action, \"bulk_accept\")\n\t}\n\n\tres.Actions = strings.Join(action, \",\")\n\treturn res\n}", "func (r ApiGetBulkExportListRequest) Filter(filter string) ApiGetBulkExportListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func contactFilter(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tcontactID := middleware.GetContactID(request)\n\t\tuserLogin := middleware.GetLogin(request)\n\t\tcontactData, err := controller.CheckUserPermissionsForContact(database, contactID, userLogin)\n\t\tif err != nil {\n\t\t\trender.Render(writer, request, err) //nolint\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(request.Context(), contactKey, contactData)\n\t\tnext.ServeHTTP(writer, request.WithContext(ctx))\n\t})\n}", "func (r ApiGetHyperflexNodeProfileListRequest) Filter(filter string) ApiGetHyperflexNodeProfileListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (pqf PushQuotaFilter) AsFilter() (*Filter, bool) {\n\treturn nil, false\n}", "func (r ApiGetHyperflexSoftwareDistributionVersionListRequest) Filter(filter string) ApiGetHyperflexSoftwareDistributionVersionListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexLicenseListRequest) Filter(filter string) ApiGetHyperflexLicenseListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexClusterListRequest) Filter(filter string) ApiGetHyperflexClusterListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexHealthCheckDefinitionListRequest) Filter(filter string) ApiGetHyperflexHealthCheckDefinitionListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexCapabilityInfoListRequest) Filter(filter string) ApiGetHyperflexCapabilityInfoListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexAutoSupportPolicyListRequest) Filter(filter string) ApiGetHyperflexAutoSupportPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func GetMappedPermissionTypeFilterValue(permission string) kafkainstanceclient.AclPermissionTypeFilter {\n\treturn permissionTypeFilterMap[permission]\n}", "func (r ApiGetHyperflexDataProtectionPeerListRequest) Filter(filter string) ApiGetHyperflexDataProtectionPeerListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexHealthCheckExecutionSnapshotListRequest) Filter(filter string) ApiGetHyperflexHealthCheckExecutionSnapshotListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexVcenterConfigPolicyListRequest) Filter(filter string) ApiGetHyperflexVcenterConfigPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexExtIscsiStoragePolicyListRequest) Filter(filter string) ApiGetHyperflexExtIscsiStoragePolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (v *View) Filter(ctx context.Context, state *request.Request) bool {\n\tenv := expression.DefaultEnv(ctx, state)\n\tfor _, prog := range v.progs {\n\t\tresult, err := expr.Run(prog, env)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif b, ok := result.(bool); ok && b {\n\t\t\tcontinue\n\t\t}\n\t\t// anything other than a boolean true result is considered false\n\t\treturn false\n\t}\n\treturn true\n}", "func (s *ServicesWidget) Filter(filter string) {\n\ts.Lock()\n\tdefer s.Unlock()\n\ts.filterPattern = filter\n}", "func (r ApiGetIqnpoolReservationListRequest) Filter(filter string) ApiGetIqnpoolReservationListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (eouf EngageOldUsersFilter) AsFilter() (*Filter, bool) {\n\treturn nil, false\n}", "func (m *APIAuditMutation) Filter() *APIAuditFilter {\n\treturn &APIAuditFilter{m}\n}", "func subscriptionFilter(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {\n\t\tcontactID := middleware.GetSubscriptionId(request)\n\t\tuserLogin := middleware.GetLogin(request)\n\t\tsubscriptionData, err := controller.CheckUserPermissionsForSubscription(database, contactID, userLogin)\n\t\tif err != nil {\n\t\t\trender.Render(writer, request, err)\n\t\t\treturn\n\t\t}\n\t\tctx := context.WithValue(request.Context(), subscriptionKey, subscriptionData)\n\t\tnext.ServeHTTP(writer, request.WithContext(ctx))\n\t})\n}", "func (Var) Filter(pred func(*VarFilterContext) bool) bool { return boolResult }", "func (r ApiGetHyperflexHealthCheckExecutionListRequest) Filter(filter string) ApiGetHyperflexHealthCheckExecutionListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (_Bucket *BucketFilterer) FilterNewWritePermission(opts *bind.FilterOpts, entity []common.Address) (*BucketNewWritePermissionIterator, error) {\n\n\tvar entityRule []interface{}\n\tfor _, entityItem := range entity {\n\t\tentityRule = append(entityRule, entityItem)\n\t}\n\n\tlogs, sub, err := _Bucket.contract.FilterLogs(opts, \"NewWritePermission\", entityRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &BucketNewWritePermissionIterator{contract: _Bucket.contract, event: \"NewWritePermission\", logs: logs, sub: sub}, nil\n}", "func (s *Searcher) Filter(filter *Filter, values *resource.MetaValues) *Searcher {\n\tnewSearcher := s.clone()\n\tif newSearcher.filters == nil {\n\t\tnewSearcher.filters = map[*Filter]*resource.MetaValues{}\n\t}\n\tnewSearcher.filters[filter] = values\n\treturn newSearcher\n}", "func (enuf EngageNewUsersFilter) AsFilter() (*Filter, bool) {\n\treturn nil, false\n}", "func (l LibsecurityRestful) SuperUserFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {\n\tif l.verifyUserPermissions(req, resp, chain, am.SuperUserPermission) == true {\n\t\tchain.ProcessFilter(req, resp)\n\t}\n}", "func (_MintableToken *MintableTokenFilterer) FilterApproval(opts *bind.FilterOpts, owner []common.Address, spender []common.Address) (*MintableTokenApprovalIterator, error) {\n\n\tvar ownerRule []interface{}\n\tfor _, ownerItem := range owner {\n\t\townerRule = append(ownerRule, ownerItem)\n\t}\n\tvar spenderRule []interface{}\n\tfor _, spenderItem := range spender {\n\t\tspenderRule = append(spenderRule, spenderItem)\n\t}\n\n\tlogs, sub, err := _MintableToken.contract.FilterLogs(opts, \"Approval\", ownerRule, spenderRule)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &MintableTokenApprovalIterator{contract: _MintableToken.contract, event: \"Approval\", logs: logs, sub: sub}, nil\n}", "func (w *Workflow) Filter(query string) *Workflow {\n\tw.items = w.items.Filter(query)\n\treturn w\n}", "func (r ApiGetBulkResultListRequest) Filter(filter string) ApiGetBulkResultListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func (r ApiGetHyperflexClusterReplicationNetworkPolicyListRequest) Filter(filter string) ApiGetHyperflexClusterReplicationNetworkPolicyListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func identityRoleFilterByResource(resourceID string) func(db *gorm.DB) *gorm.DB {\n\treturn func(db *gorm.DB) *gorm.DB {\n\t\treturn db.Where(\"resource_id = ?\", resourceID)\n\t}\n}", "func filterAnime(ctx aero.Context, user *arn.User, filter func(*arn.Anime) bool) ([]*arn.Anime, int) {\n\tyear := ctx.Get(\"year\")\n\tstatus := ctx.Get(\"status\")\n\tseason := ctx.Get(\"season\")\n\ttyp := ctx.Get(\"type\")\n\n\tif year == \"any\" {\n\t\tyear = \"\"\n\t}\n\n\tif status == \"any\" {\n\t\tstatus = \"\"\n\t}\n\n\tif season == \"any\" {\n\t\tseason = \"\"\n\t}\n\n\tif typ == \"any\" {\n\t\ttyp = \"\"\n\t}\n\n\tsettings := user.Settings()\n\tsettings.Editor.Filter.Year = year\n\tsettings.Editor.Filter.Season = season\n\tsettings.Editor.Filter.Status = status\n\tsettings.Editor.Filter.Type = typ\n\tsettings.Save()\n\n\t// Filter\n\tanimes := arn.FilterAnime(func(anime *arn.Anime) bool {\n\t\tif year != \"\" && (len(anime.StartDate) < 4 || anime.StartDate[:4] != year) {\n\t\t\treturn false\n\t\t}\n\n\t\tif season != \"\" && anime.Season() != season {\n\t\t\treturn false\n\t\t}\n\n\t\tif status != \"\" && anime.Status != status {\n\t\t\treturn false\n\t\t}\n\n\t\tif typ != \"\" && anime.Type != typ {\n\t\t\treturn false\n\t\t}\n\n\t\treturn filter(anime)\n\t})\n\n\t// Sort\n\tarn.SortAnimeByQuality(animes)\n\n\t// Limit\n\tcount := len(animes)\n\n\tif count > maxAnimeEntries {\n\t\tanimes = animes[:maxAnimeEntries]\n\t}\n\n\treturn animes, count\n}", "func (r ApiGetResourcepoolLeaseResourceListRequest) Filter(filter string) ApiGetResourcepoolLeaseResourceListRequest {\n\tr.filter = &filter\n\treturn r\n}", "func restrictAccessFilter(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Get cookie\n\t\tcookie, err := r.Cookie(cookieName)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttokenStr := cookie.Value\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\t// Validate and extract the username from the token.\n\t\tclaims := JWTClaims{}\n\t\ttoken, err := jwt.ParseWithClaims(tokenStr, &claims, func(token *jwt.Token) (interface{}, error) {\n\t\t\treturn secret, nil\n\t\t})\n\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\t\tif !token.Valid {\n\t\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\t\tnext.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\tusername := claims.Username\n\n\t\t// Add user to the context\n\t\tctx := context.WithValue(r.Context(), userContextKey, username)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}", "func (r ApiGetHyperflexFeatureLimitInternalListRequest) Filter(filter string) ApiGetHyperflexFeatureLimitInternalListRequest {\n\tr.filter = &filter\n\treturn r\n}" ]
[ "0.6111526", "0.6097766", "0.6033513", "0.5901573", "0.58897924", "0.5764668", "0.5754081", "0.5739796", "0.57370657", "0.57136273", "0.56810737", "0.56799555", "0.56732625", "0.56067866", "0.55973357", "0.5581766", "0.558101", "0.5571991", "0.55675435", "0.55151874", "0.55058736", "0.55007046", "0.54964226", "0.5494768", "0.54926723", "0.5491382", "0.5478997", "0.5467597", "0.5458905", "0.5446295", "0.5443819", "0.54374105", "0.54257166", "0.5385301", "0.5383427", "0.53722477", "0.5371777", "0.53628296", "0.53625613", "0.5362131", "0.5355606", "0.5352862", "0.5349518", "0.53461725", "0.5344821", "0.534187", "0.53379077", "0.5334857", "0.5334592", "0.53345484", "0.53252363", "0.532079", "0.5312983", "0.5308777", "0.53080523", "0.5302026", "0.52923185", "0.52848387", "0.5283528", "0.5281447", "0.5274965", "0.5261554", "0.5261437", "0.5260537", "0.5254165", "0.5246364", "0.52336806", "0.5229986", "0.52256364", "0.52222425", "0.5219177", "0.52137625", "0.52133495", "0.5212633", "0.52101", "0.52007747", "0.52000755", "0.5199837", "0.5193137", "0.51869327", "0.5184869", "0.51835555", "0.5181661", "0.51805747", "0.5178508", "0.51778805", "0.51772004", "0.51760364", "0.5169672", "0.5168376", "0.5163076", "0.51595306", "0.5156599", "0.5156442", "0.51520103", "0.5148508", "0.51479095", "0.51444143", "0.5143856", "0.514385" ]
0.51716745
88
GetCommands returns the CLI commands exported for the XC crypto backend
func GetCommands() []*cli.Command { return []*cli.Command{ { Name: "xc", Usage: "Experimental Crypto", Hidden: true, Description: "" + "These subcommands are used to control and test the experimental crypto" + "implementation.", Subcommands: []*cli.Command{ { Name: "list-private-keys", Action: ListPrivateKeys, }, { Name: "list-public-keys", Action: ListPublicKeys, }, { Name: "generate", Action: GenerateKeypair, }, { Name: "export", Action: ExportPublicKey, Flags: []cli.Flag{ &cli.StringFlag{ Name: "id", }, &cli.StringFlag{ Name: "file", }, }, }, { Name: "import", Action: ImportPublicKey, Flags: []cli.Flag{ &cli.StringFlag{ Name: "id", }, &cli.StringFlag{ Name: "file", }, }, }, { Name: "export-private-key", Action: ExportPrivateKey, Flags: []cli.Flag{ &cli.StringFlag{ Name: "id", }, &cli.StringFlag{ Name: "file", }, }, }, { Name: "import-private-key", Action: ImportPrivateKey, Flags: []cli.Flag{ &cli.StringFlag{ Name: "id", }, &cli.StringFlag{ Name: "file", }, }, }, { Name: "remove", Action: RemoveKey, Flags: []cli.Flag{ &cli.StringFlag{ Name: "id", }, }, }, { Name: "encrypt", Action: EncryptFile, Flags: []cli.Flag{ &cli.StringFlag{ Name: "file", }, &cli.StringSliceFlag{ Name: "recipients", }, &cli.BoolFlag{ Name: "stream", }, }, }, { Name: "decrypt", Action: DecryptFile, Flags: []cli.Flag{ &cli.StringFlag{ Name: "file", }, &cli.BoolFlag{ Name: "stream", }, }, }, }, }, } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetCommands(app *App) []cli.Command {\n\t// if app.IsService {\n\t// \treturn []cli.Command{\n\t// \t\t*vmgo.MakeRequireMongo(serviceStartCmd()),\n\t// \t\t*vmgo.MakeRequireMongo(createUserCmd()),\n\t// \t\t*vmgo.MakeRequireMongo(setupCmd()),\n\t// \t\t*vmgo.MakeRequireMongo(resetCmd()),\n\t// \t\t*vmgo.MakeRequireMongo(overridePasswordCmd()),\n\t// \t\t*testEMail(),\n\t// \t}\n\t// }\n\treturn []cli.Command{\n\t\t*vmgo.MakeRequireMongo(createUserCmd()),\n\t\t*vmgo.MakeRequireMongo(setupCmd()),\n\t\t*vmgo.MakeRequireMongo(resetCmd()),\n\t\t*vmgo.MakeRequireMongo(overridePasswordCmd()),\n\t\t*testEMail(),\n\t}\n}", "func GetCommands(cfg *config.Config) cli.Commands {\n\treturn []*cli.Command{\n\t\t// start this service\n\t\tServer(cfg),\n\n\t\t// interaction with this service\n\n\t\t// infos about this service\n\t\tHealth(cfg),\n\t\tVersion(cfg),\n\t}\n}", "func GetCommands() []Command {\n\treturn []Command{\n\t\t{\n\t\t\tActivation: \"quote\",\n\t\t\tAction: Quote,\n\t\t},\n\t\t{\n\t\t\tActivation: \"site\",\n\t\t\tAction: Site,\n\t\t},\n\t}\n}", "func Get() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"network\",\n\t\t\tUsage: \"Software-defined networks used by servers.\",\n\t\t\tSubcommands: networkcommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName: \"subnet\",\n\t\t\tUsage: \"Allocate IP address blocks, gateways, DNS servers, and host routes to networks.\",\n\t\t\tSubcommands: subnetcommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName: \"port\",\n\t\t\tUsage: \"Virtual switch ports on logical network switches.\",\n\t\t\tSubcommands: portcommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName: \"security-group\",\n\t\t\tUsage: \"Collections of rules for network traffic.\",\n\t\t\tSubcommands: securitygroupcommands.Get(),\n\t\t},\n\t\t{\n\t\t\tName: \"security-group-rule\",\n\t\t\tUsage: \"Define network ingress and egress rules.\",\n\t\t\tSubcommands: securitygrouprulecommands.Get(),\n\t\t},\n\t}\n}", "func (d *DevfileV2) GetCommands(options common.DevfileOptions) ([]v1.Command, error) {\n\tif len(options.Filter) == 0 {\n\t\treturn d.Commands, nil\n\t}\n\n\tvar commands []v1.Command\n\tfor _, command := range d.Commands {\n\t\tfilterIn, err := common.FilterDevfileObject(command.Attributes, options)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif filterIn {\n\t\t\tcommand.Id = strings.ToLower(command.Id)\n\t\t\tcommands = append(commands, command)\n\t\t}\n\t}\n\n\treturn commands, nil\n}", "func (d *DuinoDispatcher) GetCommands() (data []string) {\n\td.init()\n\n\tc := []string{\"CMSP\", \"gaga23\"}\n//\tc := []string{\"CSMP\"}\n\t//fmt.Printf(\"get Commands from Dispatcher called\\n\")\n\treturn c\n}", "func getCommands() []cli.Command {\n\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"create_room\",\n\t\t\tAliases: []string{\"cr\"},\n\t\t\tUsage: \"amity-golang create_room <room_name> <office|Livingspace>\",\n\t\t\tAction: createRoom,\n\t\t},\n\t\t{\n\t\t\tName: \"add_person\",\n\t\t\tAliases: []string{\"ap\"},\n\t\t\tUsage: \"amity-golang add_person <First_Name> <Last_Name> <fellow|staff> <office_Name> <livingSpace_Name>\",\n\t\t\tAction: addPerson,\n\t\t},\n\t\t{\n\t\t\tName: \"print_allocations\",\n\t\t\tAliases: []string{\"pa\"},\n\t\t\tUsage: \"amity-golang print_allocations\",\n\t\t\tAction: printAllocations,\n\t\t},\n\t\t{\n\t\t\tName: \"print_room\",\n\t\t\tAliases: []string{\"pr\"},\n\t\t\tUsage: \"amity-golang print_room <room_name>\",\n\t\t\tAction: printRoom,\n\t\t},\n\t\t{\n\t\t\tName: \"print_unallocated_people\",\n\t\t\tAliases: []string{\"pu\"},\n\t\t\tUsage: \"amity-golang print_unallocated_people\",\n\t\t\tAction: printUnallocatedPeople,\n\t\t},\n\t\t{\n\t\t\tName: \"reallocate_person\",\n\t\t\tAliases: []string{\"rp\"},\n\t\t\tUsage: \"amity-golang reallocate_person <First_Name> <Last_Name> <New_Room_Name>\",\n\t\t\tAction: reallocatePerson,\n\t\t},\n\t}\n}", "func GetSubCommands() []*cobra.Command {\n\n\tvar getrule = &cobra.Command{\n\t\tUse: \"db-rule\",\n\t\tRunE: actionGetDbRules,\n\t}\n\n\tvar getconfig = &cobra.Command{\n\t\tUse: \"db-config\",\n\t\tRunE: actionGetDbConfig,\n\t}\n\n\tvar getschema = &cobra.Command{\n\t\tUse: \"db-schema\",\n\t\tRunE: actionGetDbSchema,\n\t}\n\n\tvar getrules = &cobra.Command{\n\t\tUse: \"db-rules\",\n\t\tRunE: actionGetDbRules,\n\t}\n\n\tvar getconfigs = &cobra.Command{\n\t\tUse: \"db-configs\",\n\t\tRunE: actionGetDbConfig,\n\t}\n\n\tvar getschemas = &cobra.Command{\n\t\tUse: \"db-schemas\",\n\t\tRunE: actionGetDbSchema,\n\t}\n\n\treturn []*cobra.Command{getrule, getconfig, getschema, getrules, getconfigs, getschemas}\n}", "func (c StandardCommand) GetCommands() ([]Command, error) {\n\treturn c.SubCommands, nil\n}", "func GetCommand() []string {\n\treturn []string{\"ipconfig\", \"/all\"}\n}", "func GetCommands() []string {\n\treturn []string{\n\t\ttaskAddCommand,\n\t\ttaskDelCommand,\n\t\ttaskListCommand,\n\t}\n}", "func GetSubCommands() []*cobra.Command {\n\n\tvar getproject = &cobra.Command{\n\t\tUse: \"project\",\n\t\tRunE: actionGetProjectConfig,\n\t}\n\n\tvar getprojects = &cobra.Command{\n\t\tUse: \"projects\",\n\t\tRunE: actionGetProjectConfig,\n\t}\n\n\treturn []*cobra.Command{getproject, getprojects}\n}", "func GetTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tcmd.AddCommand(\n\t\tNewLockTokensCmd(),\n\t\tNewUnlockTokensCmd(),\n\t\tNewUnlockByIDCmd(),\n\t)\n\n\treturn cmd\n}", "func GetSubCommands() []*cobra.Command {\n\n\tvar getFileStoreRule = &cobra.Command{\n\t\tUse: \"filestore-rules\",\n\t\tRunE: actionGetFileStoreRule,\n\t}\n\n\tvar getFileStoreConfig = &cobra.Command{\n\t\tUse: \"filestore-config\",\n\t\tRunE: actionGetFileStoreConfig,\n\t}\n\n\treturn []*cobra.Command{getFileStoreRule, getFileStoreConfig}\n}", "func GetTxCmd() *cobra.Command {\n\ttxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Wasm transaction subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\ttxCmd.AddCommand(\n\t\tStoreCodeCmd(),\n\t\tInstantiateContractCmd(),\n\t\tExecuteContractCmd(),\n\t\tMigrateContractCmd(),\n\t\tUpdateContractAdminCmd(),\n\t\tClearContractAdminCmd(),\n\t)\n\treturn txCmd\n}", "func GetTxCmd() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tcmd.AddCommand(RegisterChainNameCmd())\n\tcmd.AddCommand(UpdateChainInfoCmd())\n\treturn cmd\n}", "func GetTxCmd(cdc *amino.Codec) *cobra.Command {\n\ttxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Currency transactions subcommands\",\n\t}\n\n\ttxCmd.AddCommand(sdkClient.PostCommands(\n\t\tcli.PostMsIssueCurrency(cdc),\n\t\tcli.PostMsUnstakeCurrency(cdc),\n\t\tcli.PostWithdrawCurrency(cdc),\n\t\tcli.AddCurrencyProposal(cdc),\n\t)...)\n\n\treturn txCmd\n}", "func Get() []cli.Command {\n\treturn []cli.Command{\n\t\tabandon,\n\t\tadopt,\n\t\tcreate,\n\t\tget,\n\t\tgetTemplate,\n\t\tlist,\n\t\tlistEvents,\n\t\tpreview,\n\t\tremove,\n\t\tupdate,\n\t}\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\ttxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Auth transaction subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\ttxCmd.AddCommand(\n\t\tGetMultiSignCommand(cdc),\n\t\tGetSignCommand(cdc),\n\t)\n\treturn txCmd\n}", "func GetSubCommands() []*cobra.Command {\n\tvar getAuthProviders = &cobra.Command{\n\t\tUse: \"auth-providers\",\n\t\tAliases: []string{\"auth-provider\"},\n\t\tRunE: actionGetAuthProviders,\n\t\tValidArgsFunction: authProvidersAutoCompleteFunc,\n\t}\n\treturn []*cobra.Command{getAuthProviders}\n}", "func (channelInfo ChannelInfo) GetCommands() string {\n\tif channelInfo.StreamStatus.Online == true {\n\t\treturn \"!\" + strings.Join(channelInfo.OnlineCommands, \", !\")\n\n\t}\n\treturn \"!\" + strings.Join(channelInfo.OfflineCommands, \", !\")\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tstorageTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tstorageTxCmd.AddCommand(flags.PostCommands(\n\t\tGetSetStorageDataCmd(cdc),\n\t)...)\n\n\treturn storageTxCmd\n}", "func Commands() map[string]cli.CommandFactory {\n\tmeta := &command.Meta{\n\t\tAppName: AppName,\n\t\tUi: &cli.BasicUi{\n\t\t\tWriter: os.Stdout,\n\t\t\tErrorWriter: os.Stderr,\n\t\t},\n\n\t\tAcdApiClientId: acdApiClientId,\n\t\tAcdApiSecret: acdApiSecret,\n\t\tCallbackPort: \"56789\",\n\t}\n\n\treturn map[string]cli.CommandFactory{\n\t\t\"auth\": func() (cli.Command, error) {\n\t\t\treturn &command.AuthCommand{\n\t\t\t\tMeta: *meta,\n\t\t\t}, nil\n\t\t},\n\t\t\"storage\": func() (cli.Command, error) {\n\t\t\treturn &command.StorageCommand{\n\t\t\t\tMeta: *meta,\n\t\t\t}, nil\n\t\t},\n\t\t\"ls\": func() (cli.Command, error) {\n\t\t\treturn &command.ListCommand{\n\t\t\t\tMeta: *meta,\n\t\t\t}, nil\n\t\t},\n\t\t\"info\": func() (cli.Command, error) {\n\t\t\treturn &command.InfoCommand{\n\t\t\t\tMeta: *meta,\n\t\t\t}, nil\n\t\t},\n\t\t\"get\": func() (cli.Command, error) {\n\t\t\treturn &command.DownloadCommand{\n\t\t\t\tMeta: *meta,\n\t\t\t}, nil\n\t\t},\n\t\t\"version\": func() (cli.Command, error) {\n\t\t\treturn &command.VersionCommand{\n\t\t\t\tAppName: AppName,\n\t\t\t\tRevision: gitCommit,\n\t\t\t\tVersion: Version,\n\t\t\t\tVersionPrerelease: VersionPrerelease,\n\t\t\t\tUi: meta.Ui,\n\t\t\t}, nil\n\t\t},\n\t}\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: swap.ModuleName,\n\t\tShort: \"swap subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\tcmd.AddCommand(\n\t\tGetSwapTxCmd(cdc),\n\t)\n\n\treturn cmd\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tscxTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tscxTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdAppendOrganization(cdc),\n\t\tGetCmdRelegateOrganization(cdc),\n\t\tGetCmdReapproveOrganization(cdc),\n\t\tGetCmdCreateProduct(cdc),\n\t\tGetCmdCreateUnit(cdc),\n\t\tGetCmdTransferUnit(cdc),\n\t)...)\n\n\treturn scxTxCmd\n}", "func (c *Cacheable) Commands() []string {\n\treturn c.cs.s\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tissuanceTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"transaction commands for the issuance module\",\n\t}\n\n\tissuanceTxCmd.AddCommand(flags.PostCommands(\n\t\tgetCmdIssueTokens(cdc),\n\t\tgetCmdRedeemTokens(cdc),\n\t\tgetCmdBlockAddress(cdc),\n\t\tgetCmdUnblockAddress(cdc),\n\t\tgetCmdPauseAsset(cdc),\n\t)...)\n\n\treturn issuanceTxCmd\n\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tmyappTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tmyappTxCmd.AddCommand(flags.PostCommands(\n // this line is used by starport scaffolding # 1\n\t\tGetCmdCreateStudent(cdc),\n\t\tGetCmdSetStudent(cdc),\n\t\tGetCmdDeleteStudent(cdc),\n\t\tGetCmdCreatePost(cdc),\n\t\tGetCmdSetPost(cdc),\n\t\tGetCmdDeletePost(cdc),\n\t)...)\n\n\treturn myappTxCmd\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tstarportchainTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tstarportchainTxCmd.AddCommand(flags.PostCommands(\n // this line is used by starport scaffolding # 1\n\t)...)\n\n\treturn starportchainTxCmd\n}", "func Get() []cli.Command {\n\treturn []cli.Command{\n\t\tsetMetadata,\n\t\tupdateMetadata,\n\t\tgetMetadata,\n\t\tdeleteMetadata,\n\t}\n}", "func GetTxCmd() *cobra.Command {\n\ttxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"airequest transaction subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\ttxCmd.AddCommand(\n\t\tGetCmdSetAIRequest(),\n\t)\n\treturn txCmd\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tcdpTxCmd := &cobra.Command{\n\t\tUse: \"cdp\",\n\t\tShort: \"cdp transactions subcommands\",\n\t}\n\n\tcdpTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdCreateCdp(cdc),\n\t\tGetCmdDeposit(cdc),\n\t\tGetCmdWithdraw(cdc),\n\t\tGetCmdDraw(cdc),\n\t\tGetCmdRepay(cdc),\n\t)...)\n\n\treturn cdpTxCmd\n}", "func (ab AppModuleBasic) GetTxCmd() *cobra.Command {\n\treturn cli.NewTxCmd(ab.cdc.InterfaceRegistry().SigningContext().ValidatorAddressCodec(), ab.cdc.InterfaceRegistry().SigningContext().AddressCodec())\n}", "func (mc ModuleClient) GetTxCmd() *cobra.Command {\n\tstakingTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Staking transaction subcommands\",\n\t}\n\n\tstakingTxCmd.AddCommand(client.PostCommands(\n\t\thstakingcli.GetCmdCreateValidator(mc.cdc),\n\t\thstakingcli.GetCmdEditValidator(mc.cdc),\n\t\thstakingcli.GetCmdDelegate(mc.cdc),\n\t\thstakingcli.GetCmdRedelegate(mc.storeKey, mc.cdc),\n\t\thstakingcli.GetCmdUnbond(mc.storeKey, mc.cdc),\n\t\thstakingcli.GetCmdUpgradeDelStatus(mc.storeKey, mc.cdc),\n\t)...)\n\n\treturn stakingTxCmd\n}", "func (c *Compatibility) GetValidCommands() []string {\n\treturn []string{\n\t\t\"apply\",\n\t\t\"destroy\",\n\t\t\"env\",\n\t\t\"get\",\n\t\t\"graph\",\n\t\t\"import\",\n\t\t\"init\",\n\t\t\"output\",\n\t\t\"plan\",\n\t\t\"providers\",\n\t\t\"refresh\",\n\t\t\"show\",\n\t\t\"taint\",\n\t\t\"untaint\",\n\t\t\"workspace\",\n\t\t\"force-unlock\",\n\t\t\"state\",\n\t}\n}", "func (cl *commandList) GetDebugCommands(mode string) [][]string {\n\tvar allCommands [][]string\n\tfor _, def := range cl.definitions {\n\t\t// TODO: incorporate query commands into e2e testing once proxy access is implemented\n\t\tif def.commandGroup == query {\n\t\t\tcontinue\n\t\t}\n\t\tif mode == runtime.ModeController && def.use == \"log-level\" {\n\t\t\t// log-level command does not support remote execution.\n\t\t\tcontinue\n\t\t}\n\t\tif mode == runtime.ModeAgent && def.agentEndpoint != nil ||\n\t\t\tmode == runtime.ModeController && def.controllerEndpoint != nil ||\n\t\t\tmode == runtime.ModeFlowAggregator && def.flowAggregatorEndpoint != nil {\n\t\t\tvar currentCommand []string\n\t\t\tif group, ok := groupCommands[def.commandGroup]; ok {\n\t\t\t\tcurrentCommand = append(currentCommand, group.Use)\n\t\t\t}\n\t\t\tcurrentCommand = append(currentCommand, def.use)\n\t\t\tallCommands = append(allCommands, currentCommand)\n\t\t}\n\t}\n\tfor _, cmd := range cl.rawCommands {\n\t\tif cmd.cobraCommand.Use == \"proxy\" {\n\t\t\t// proxy will keep running until interrupted so it\n\t\t\t// cannot be used as is in e2e tests.\n\t\t\tcontinue\n\t\t}\n\t\tif mode == runtime.ModeController && cmd.supportController ||\n\t\t\tmode == runtime.ModeAgent && cmd.supportAgent {\n\t\t\tvar currentCommand []string\n\t\t\tif group, ok := groupCommands[cmd.commandGroup]; ok {\n\t\t\t\tcurrentCommand = append(currentCommand, group.Use)\n\t\t\t}\n\t\t\tcurrentCommand = append(currentCommand, strings.Split(cmd.cobraCommand.Use, \" \")[0])\n\t\t\tallCommands = append(allCommands, currentCommand)\n\t\t}\n\t}\n\treturn allCommands\n}", "func AllCmds() []string {\n\tvar ret []string\n\tfor k := range command.Commands {\n\t\tret = append(ret, k)\n\t}\n\tsort.Strings(ret)\n\treturn ret\n}", "func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {\n\tpdvTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tpdvTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdCreatePDV(cdc),\n\t\tGetCmdSignPDV(cdc),\n\t)...)\n\n\treturn pdvTxCmd\n}", "func CreateCommands(app *cli.Cli) {\n\n\t/* Functions to implement...\n\t/api/v1/go-kms/listkeys\n\t/api/v1/go-kms/createkey\n\t/api/v1/go-kms/generatedatakey\n\t/api/v1/go-kms/enablekey\n\t/api/v1/go-kms/disablekey\n\t/api/v1/go-kms/decrypt\n\t/api/v1/go-kms/encrypt*/\n\n\tapp.Command(\"keys\", \"Key functions\", func(commandCmd *cli.Cmd) {\n\t\tcommandCmd.Command(\"list\", \"List all available keys\", func(listKeysCmd *cli.Cmd) {\n\t\t\tlistKeysCmd.Action = func() {\n\n\t\t\t\t// List the key available...\n\t\t\t\tlistKeyRequest := kms.ListKeysRequest{}\n\n\t\t\t\tlistKeyResponse := &kms.ListKeysResponse{}\n\t\t\t\terr := Client.Do(\"POST\", \"/api/v1/go-kms/listkeys\", &listKeyRequest, listKeyResponse)\n\t\t\t\tif err != nil {\n\t\t\t\t\tExit(err.Error(), 1)\n\t\t\t\t}\n\n\t\t\t\tOutputMetadata(listKeyResponse.KeyMetadata)\n\t\t\t}\n\t\t})\n\t\tcommandCmd.Command(\"create\", \"Create a new key\", func(createKeyCmd *cli.Cmd) {\n\n\t\t\tdescription := createKeyCmd.StringOpt(\"d description\", \"\", \"Description for the new key\")\n\n\t\t\tcreateKeyCmd.Action = func() {\n\t\t\t\tcreateKeyRequest := kms.CreateKeyRequest{Description: *(description)}\n\n\t\t\t\tcreateKeyResponse := &kms.CreateKeyResponse{}\n\t\t\t\terr := Client.Do(\"POST\", \"/api/v1/go-kms/createkey\", &createKeyRequest, createKeyResponse)\n\t\t\t\tif err != nil {\n\t\t\t\t\tExit(err.Error(), 1)\n\t\t\t\t}\n\n\t\t\t\tOutputMetadata([]kms.KeyMetadata{createKeyResponse.KeyMetadata})\n\t\t\t}\n\t\t})\n\t\tcommandCmd.Command(\"disable\", \"Disable a key\", func(disableKeyCmd *cli.Cmd) {\n\n\t\t\tkeyID := disableKeyCmd.StringArg(\"KEYID\", \"\", \"The KeyID of the key to be disabled\")\n\n\t\t\tdisableKeyCmd.Action = func() {\n\t\t\t\tdisableKeyRequest := kms.DisableKeyRequest{KeyID: *(keyID)}\n\n\t\t\t\tdisableKeyResponse := &kms.DisableKeyResponse{}\n\t\t\t\terr := Client.Do(\"POST\", \"/api/v1/go-kms/disablekey\", &disableKeyRequest, disableKeyResponse)\n\t\t\t\tif err != nil {\n\t\t\t\t\tExit(err.Error(), 1)\n\t\t\t\t}\n\n\t\t\t\tOutputMetadata([]kms.KeyMetadata{disableKeyResponse.KeyMetadata})\n\n\t\t\t}\n\t\t})\n\t\tcommandCmd.Command(\"enable\", \"Enable a key\", func(enableKeyCmd *cli.Cmd) {\n\n\t\t\tkeyID := enableKeyCmd.StringArg(\"KEYID\", \"\", \"The KeyID of the key to be enabled\")\n\n\t\t\tenableKeyCmd.Action = func() {\n\t\t\t\tenableKeyRequest := kms.EnableKeyRequest{KeyID: *(keyID)}\n\n\t\t\t\tenableKeyResponse := &kms.EnableKeyResponse{}\n\t\t\t\terr := Client.Do(\"POST\", \"/api/v1/go-kms/enablekey\", &enableKeyRequest, enableKeyResponse)\n\t\t\t\tif err != nil {\n\t\t\t\t\tExit(err.Error(), 1)\n\t\t\t\t}\n\n\t\t\t\tOutputMetadata([]kms.KeyMetadata{enableKeyResponse.KeyMetadata})\n\t\t\t}\n\t\t})\n\n\t})\n}", "func (cli *CLI) GetCmdList() []string {\n\tvar list = cli.registerCmdList\n\tif cli.cmds != nil {\n\t\tfor cmd, _ := range cli.cmds {\n\t\t\tif alias, hasMk := cli.cmdMap[cmd]; hasMk {\n\t\t\t\tvar cmdList = []string{cmd}\n\t\t\t\tif v, isStr := alias.(string); isStr {\n\t\t\t\t\tcmdList = append(cmdList, v)\n\t\t\t\t\tcmd = strings.Join(cmdList, \", \")\n\t\t\t\t} else if v, isStrQue := alias.([]string); isStrQue {\n\t\t\t\t\tcmdList = append(cmdList, v...)\n\t\t\t\t\tcmd = strings.Join(cmdList, \", \")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlist = append(list, cmd)\n\t\t}\n\t}\n\treturn list\n}", "func (handler commandHandler) getCmds() cmdMap {\n\treturn handler.Cmds\n}", "func (handler commandHandler) getCmds() cmdMap {\n\treturn handler.Cmds\n}", "func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\t// return cli.GetTxCmd(cdc)\n\tpanic(\"need to add cli.GetTxCmd(cdc)\")\n}", "func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {\n\tpdvTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: fmt.Sprintf(\"%s transactions subcommands\", types.ModuleName),\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tpdvTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdSignPDV(cdc),\n\t)...)\n\n\treturn pdvTxCmd\n}", "func GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\tslashingTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Slashing transactions subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tslashingTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdUnjail(cdc),\n\t)...)\n\n\treturn slashingTxCmd\n}", "func (o GetAppTemplateContainerOutput) Commands() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GetAppTemplateContainer) []string { return v.Commands }).(pulumi.StringArrayOutput)\n}", "func (AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\treturn cli.GetTxCmd(cdc)\n}", "func GetTxCmd(storeKey string, cdc *codec.Codec) *cobra.Command {\n\tAuthorizationTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Msg authorization transactions subcommands\",\n\t\tLong: \"Authorize and revoke access to execute transactions on behalf of your address\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\tAuthorizationTxCmd.AddCommand(flags.PostCommands(\n\t\tGetCmdGrantAuthorization(cdc),\n\t\tGetCmdRevokeAuthorization(cdc),\n\t\tGetCmdSendAs(cdc),\n\t)...)\n\n\treturn AuthorizationTxCmd\n}", "func (AppModuleBasic) GetTxCmd(cdc *amino.Codec) *cobra.Command {\n\treturn client.GetTxCmd(cdc)\n}", "func (mc ModuleClient) GetTxCmd() *cobra.Command {\n\t// Group gov queries under a subcommand\n\tgovTxCmd := &cobra.Command{\n\t\tUse: \"gitService\",\n\t\tShort: \"GitService transaction commands\",\n\t}\n\n\tgovTxCmd.AddCommand(client.PostCommands(\n\t\tgitServiceCmd.GetCmdPushRefs(mc.moduleName, mc.cdc),\n\t)...)\n\tgovTxCmd.AddCommand(client.PostCommands(\n\t\tgitServiceCmd.GetCmdRemoveRepo(mc.moduleName, mc.cdc),\n\t)...)\n\n\treturn govTxCmd\n}", "func Commands(globalParams *command.GlobalParams) []*cobra.Command {\n\tcmd := dcaconfigcheck.MakeCommand(func() dcaconfigcheck.GlobalParams {\n\t\treturn dcaconfigcheck.GlobalParams{\n\t\t\tConfFilePath: globalParams.ConfFilePath,\n\t\t}\n\t})\n\n\treturn []*cobra.Command{cmd}\n}", "func (mc ModuleClient) GetTxCmd() *cobra.Command {\n\tassetsvcTxCmd := &cobra.Command{\n\t\tUse: \"assetservice\",\n\t\tShort: \"Assetservice transactions subcommands\",\n\t}\n\n\tassetsvcTxCmd.AddCommand(client.PostCommands(\n\t\tassetservicecmd.GetCmdBuyAsset(mc.cdc),\n\t\tassetservicecmd.GetCmdSetAsset(mc.cdc),\n\t)...)\n\n\treturn assetsvcTxCmd\n}", "func SubCommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"export\",\n\t\t\tUsage: \"Exports infrastructure file from IMCO\",\n\t\t\tAction: cmd.TemporaryArchiveExport,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"server-ids\",\n\t\t\t\t\tUsage: \"A list of comma separated server identifiers to be exported\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"server-array-ids\",\n\t\t\t\t\tUsage: \"A list of comma separated server array identifiers to be exported\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"filepath\",\n\t\t\t\t\tUsage: \"Path and file name to download infrastructure 'csar' file, i.e: --filename /folder-path/filename.csar\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"time, t\",\n\t\t\t\t\tUsage: \"Time lapse -seconds- for export status check\",\n\t\t\t\t\tValue: cmd.DefaultTimeLapseExportStatusCheck,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"import\",\n\t\t\tUsage: \"Imports infrastructure file on IMCO\",\n\t\t\tAction: cmd.TemporaryArchiveImport,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"filepath\",\n\t\t\t\t\tUsage: \"Path and file name to infrastructure 'csar' file\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"label\",\n\t\t\t\t\tUsage: \"New label name to be associated with infrastructure\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"time, t\",\n\t\t\t\t\tUsage: \"Time lapse -seconds- for import status check\",\n\t\t\t\t\tValue: cmd.DefaultTimeLapseImportStatusCheck,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (m *Device) GetCommands() (val map[string]Command, set bool) {\n\tif m.Commands == nil {\n\t\treturn\n\t}\n\n\treturn *m.Commands, true\n}", "func Commands() []cli.Command {\n\treturn []cli.Command{\n\t\tgenerate(),\n\t}\n}", "func (mc ModuleClient) GetTxCmd() *cobra.Command {\n\tagentTxCmd := &cobra.Command{\n\t\tUse: \"group\",\n\t\tShort: \"Agent transactions subcommands\",\n\t}\n\n\tagentTxCmd.AddCommand(client.PostCommands(\n\t\tagentcmd.GetCmdCreateGroup(mc.cdc),\n\t\tagentcmd.GetCmdApprove(mc.cdc),\n\t\tagentcmd.GetCmdUnapprove(mc.cdc),\n\t\tagentcmd.GetCmdTryExec(mc.cdc),\n\t\tagentcmd.GetCmdWithdraw(mc.cdc),\n\t)...)\n\n\treturn agentTxCmd\n}", "func GetQueryCmd(cdc *amino.Codec) *cobra.Command {\n\tqueryCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Querying commands for the currencies module\",\n\t}\n\n\tqueryCmd.AddCommand(\n\t\tsdkClient.GetCommands(\n\t\t\tcli.GetIssue(types.ModuleName, cdc),\n\t\t\tcli.GetCurrency(types.ModuleName, cdc),\n\t\t\tcli.GetCurrencies(types.ModuleName, cdc),\n\t\t\tcli.GetWithdraw(types.ModuleName, cdc),\n\t\t\tcli.GetWithdraws(types.ModuleName, cdc),\n\t\t)...)\n\n\treturn queryCmd\n}", "func GetTxCmd() *cobra.Command {\n\toracleTxCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Impermanent Loss transaction subcommands\",\n\t\tDisableFlagParsing: true,\n\t\tSuggestionsMinimumDistance: 2,\n\t\tRunE: client.ValidateCmd,\n\t}\n\n\toracleTxCmd.AddCommand([]*cobra.Command{\n\t\tGetCmdCreateStoploss(),\n\t\tGetCmdDeleteStoploss(),\n\t}...)\n\n\treturn oracleTxCmd\n}", "func Commands() []*cobra.Command {\n\treturn rootCmd.Commands()\n}", "func (b *Bot) GetMyCommands() (result axon.A, err error) {\n\tvar response interface{}\n\tif response, err = b.doGet(\"getMyCommands\"); err == nil {\n\t\tresult = response.([]interface{})\n\t}\n\treturn\n}", "func (am AppModuleBasic) GetTxCmd() *cobra.Command {\n\t// Append local TX cmd to this if required\n\treturn am.cosmosAppModule.GetTxCmd()\n}", "func (Module) GetModuleCommands() []*cli.Command {\n\treturn []*cli.Command{\n\t\t{\n\t\t\tName: \"bulkdownload\",\n\t\t\tUsage: \"Download multiple files from a list\",\n\t\t\tDescription: `Bulkdownload downloads all files from a list. \nYou can set how many files should be downloaded concurrently..`,\n\t\t\tCategory: categories.Web,\n\t\t\tAliases: []string{\"bd\"},\n\t\t\tAction: func(c *cli.Context) error {\n\t\t\t\tinput := utils.Input(c.String(\"input\"))\n\t\t\t\toutputDir := c.String(\"output\")\n\t\t\t\tconcurrentDownloads := c.Int(\"concurrent\")\n\n\t\t\t\tvar urls []string\n\n\t\t\t\tif strings.HasPrefix(input, `{\"Module\":[{\"Name\":`) {\n\t\t\t\t\tscheme := pipe.GetSchemeFromJSON(input)\n\t\t\t\t\turls = scheme.GetLastModule().Todo\n\t\t\t\t} else {\n\t\t\t\t\tvar err error\n\t\t\t\t\turls, err = readLines(input)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\twg.Add(len(urls))\n\n\t\t\t\tpterm.Info.Println(\"Downloading \" + pterm.LightMagenta(len(urls)) + \" files\")\n\n\t\t\t\tdownloadMultipleFiles(urls, outputDir, concurrentDownloads)\n\t\t\t\twg.Wait()\n\n\t\t\t\tmod := pipe.Module{\n\t\t\t\t\tName: c.Command.Name,\n\t\t\t\t}\n\t\t\t\tfor s, b := range successList {\n\t\t\t\t\tif b {\n\t\t\t\t\t\tmod.Files.Finished.Success = append(mod.Files.Finished.Success, s)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tmod.Files.Finished.Failed = append(mod.Files.Finished.Failed, s)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tpipe.AddModule(mod)\n\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\tFlags: []cli.Flag{\n\t\t\t\t&cli.StringFlag{\n\t\t\t\t\tName: \"input\",\n\t\t\t\t\tAliases: []string{\"i\"},\n\t\t\t\t\tUsage: \"load URLs from `FILE`\",\n\t\t\t\t},\n\t\t\t\t&cli.StringFlag{\n\t\t\t\t\tName: \"output\",\n\t\t\t\t\tAliases: []string{\"o\"},\n\t\t\t\t\tUsage: \"save the downloaded files to `DIR`\",\n\t\t\t\t\tDefaultText: \"current directory\",\n\t\t\t\t},\n\t\t\t\t&cli.IntFlag{\n\t\t\t\t\tName: \"concurrent\",\n\t\t\t\t\tAliases: []string{\"c\"},\n\t\t\t\t\tUsage: \"downloads `NUMBER` files concurrently\",\n\t\t\t\t\tValue: 3,\n\t\t\t\t},\n\t\t\t},\n\t\t\tExamples: []cli.Example{\n\t\t\t\t{\n\t\t\t\t\tShortDescription: \"Download all files from urls.txt, with 5 concurrent connections, to the current directory.\",\n\t\t\t\t\tUsage: \"dops bulkdownload -i urls.txt -c 5\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func AllCommands(offset int, limit int, dic *di.Container) (deviceCoreCommands []dtos.DeviceCoreCommand, err errors.EdgeX) {\n\t// retrieve device information through Metadata DeviceClient\n\tdc := V2Container.MetadataDeviceClientFrom(dic.Get)\n\tif dc == nil {\n\t\treturn deviceCoreCommands, errors.NewCommonEdgeX(errors.KindClientError, \"nil MetadataDeviceClient returned\", nil)\n\t}\n\tmultiDevicesResponse, err := dc.AllDevices(context.Background(), nil, offset, limit)\n\tif err != nil {\n\t\treturn deviceCoreCommands, errors.NewCommonEdgeXWrapper(err)\n\t}\n\n\t// retrieve device profile information through Metadata DeviceProfileClient\n\tdpc := V2Container.MetadataDeviceProfileClientFrom(dic.Get)\n\tif dpc == nil {\n\t\treturn deviceCoreCommands, errors.NewCommonEdgeX(errors.KindClientError, \"nil MetadataDeviceProfileClient returned\", nil)\n\t}\n\n\t// Prepare the url for command\n\tconfiguration := commandContainer.ConfigurationFrom(dic.Get)\n\tserviceUrl := configuration.Service.Url()\n\n\tdeviceCoreCommands = make([]dtos.DeviceCoreCommand, len(multiDevicesResponse.Devices))\n\tfor i, device := range multiDevicesResponse.Devices {\n\t\tdeviceProfileResponse, err := dpc.DeviceProfileByName(context.Background(), device.ProfileName)\n\t\tif err != nil {\n\t\t\treturn deviceCoreCommands, errors.NewCommonEdgeXWrapper(err)\n\t\t}\n\t\tcommands := make([]dtos.CoreCommand, len(deviceProfileResponse.Profile.CoreCommands))\n\t\tfor index, c := range deviceProfileResponse.Profile.CoreCommands {\n\t\t\tcommands[index] = dtos.CoreCommand{\n\t\t\t\tName: c.Name,\n\t\t\t\tGet: c.Get,\n\t\t\t\tSet: c.Set,\n\t\t\t\tUrl: serviceUrl,\n\t\t\t\tPath: fmt.Sprintf(\"%s/%s/%s/%s\", V2Routes.ApiDeviceRoute, V2Routes.Name, device.Name, c.Name),\n\t\t\t}\n\t\t}\n\t\tdeviceCoreCommands[i] = dtos.DeviceCoreCommand{\n\t\t\tDeviceName: device.Name,\n\t\t\tProfileName: device.ProfileName,\n\t\t\tCoreCommands: commands,\n\t\t}\n\t}\n\treturn deviceCoreCommands, nil\n}", "func Get() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"Gets CA certificate for SSH engine.\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tengineName, _ := cmd.Flags().GetString(\"engine\")\n\n\t\t\tapi, err := vault.NewAPI()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tpublicKey, err := controller.NewController(api).GetCACertificate(engineName)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tlog.Infoln(publicKey)\n\n\t\t\treturn nil\n\t\t},\n\t}\n\n\tcmd.Flags().String(\"engine\", vault.SSHEngineDefaultName, \"SSH engine path\")\n\n\treturn cmd\n}", "func (amb AppModuleBasic) GetTxCmd(cdc *codec.Codec) *cobra.Command {\n\treturn nil\n}", "func GetAllRawCommands() (commands []accessors.RawCommand, err error) {\n\tlog.Printf(\"Getting all commands.\")\n\turl := os.Getenv(\"CONFIGURATION_DATABASE_MICROSERVICE_ADDRESS\") + \"/devices/commands\"\n\terr = GetData(url, &commands)\n\n\tif err != nil {\n\t\tlog.Printf(\"Error: %s\", err.Error())\n\t\treturn\n\t}\n\n\tlog.Printf(\"Done.\")\n\treturn\n}", "func GetTxCmd(storeKey string, cdc *amino.Codec) *cobra.Command {\n\tdistTxCmd := &cobra.Command{\n\t\tUse: \"dist\",\n\t\tShort: \"Distribution transactions subcommands\",\n\t}\n\n\tdistTxCmd.AddCommand(client.PostCommands(\n\t\tGetCmdWithdrawRewards(cdc),\n\t\tGetCmdSetWithdrawAddr(cdc),\n\t)...)\n\n\treturn distTxCmd\n}", "func (o AppTemplateContainerOutput) Commands() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v AppTemplateContainer) []string { return v.Commands }).(pulumi.StringArrayOutput)\n}", "func Getcommand(text string, separ byte) (command []string, err error) {\n\ttext = strings.Trim(text, \" \")\n\tif text[0] != separ {\n\t\treturn nil, fmt.Errorf(\"Commands must start with: '%c' \", separ)\n\t}\n\ts := strings.Split(text, \" \")\n\treturn s, nil\n}", "func (w *ConfigModule) Commands() []Command {\n\treturn []Command{\n\t\t&setConfigCommand{},\n\t\t&getConfigCommand{},\n\t\t&setupCommand{},\n\t\t&setMemberRole{},\n\t}\n}", "func getTechConfigsCommands(serverId string, setM2ForMaven bool, data *CiSetupData) []string {\n\tvar configs []string\n\tswitch data.BuiltTechnology.Type {\n\tcase Maven:\n\t\tif setM2ForMaven {\n\t\t\tconfigs = append(configs, m2pathCmd)\n\t\t}\n\t\tconfigs = append(configs, getMavenConfigCmd(serverId, data.BuiltTechnology.VirtualRepo))\n\n\tcase Gradle:\n\t\tconfigs = append(configs, getBuildToolConfigCmd(gradleConfigCmdName, serverId, data.BuiltTechnology.VirtualRepo))\n\n\tcase Npm:\n\t\tconfigs = append(configs, getBuildToolConfigCmd(npmConfigCmdName, serverId, data.BuiltTechnology.VirtualRepo))\n\n\t}\n\treturn configs\n}", "func (c *Completed) Commands() []string {\n\treturn c.cs.s\n}", "func GetCmd(opts *KubectlOpts) []string {\n\tcmd := []string{\"kubectl\", \"apply\", \"-f\", \"-\"}\n\n\tif opts.Context != \"\" {\n\t\tcmd = append(cmd, fmt.Sprintf(`--context=%s`, opts.Context))\n\t}\n\tif opts.Namespace != \"\" {\n\t\tcmd = append(cmd, fmt.Sprintf(`--namespace=%s`, opts.Namespace))\n\t}\n\n\treturn cmd\n}", "func NewCommands(kt kt.CliInterface, action ActionInterface, options *options.DaemonOptions) []cli.Command {\n\treturn []cli.Command{\n\t\tnewConnectCommand(kt, options, action),\n\t\tnewExchangeCommand(kt, options, action),\n\t\tnewMeshCommand(kt, options, action),\n\t\tnewProvideCommand(kt, options, action),\n\t\tnewCleanCommand(kt, options, action),\n\t\tnewDashboardCommand(kt, options, action),\n\t}\n}", "func (AppModuleBasic) GetTxCmd() *cobra.Command {\n\treturn cli.GetTxCmd()\n}", "func (b AppModuleBasic) GetTxCmd() *cobra.Command {\n\t// return cli.NewTxCmd()\n\treturn nil\n}", "func main() {\n\tfmt.Println(getCommandsFromFile(\"resources/not_enough_lines\"))\n\tfmt.Println(getCommandsFromFile(\"resources/version_not_a_number\"))\n\tfmt.Println(getCommandsFromFile(\"resources/invalid_json\"))\n\tfmt.Println(getCommandsFromFile(\"resources/incorrect_version\"))\n\tfmt.Println(getCommandsFromFile(\"resources/incorrect_mode\"))\n\tfmt.Println(getCommandsFromFile(\"resources/valid\"))\n}", "func (b *Bot) getCommands() []BotCommandType {\n\tbcts := make([]BotCommandType, 0)\n\tfor _, bct := range b.Commands {\n\t\tif bct.isRunning() {\n\t\t\tbcts = append(bcts, bct)\n\t\t}\n\t}\n\treturn bcts\n}", "func SubCommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"templates\",\n\t\t\tUsage: \"Provides information about CAT\",\n\t\t\tSubcommands: append(templates.SubCommands()),\n\t\t},\n\t\t{\n\t\t\tName: \"deployments\",\n\t\t\tUsage: \"Provides information about CAT deployments\",\n\t\t\tSubcommands: append(deployments.SubCommands()),\n\t\t},\n\t}\n}", "func GetCommand() *cobra.Command {\n\treturn powerCmd\n}", "func buildCLICommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"run\",\n\t\t\tUsage: \"runs your test suites\",\n\t\t\tAction: runAction,\n\t\t},\n\t\t{\n\t\t\tName: \"verify\",\n\t\t\tUsage: \"verify an api-check file\",\n\t\t\tAction: verifyAction,\n\t\t},\n\t\t{\n\t\t\tName: \"generate\",\n\t\t\tAliases: []string{\"gen\"},\n\t\t\tUsage: \"generate a skeleton api-check file\",\n\t\t\tAction: generateAction,\n\t\t},\n\t}\n}", "func (container *Container) getCommandLine(projectName string, runningPods rkt.Pods, logger *log.Logger) ([]string, error) {\n\t// generate the different components\n\tcommand := make([]string, 0)\n\n\t// get the appName\n\tappName, err := rkt.GetAppName(projectName, container.Name)\n\tif err != nil {\n\t\treturn command, err\n\t}\n\tappNameLine := fmt.Sprintf(\"--name=%s\", appName)\n\n\t// generate environment strings\n\tenvArray := make([]string, 0)\n\tfor varName, varValue := range container.Environment {\n\t\tenvArray = append(envArray, fmt.Sprintf(\"--environment=%s=%s\", varName, varValue))\n\t}\n\n\t// exec string\n\texecArray := make([]string, 0)\n\tif container.Exec != \"\" {\n\t\texec_parts := util.ShellSplit(container.Exec)\n\n\t\tif len(exec_parts) > 0 {\n\t\t\t// first prime our array\n\t\t\texecArray = append(execArray, \"--exec\")\n\t\t\t// split our string into parts\n\t\t\texecArray = append(execArray, exec_parts[0])\n\t\t}\n\t\t// if there is more than one part the rkt command requires that other compoments come after a double hyphen\n\t\tif len(exec_parts) > 1 {\n\t\t\texecArray = append(execArray, \"--\")\n\t\t\texecArray = append(execArray, exec_parts[1:]...)\n\t\t}\n\t}\n\n\t// mount strings\n\tmountArray := make([]string, 0)\n\tfor _, mount := range container.Mounts {\n\t\tmountArray = append(mountArray, mount.GenerateCommandLine()...)\n\t}\n\n\tdepIPMap, err := container.GetDepChainIPs(projectName, runningPods, logger)\n\tif err != nil {\n\t\treturn command, err\n\t}\n\n\thostsArray := make([]string, 0)\n\tfor name, IPs := range depIPMap {\n\t\tfor _, IP := range IPs {\n\t\t\thostsArray = append(hostsArray, fmt.Sprintf(\"--hosts-entry=%s=%s\", IP, name))\n\t\t}\n\t}\n\n\t// create the hostname\n\thostnameLine := fmt.Sprintf(\"--hostname=%s\", container.Name)\n\n\t// combine our command parts\n\tcommand = append(command, container.Image)\n\tcommand = append(command, hostnameLine)\n\tcommand = append(command, envArray...)\n\tcommand = append(command, mountArray...)\n\tcommand = append(command, hostsArray...)\n\tcommand = append(command, appNameLine)\n\tcommand = append(command, execArray...)\n\n\treturn command, nil\n}", "func (AppModuleBasic) GetTxCmd() *cobra.Command {\n\treturn cli.NewTxCmd()\n}", "func (AppModuleBasic) GetTxCmd() *cobra.Command {\n\treturn cli.NewTxCmd()\n}", "func (AppModuleBasic) GetTxCmd() *cobra.Command {\n\treturn cli.NewTxCmd()\n}", "func SubCommands() []cli.Command {\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"list\",\n\t\t\tUsage: \"Lists all existing node pools in a cluster\",\n\t\t\tAction: cmd.NodePoolList,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Cluster Id\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"show\",\n\t\t\tUsage: \"Shows information about the node pool identified by the given id\",\n\t\t\tAction: cmd.NodePoolShow,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Node pool Id\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"create\",\n\t\t\tUsage: \"Creates a new node pool\",\n\t\t\tAction: cmd.NodePoolCreate,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Cluster Id\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"name\",\n\t\t\t\t\tUsage: \"Logical name of the node pool\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"subnet-id\",\n\t\t\t\t\tUsage: \"Identifier of the subnet where this node pool is deployed\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"node-pool-plan-id\",\n\t\t\t\t\tUsage: \"Identifier of the node pool plan that this node pool is based\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"cpu-type\",\n\t\t\t\t\tUsage: \"Type of CPU each node of the node pools will have. \" +\n\t\t\t\t\t\t\"Can be nil only if the node pool plan does not have any cpu types\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"disk-size\",\n\t\t\t\t\tUsage: \"Size of the disk each node of the node pool will have, expressed in Gigabytes (GB)\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"min-nodes\",\n\t\t\t\t\tUsage: \"Minimum number of nodes the node pool will have\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"max-nodes\",\n\t\t\t\t\tUsage: \"Maximum number of nodes the node pool will have\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"desired-nodes\",\n\t\t\t\t\tUsage: \"Amount of nodes the node pool will tend to have if the node pool does not have autoscaling\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"pods-per-node\",\n\t\t\t\t\tUsage: \"Amount of pods each node of the node pool will have if the node pool plan supports it\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"update\",\n\t\t\tUsage: \"Updates an existing node pool identified by the given id\",\n\t\t\tAction: cmd.NodePoolUpdate,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Node pool Id\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"name\",\n\t\t\t\t\tUsage: \"Logical name of the node pool\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"min-nodes\",\n\t\t\t\t\tUsage: \"Minimum number of nodes the node pool will have\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"max-nodes\",\n\t\t\t\t\tUsage: \"Maximum number of nodes the node pool will have\",\n\t\t\t\t},\n\t\t\t\tcli.IntFlag{\n\t\t\t\t\tName: \"desired-nodes\",\n\t\t\t\t\tUsage: \"Amount of nodes the node pool will tend to have if the node pool does not have autoscaling\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"delete\",\n\t\t\tUsage: \"Deletes a node pool\",\n\t\t\tAction: cmd.NodePoolDelete,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Node pool Id\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"retry\",\n\t\t\tUsage: \"Retries the application of node pool identified by the given id\",\n\t\t\tAction: cmd.NodePoolRetry,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Node pool Id\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tName: \"show-plan\",\n\t\t\tUsage: \"Shows information about a specific node pool plan identified by the given id\",\n\t\t\tAction: cmd.NodePoolPlanShow,\n\t\t\tFlags: []cli.Flag{\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"id\",\n\t\t\t\t\tUsage: \"Node pool plan Id\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (mc ModuleClient) GetQueryCmd() *cobra.Command {\n\tstakingQueryCmd := &cobra.Command{\n\t\tUse: types.ModuleName,\n\t\tShort: \"Querying commands for the staking module\",\n\t}\n\n\tstakingQueryCmd.AddCommand(client.GetCommands(\n\t\tstakingcli.GetCmdQueryDelegation(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryDelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryUnbondingDelegation(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryUnbondingDelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryRedelegation(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryRedelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryValidator(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryValidators(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryValidatorDelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryValidatorUnbondingDelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryValidatorRedelegations(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryParams(mc.storeKey, mc.cdc),\n\t\tstakingcli.GetCmdQueryPool(mc.storeKey, mc.cdc))...)\n\n\treturn stakingQueryCmd\n\n}", "func (lbbft *LBBFTCore) GetProposeCommands(timeout bool) *([]data.Command) {\n\n\tvar batch []data.Command\n\n\tif timeout { // timeout的时候,不管够不够batch都要发起共识。\n\t\tbatch = lbbft.cmdCache.RetriveFirst(lbbft.Config.BatchSize)\n\t} else {\n\t\tbatch = lbbft.cmdCache.RetriveExactlyFirst(lbbft.Config.BatchSize)\n\t}\n\n\treturn &batch\n}", "func (bot *Bot) GetMyCommands() (cmds []Command, err error) {\n\t_, resBody, err := bot.client.Get(methodGetMyCommands, nil, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetMyCommands: %w\", err)\n\t}\n\n\tres := &response{\n\t\tResult: cmds,\n\t}\n\terr = res.unpack(resBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetMyCommands: %w\", err)\n\t}\n\n\treturn cmds, nil\n}", "func (b *BotInfo) GetCommands() (value []BotCommand) {\n\tif b == nil {\n\t\treturn\n\t}\n\treturn b.Commands\n}", "func getCommandsDBS() []cli.Command {\n\tdbFilterFlags := newCliFlags(option{\n\t\tDatabases: modeFlagMulti,\n\t\tExcludeDatabases: modeFlagMulti,\n\t\tEngines: modeFlagMulti,\n\t\tTags: modeFlagMulti,\n\t\tExcludeTags: modeFlagMulti,\n\t})\n\tflagsQuery := flagsForQuery(dbFilterFlags.Flags()...)\n\treturn []cli.Command{\n\t\tcli.Command{\n\t\t\tName: \"ping\",\n\t\t\tUsage: \"ping remote databases\",\n\t\t\tFlags: flagsQuery,\n\t\t\tAction: commonActionDBS(dbFilterFlags, \"ping\", handlersrdb.PingHandler, false,\n\t\t\t\tnil,\n\t\t\t\tmuxActionTriggers(handlersrdb.PrintStatistic),\n\t\t\t\tmuxActionTriggers(handlersrdb.PrintStatistic)),\n\t\t},\n\t\tcli.Command{\n\t\t\tName: \"select\",\n\t\t\tUsage: \"select from remote databases\",\n\t\t\tFlags: append(flagsQuery,\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName: \"fit\",\n\t\t\t\t\tUsage: \"use for fit table by width window of terminal\",\n\t\t\t\t},\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName: \"fitcolumns\",\n\t\t\t\t\tUsage: \"use for auto width columns by contents\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"border\",\n\t\t\t\t\tUsage: \"set type of border table: Thin,Double,Simple or None. Default:Thin\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"sepalias\",\n\t\t\t\t\tUsage: \"separator alias for output raw. default ': '\",\n\t\t\t\t},\n\t\t\t\tcli.StringFlag{\n\t\t\t\t\tName: \"indent\",\n\t\t\t\t\tUsage: \"indent output for format:xml,json. Default xml:4 spaces; json:\\\\t\",\n\t\t\t\t}),\n\t\t\tAction: commonActionDBS(dbFilterFlags, \"select\", handlersrdb.Select, true,\n\t\t\t\thandlersrdb.SelectBefore,\n\t\t\t\tmuxActionTriggers(handlersrdb.SelectAfter, handlersrdb.PrintStatisticQuery, handlersrdb.PrintStatistic, handlersrdb.WriteRetryFile),\n\t\t\t\tmuxActionTriggers(handlersrdb.SelectError, handlersrdb.PrintStatisticQuery, handlersrdb.PrintStatistic, handlersrdb.WriteRetryFile)),\n\t\t},\n\t\tcli.Command{\n\t\t\tName: \"exec\",\n\t\t\tUsage: \"execute sql command on the remote databases\",\n\t\t\tFlags: append(flagsQuery,\n\t\t\t\tcli.BoolFlag{\n\t\t\t\t\tName: \"commit\",\n\t\t\t\t\tUsage: \"Use flag for commit the transaction. Default: false(rollback)\",\n\t\t\t\t},\n\t\t\t),\n\t\t\tAction: commonActionDBS(dbFilterFlags, \"exec\", handlersrdb.Exec, true,\n\t\t\t\tnil,\n\t\t\t\tmuxActionTriggers(handlersrdb.PrintStatisticQuery, handlersrdb.PrintStatistic, handlersrdb.WriteRetryFile),\n\t\t\t\tmuxActionTriggers(handlersrdb.PrintStatisticQuery, handlersrdb.PrintStatistic, handlersrdb.WriteRetryFile)),\n\t\t},\n\t}\n}", "func (h *HyperCommand) Commands() []*cobra.Command {\n\treturn h.cmds\n}", "func Commands(globalParams *command.GlobalParams) []*cobra.Command {\n\tcmd := workloadlist.MakeCommand(func() workloadlist.GlobalParams {\n\t\treturn workloadlist.GlobalParams{\n\t\t\tConfFilePath: globalParams.ConfFilePath,\n\t\t\tConfigName: command.ConfigName,\n\t\t\tLoggerName: command.LoggerName,\n\t\t}\n\t})\n\n\treturn []*cobra.Command{cmd}\n}", "func getKVMsCmd(params *Parameters) *subcommands.Command {\n\treturn &subcommands.Command{\n\t\tUsageLine: \"get-kvms [-name <name>]... [-vlan <id>]... [-plat <platform>]... [-rack <rack>]... [-dc <datacenter>]... [-mac <mac address>]... [-ip <ip address>]... [-state <state>]...\",\n\t\tShortDesc: \"retrieves KVMs\",\n\t\tLongDesc: \"Retrieves KVMs matching the given filters, or all KVMs if filters are omitted.\\n\\nExample to get all KVMs:\\ncrimson get-kvms\\nExample to get KVMs in rack xx1:\\ncrimson get-kvms -rack xx1\",\n\t\tCommandRun: func() subcommands.CommandRun {\n\t\t\tcmd := &GetKVMsCmd{}\n\t\t\tcmd.Initialize(params)\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.Names), \"name\", \"Name of a KVM to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.Int64Slice(&cmd.req.Vlans), \"vlan\", \"ID of a VLAN to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.Platforms), \"plat\", \"Name of a platform to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.Racks), \"rack\", \"Name of a rack to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.Datacenters), \"dc\", \"Name of a datacenter to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.MacAddresses), \"mac\", \"MAC address to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(flag.StringSlice(&cmd.req.Ipv4S), \"ip\", \"IPv4 address to filter by. Can be specified multiple times.\")\n\t\t\tcmd.Flags.Var(StateSliceFlag(&cmd.req.States), \"state\", \"State to filter by. Can be specified multiple times.\")\n\t\t\treturn cmd\n\t\t},\n\t}\n}", "func getAvailableCommands() (map[string]string, error) {\n\n\t// Check if run.yaml exists\n\tfile := \"run.yaml\"\n\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\t// If run.yaml does not exit, check for run.yml\n\t\tfile = \"run.yml\"\n\t\tif _, err := os.Stat(file); os.IsNotExist(err) {\n\t\t\treturn nil, errors.New(\"unable to find \\\"run.yaml\\\" in the current directory\")\n\t\t}\n\t}\n\n\t// Read run.yaml\n\tdata, err := ioutil.ReadFile(file)\n\tif err != nil {\n\t\treturn nil, errors.New(\"unable to read \\\"run.yaml\\\"\")\n\t}\n\n\t// Parse run.yaml\n\tcommands := make(map[string]string)\n\tif err := yaml.Unmarshal(data, &commands); err != nil {\n\t\treturn nil, errors.New(\"unable to parse \\\"run.yaml\\\"\")\n\t}\n\n\t// Returned parsed commands\n\treturn commands, nil\n}", "func newGetCmd(out io.Writer) *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"get\",\n\t\tShort: \"The command to get choerodon resource\",\n\t\tLong: `The command to get choerodon resource.such as organization, project, app, instance.`,\n\t\tRun: func(cmd *cobra.Command, args []string) {\n\t\t\tc7nclient.InitClient(&clientConfig, &clientPlatformConfig)\n\t\t\terror := c7nclient.Client.CheckIsLogin()\n\t\t\tif error != nil {\n\t\t\t\tfmt.Println(error)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif len(args) > 0 {\n\t\t\t\tfmt.Printf(\"don't have the resource %s, you can user c7nctl get --help to see the resource you can use!\", args[0])\n\t\t\t} else {\n\t\t\t\tcmd.Help()\n\t\t\t}\n\t\t},\n\t}\n\n\tcmd.AddCommand(newGetEnvCmd(out))\n\tcmd.AddCommand(newGetInstanceCmd(out))\n\tcmd.AddCommand(newGetProCmd(out))\n\tcmd.AddCommand(newGetOrgCmd(out))\n\tcmd.AddCommand(newGetServiceCmd(out))\n\tcmd.AddCommand(newGetIngressCmd(out))\n\tcmd.AddCommand(NewGetAppVersionCmd(out))\n\tcmd.AddCommand(newGetAppCmd(out))\n\tcmd.AddCommand(newGetClusterNodeCmd(out))\n\tcmd.AddCommand(newGetClusterCmd(out))\n\tcmd.AddCommand(newGetValueCmd(out))\n\tcmd.AddCommand(newGetCertCmd(out))\n\tcmd.AddCommand(newGetConfigMapCmd(out))\n\tcmd.AddCommand(newGetSecretCmd(out))\n\tcmd.AddCommand(newGetCustomCmd(out))\n\tcmd.AddCommand(newGetPvcCmd(out))\n\tcmd.AddCommand(newGetPvCmd(out))\n\n\treturn cmd\n}", "func GetDeploymentsCommand() cli.Command {\n\tcommand := cli.Command{\n\t\tName: \"deployment\",\n\t\tUsage: \"options for deployment\",\n\t\tSubcommands: []cli.Command{\n\t\t\t{\n\t\t\t\tName: \"list\",\n\t\t\t\tUsage: \"Lists all the deployments\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"[Deprecated] List the current deployment.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := listDeployments(c, os.Stdout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"show\",\n\t\t\t\tUsage: \"Show deployment info\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Show detailed information about the current deployment.\\n\" +\n\t\t\t\t\t\" Requires system administrator access,\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := showDeployment(c, os.Stdout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"list-hosts\",\n\t\t\t\tUsage: \"Lists all ESXi hosts\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"List information about all ESXi hosts used in the deployment.\\n\" +\n\t\t\t\t\t\" For each host, the ID, the current state, the IP, and the type (MGMT and/or CLOUD)\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := listDeploymentHosts(c, os.Stdout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"list-vms\",\n\t\t\t\tUsage: \"Lists all VMs\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"List all VMs associated with all tenants and projects.\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := listDeploymentVms(c, os.Stdout)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"enable-cluster-type\",\n\t\t\t\tUsage: \"Enable cluster type for deployment\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Enable a cluster type (e.g. Kubernetes) and specify the image to be used\\n\" +\n\t\t\t\t\t\" when creating the cluster.\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\tName: \"type, k\",\n\t\t\t\t\t\tUsage: \"Cluster type (accepted values are KUBERNETES, MESOS, or SWARM)\",\n\t\t\t\t\t},\n\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\tName: \"image-id, i\",\n\t\t\t\t\t\tUsage: \"ID of the cluster image\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := enableClusterType(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"disable-cluster-type\",\n\t\t\t\tUsage: \"Disable cluster type for deployment\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Disable a cluster type (e.g. Kubernetes). Users will no longer be able\\n\" +\n\t\t\t\t\t\" to deploy clusters of that type, but existing clusters will be unaffected.\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\tName: \"type, k\",\n\t\t\t\t\t\tUsage: \"Cluster type (accepted values are KUBERNETES, MESOS, or SWARM)\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := disableClusterType(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"update-image-datastores\",\n\t\t\t\tUsage: \"Updates the list of image datastores\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Update the list of allowed image datastores.\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\tName: \"datastores, d\",\n\t\t\t\t\t\tUsage: \"Comma separated name of datastore names\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := updateImageDatastores(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"sync-hosts-config\",\n\t\t\t\tUsage: \"Synchronizes hosts configurations\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := syncHostsConfig(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"pause\",\n\t\t\t\tUsage: \"Pause system under the deployment\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Pause Photon Controller. All incoming requests that modify the system\\n\" +\n\t\t\t\t\t\" state (other than resume) will be refused. This implies pause-background-states\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := pauseSystem(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"pause-background-tasks\",\n\t\t\t\tUsage: \"Pause background tasks\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Pause all background tasks in Photon Controller, such as image replication.\" +\n\t\t\t\t\t\" Incoming requests from users will continue to work\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := pauseBackgroundTasks(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"resume\",\n\t\t\t\tUsage: \"Resume system under the deployment\",\n\t\t\t\tArgsUsage: \" \",\n\t\t\t\tDescription: \"Resume Photon Controller after it has been paused.\\n\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := resumeSystem(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"set-security-groups\",\n\t\t\t\tUsage: \"Set security groups for a deployment\",\n\t\t\t\tArgsUsage: \"<security-groups>\",\n\t\t\t\tDescription: \"Provide the list of Lightwave groups that contain the people who are\\n\" +\n\t\t\t\t\t\" allowed to be system administrators. Be careful: providing the wrong group could remove\\n\" +\n\t\t\t\t\t\" your access.\" +\n\t\t\t\t\t\" Requires system administrator access.\",\n\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\terr := setDeploymentSecurityGroups(c)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tName: \"migration\",\n\t\t\t\tUsage: \"migrates state and hosts between photon controller deployments\",\n\t\t\t\tSubcommands: []cli.Command{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"prepare\",\n\t\t\t\t\t\tUsage: \"initializes the migration\",\n\t\t\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\t\t\tName: \"endpoint, e\",\n\t\t\t\t\t\t\t\tUsage: \"API endpoint of the old management plane\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\t\t\terr := deploymentMigrationPrepare(c)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"finalize\",\n\t\t\t\t\t\tUsage: \"finalizes the migration\",\n\t\t\t\t\t\tFlags: []cli.Flag{\n\t\t\t\t\t\t\tcli.StringFlag{\n\t\t\t\t\t\t\t\tName: \"endpoint, e\",\n\t\t\t\t\t\t\t\tUsage: \"API endpoint of the old management plane\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\t\t\terr := deploymentMigrationFinalize(c)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"status\",\n\t\t\t\t\t\tUsage: \"shows the status of the current migration\",\n\t\t\t\t\t\tAction: func(c *cli.Context) {\n\t\t\t\t\t\t\terr := showMigrationStatus(c)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\tlog.Fatal(\"Error: \", err)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn command\n}", "func InitCommands() []*cobra.Command {\n\t//init all sub resource command\n\tlistCmd.AddCommand(listBusinessCmd())\n\tlistCmd.AddCommand(listShardingDBCmd())\n\tlistCmd.AddCommand(listAppCmd())\n\tlistCmd.AddCommand(listClusterCmd())\n\tlistCmd.AddCommand(listZoneCmd())\n\tlistCmd.AddCommand(listConfigSetCmd())\n\tlistCmd.AddCommand(listMultiCommitCmd())\n\tlistCmd.AddCommand(listStrategyCmd())\n\tlistCmd.AddCommand(listMultiReleaseCmd())\n\tlistCmd.AddCommand(listAppInstCmd())\n\treturn []*cobra.Command{listCmd}\n}", "func NewCommands() []cli.Command {\n\tvar cfgFlags = []cli.Flag{\n\t\tcli.StringFlag{Name: \"config-path\"},\n\t\tcli.BoolFlag{Name: \"debug, d\"},\n\t}\n\tcfgFlags = append(cfgFlags, options.Network...)\n\tvar cfgWithCountFlags = make([]cli.Flag, len(cfgFlags))\n\tcopy(cfgWithCountFlags, cfgFlags)\n\tcfgWithCountFlags = append(cfgWithCountFlags,\n\t\tcli.UintFlag{\n\t\t\tName: \"count, c\",\n\t\t\tUsage: \"number of blocks to be processed (default or 0: all chain)\",\n\t\t},\n\t)\n\tvar cfgCountOutFlags = make([]cli.Flag, len(cfgWithCountFlags))\n\tcopy(cfgCountOutFlags, cfgWithCountFlags)\n\tcfgCountOutFlags = append(cfgCountOutFlags,\n\t\tcli.UintFlag{\n\t\t\tName: \"start, s\",\n\t\t\tUsage: \"block number to start from (default: 0)\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"out, o\",\n\t\t\tUsage: \"Output file (stdout if not given)\",\n\t\t},\n\t)\n\tvar cfgCountInFlags = make([]cli.Flag, len(cfgWithCountFlags))\n\tcopy(cfgCountInFlags, cfgWithCountFlags)\n\tcfgCountInFlags = append(cfgCountInFlags,\n\t\tcli.StringFlag{\n\t\t\tName: \"in, i\",\n\t\t\tUsage: \"Input file (stdin if not given)\",\n\t\t},\n\t\tcli.StringFlag{\n\t\t\tName: \"dump\",\n\t\t\tUsage: \"directory for storing JSON dumps\",\n\t\t},\n\t\tcli.BoolFlag{\n\t\t\tName: \"incremental, n\",\n\t\t\tUsage: \"use if dump is incremental\",\n\t\t},\n\t)\n\treturn []cli.Command{\n\t\t{\n\t\t\tName: \"node\",\n\t\t\tUsage: \"start a NEO node\",\n\t\t\tAction: startServer,\n\t\t\tFlags: cfgFlags,\n\t\t},\n\t\t{\n\t\t\tName: \"db\",\n\t\t\tUsage: \"database manipulations\",\n\t\t\tSubcommands: []cli.Command{\n\t\t\t\t{\n\t\t\t\t\tName: \"dump\",\n\t\t\t\t\tUsage: \"dump blocks (starting with block #1) to the file\",\n\t\t\t\t\tAction: dumpDB,\n\t\t\t\t\tFlags: cfgCountOutFlags,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"restore\",\n\t\t\t\t\tUsage: \"restore blocks from the file\",\n\t\t\t\t\tAction: restoreDB,\n\t\t\t\t\tFlags: cfgCountInFlags,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}", "func (o GroupInitContainerOutput) Commands() pulumi.StringArrayOutput {\n\treturn o.ApplyT(func(v GroupInitContainer) []string { return v.Commands }).(pulumi.StringArrayOutput)\n}" ]
[ "0.76198924", "0.721652", "0.70294607", "0.7025578", "0.696028", "0.68951416", "0.68878794", "0.68476355", "0.6826152", "0.6761924", "0.6732814", "0.6677199", "0.6621453", "0.66052717", "0.6602549", "0.65582794", "0.6551299", "0.6538137", "0.6523756", "0.6487545", "0.6456644", "0.643507", "0.64270043", "0.6365241", "0.63587415", "0.63402045", "0.6320374", "0.6301017", "0.62955135", "0.6256494", "0.62480193", "0.62280524", "0.6218664", "0.6179798", "0.6171765", "0.61712855", "0.61674935", "0.6160352", "0.6158928", "0.61471844", "0.61376435", "0.61376435", "0.61365515", "0.61199355", "0.6114716", "0.61041164", "0.61020195", "0.60814863", "0.60750526", "0.60747224", "0.6036848", "0.6036385", "0.60342443", "0.59877676", "0.5973766", "0.5968305", "0.59677", "0.59449106", "0.593562", "0.5916361", "0.5899768", "0.5897721", "0.5887612", "0.58764684", "0.5876279", "0.586326", "0.58595896", "0.58563983", "0.58520687", "0.58271796", "0.5822884", "0.5821591", "0.58183396", "0.5808105", "0.57994306", "0.5796475", "0.57829016", "0.5779674", "0.577687", "0.5767774", "0.5764279", "0.57359934", "0.57345885", "0.57345885", "0.57345885", "0.5707796", "0.5702271", "0.56804127", "0.567499", "0.56743723", "0.5662122", "0.56608784", "0.5656116", "0.5653062", "0.5652733", "0.56517446", "0.5651595", "0.5649463", "0.5645844", "0.56395113" ]
0.83512974
0
GetName should be overridden to return the name of your collection
func (b *Base) GetName() string { panic("must override Name() on Base model") return "base" }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *collection) Name() string {\n\treturn c.name\n}", "func (iteration Iteration) GetName() string {\n\treturn iteration.GetCollectionName()\n}", "func (workItemType WorkItemType) GetName() string {\n return workItemType.GetCollectionName()\n}", "func (c *Collection) Name() string {\n\treturn c.collectionName\n}", "func (r *staticCollection) Name() string {\n\treturn r.name\n}", "func GetCollectionName(name string) string {\n\t// pluralize the name\n\tname = inflect.Pluralize(name)\n\n\t//split name into string array\n\tsplittedName := strings.Split(name, \"\")\n\n\t//uppercase first character and assign back\n\tsplittedName[0] = strings.ToLower(splittedName[0])\n\n\t//merge string array\n\tname = strings.Join(splittedName, \"\")\n\treturn name\n\n}", "func (workItemType WorkItemType) GetCollectionName() string {\n return WorkItemTypeName\n}", "func (iteration Iteration) GetCollectionName() string {\n\treturn IterationName\n}", "func (c *vertexCollection) Name() string {\n\treturn c.name\n}", "func (s UserSet) Name() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"Name\", \"name\")).(string)\n\treturn res\n}", "func (s UserSet) NameGet() string {\n\tres := s.Collection().Call(\"NameGet\")\n\tresTyped, _ := res.(string)\n\treturn resTyped\n}", "func (c FieldsCollection) Name() *models.Field {\n\treturn c.MustGet(\"Name\")\n}", "func (x *SingleCollection) NameOf() string {\n\treturn x.String()\n}", "func (a Admin) CollectionName() string {\n\treturn \"admins\"\n}", "func (x *UserCollection) String() string {\n\treturn x.NameOf()\n}", "func (o Mongo) GetName() string {\n\treturn \"Mongo\"\n}", "func getCollectionName(ctx contractapi.TransactionContextInterface) (string, error) {\n\n\t// Get the MSP ID of submitting client identity\n\tclientMSPID, err := ctx.GetClientIdentity().GetMSPID()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get verified MSPID: %v\", err)\n\t}\n\n\t// Create the collection name\n\torgCollection := \"_implicit_org_\" + clientMSPID\n\n\treturn orgCollection, nil\n}", "func (o DataCollectionRuleOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DataCollectionRule) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (x *SingleCollection) String() string {\n\tif x.name != \"\" {\n\t\treturn \"rest-dal-single-single-\" + x.name\n\t}\n\treturn \"rest-dal-single-single\"\n}", "func (set Set) Name() string { return set.name }", "func (obj *ObjectBase) GetName() string {\n\treturn obj.name\n}", "func (m Service) GetCollection() string {\n\treturn ServiceCollectionName\n}", "func (o FirewallNetworkRuleCollectionOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *FirewallNetworkRuleCollection) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (c MethodsCollection) NameGet() pNameGet {\n\treturn pNameGet{\n\t\tMethod: c.MustGet(\"NameGet\"),\n\t}\n}", "func (fastuser *FastUser) CollectionName() string {\n\treturn \"fastuseraccount\"\n}", "func (m *ManagementTemplateStepTenantSummary) GetManagementTemplateCollectionDisplayName()(*string) {\n val, err := m.GetBackingStore().Get(\"managementTemplateCollectionDisplayName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (o GoogleDatastoreAdminV1IndexedPropertyOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleDatastoreAdminV1IndexedProperty) string { return v.Name }).(pulumi.StringOutput)\n}", "func (ds *Datasource) GetName() string {\n\treturn ds.name\n}", "func (d *Document) Name() string { return d.Document.DocumentName }", "func (x *AclSet) GetName() string {\n\tif x != nil {\n\t\treturn x.Name\n\t}\n\treturn \"\"\n}", "func (cli *SetWrapper) GetName() (string, error) {\n\tvals, err := cli.set.GetValues()\n\tif nil != err {\n\t\treturn \"\", err\n\t}\n\treturn vals.String(fieldSetName), nil\n}", "func (s *Set) Name() string {\n\treturn s.name\n}", "func (dc DatabaseCollection) String() string {\n\tswitch dc {\n\tcase TRACKS:\n\t\treturn \"tracks\"\n\tcase WEBHOOKS:\n\t\treturn \"webhooks\"\n\t}\n\treturn \"\"\n}", "func (i *Index) Name() string { return i.name }", "func (c FieldsCollection) DisplayName() *models.Field {\n\treturn c.MustGet(\"DisplayName\")\n}", "func (collector *CollectorV2[T]) Name() string {\n\treturn collector.name\n}", "func (o *SourceMongoDb) GetCollectionName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.CollectionName\n}", "func (o *ContentProviderReadDetailed) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (instance *Instance) GetCollection() (collection string) {\n\tif val := instance.GetIndexInstance(); val != nil {\n\t\treturn val.GetDefinition().GetCollection()\n\t} else {\n\t\t// TODO: should we panic\n\t}\n\treturn\n}", "func (x GenericEntity) GetName() string {\n\treturn x.Name\n}", "func (e *EntryBase) Name() string {\n\treturn e.name()\n}", "func (x GenericInfrastructureEntity) GetName() string {\n\treturn x.Name\n}", "func (d Document) Name() string { return d.name }", "func (o GoogleDatastoreAdminV1IndexedPropertyResponseOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v GoogleDatastoreAdminV1IndexedPropertyResponse) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o *ContentProvider2) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (i *item) Name() string {\n\treturn i.wrapped.Name()\n}", "func (c unionCAContent) Name() string {\n\tnames := []string{}\n\tfor _, curr := range c {\n\t\tnames = append(names, curr.Name())\n\t}\n\treturn strings.Join(names, \",\")\n}", "func (x *UserCollection) NameOf() string {\n\treturn \"rest_dal_users_\" + x.config.Name\n}", "func (o *EventSubcategory) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (d *Document) Name() string {\n\treturn fmt.Sprintf(\"%s-%s\", d.AccountId, d.InstanceId)\n}", "func (fdb *fdbSlice) Name() string {\n\treturn fdb.name\n}", "func (re *Records) Name() string { return \"records\" }", "func (t Scalar) Name() string {\n\treturn strings.Title(t.Type)\n}", "func (o *BaseItem) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (t *Type) GetName() string { return t.Name }", "func (o *SiteMapReadDetailed) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (n Normalizer) GetName() string {\n\treturn n.name\n}", "func (o *View) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (CosmosKeyResource) GetName() string {\n\treturn \"cosmosKeys\"\n}", "func (o *Replication) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (*MapSchema) GetName() string {\n\treturn typeMap\n}", "func (x GenericInfrastructureEntityOutline) GetName() string {\n\treturn x.Name\n}", "func (s *Structured) GetName() string {\n\treturn s.cloudEvent.Source\n}", "func (m *ProjectionMapping) GetName() string {\n\treturn m.Name\n}", "func (x GenericEntityOutline) GetName() string {\n\treturn x.Name\n}", "func (s CloudEventResource) GetName() string {\n\treturn s.Name\n}", "func (o *SiteAllOfNameResolutionGcpResolvers) GetName() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.Name\n}", "func (o RecordSetOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *RecordSet) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (o CustomLayerOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *CustomLayer) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (e *EDNS) Name() string { return name }", "func (o CatalogOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *Catalog) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}", "func (p NodeSet) Name() []string {\n\treturn p.ToString(NameOf)\n}", "func (p *Property) GetName() string {\n\treturn \"properties\"\n}", "func (o *CloudInstanceTypeAllOf) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (s *Speacies) GetName() string {\n\treturn s.Name\n}", "func (c Collection) String() string {\n\tvar enumVal string\n\n\tswitch c {\n\tcase CollectionBackupCareBooking:\n\t\tenumVal = \"BACKUP_CARE_BOOKING\"\n\t}\n\n\treturn enumVal\n}", "func (g *generator) Name() string {\n\treturn g.typeName\n}", "func (o *IamServiceProviderAllOf) GetName() string {\n\tif o == nil || o.Name == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Name\n}", "func (m *metadata) GetName() string {\n\treturn m.name\n}", "func (object *Object) Name() string {\n\treturn object.objectType\n}", "func TestCollectionName(t *testing.T) {\n\tc := createClient(t, nil)\n\tdb := ensureDatabase(nil, c, \"collection_test\", nil, t)\n\tname := \"test_collection_name\"\n\tcol, err := db.CreateCollection(nil, name, nil)\n\tif err != nil {\n\t\tt.Fatalf(\"Failed to create collection '%s': %s\", name, describe(err))\n\t}\n\tif col.Name() != name {\n\t\tt.Errorf(\"Collection.Name() is wrong, got '%s', expected '%s'\", col.Name(), name)\n\t}\n}", "func (c classy) GetName() string {\n\treturn c.name\n}", "func (*ArraySchema) GetName() string {\n\treturn typeArray\n}", "func (this *AppItem) Name() string {\n return this.name\n}", "func (ct ContentType) Name() string {\n\treturn string(ct)\n}", "func (ct ContentType) Name() string {\n\treturn string(ct)\n}", "func (m *AssignedEntitiesWithMetricTile) Name() *string {\n\treturn m.nameField\n}", "func GetName() string {\n\treturn NewExchange().GetName()\n}", "func (svc *Rekognition) GetCollection(name string) (*Collection, error) {\n\tcollectionName := svc.prefix + name\n\n\t// get the stream from cache\n\tsvc.collectionsMu.RLock()\n\tc, ok := svc.collections[collectionName]\n\tsvc.collectionsMu.RUnlock()\n\tif ok {\n\t\treturn c, nil\n\t}\n\n\tc = NewCollection(svc, name)\n\tsvc.collectionsMu.Lock()\n\tsvc.collections[collectionName] = c\n\tsvc.collectionsMu.Unlock()\n\treturn c, nil\n}", "func ResourceName(meta *admin.Meta) string {\n\t// follow ptr && slice\n\telemType := meta.FieldStruct.Struct.Type\n\tfor elemType.Kind() == reflect.Slice || elemType.Kind() == reflect.Ptr {\n\t\telemType = elemType.Elem()\n\t}\n\n\t// get empty struct\n\tvalue := reflect.New(elemType).Interface()\n\n\treturn getResourceNameByValue(value)\n}", "func (v *nicerButSlowerFilmListViewType) Name() string {\n\treturn v.s.SQLName\n}", "func (store *GSStore) GetName() string {\n\treturn store.Name\n}", "func (n *Notification) Collection() string {\n\treturn COLLECTION\n}", "func (c *Collection) ChangeName(name string) error {\n\tif c.Name == \"ALL_MEDIA_AUTO_COLLECTION\" {\n\t\treturn ErrAllSaved\n\t}\n\tinsta := c.insta\n\n\tdata, err := json.Marshal(\n\t\tmap[string]string{\n\t\t\t\"cover_media_id\": toString(c.Cover.ID),\n\t\t\t\"_uid\": toString(insta.Account.ID),\n\t\t\t\"name\": name,\n\t\t\t\"_uuid\": insta.uuid,\n\t\t\t\"added_collaborator_ids\": \"[]\",\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbody, _, err := insta.sendRequest(\n\t\t&reqOptions{\n\t\t\tEndpoint: fmt.Sprintf(urlCollectionEdit, c.ID),\n\t\t\tIsPost: true,\n\t\t\tQuery: generateSignature(data),\n\t\t},\n\t)\n\terr = json.Unmarshal(body, c)\n\treturn err\n}", "func (o VirtualDatabaseSpecDatasourcesPropertiesOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v VirtualDatabaseSpecDatasourcesProperties) string { return v.Name }).(pulumi.StringOutput)\n}", "func (o *NamedListOpts) Name() string {\n return o.name\n}", "func (m *CalendarGroup) GetName()(*string) {\n val, err := m.GetBackingStore().Get(\"name\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}", "func (s *BasePlSqlParserListener) EnterCollection_name(ctx *Collection_nameContext) {}", "func (x DashboardEntity) GetName() string {\n\treturn x.Name\n}", "func (o DicomStoreOutput) Name() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *DicomStore) pulumi.StringOutput { return v.Name }).(pulumi.StringOutput)\n}" ]
[ "0.7801984", "0.77176106", "0.7488358", "0.73315096", "0.71971077", "0.69981635", "0.69015723", "0.6898812", "0.68495", "0.6812542", "0.67449296", "0.6693253", "0.66145366", "0.65889096", "0.64945", "0.64914566", "0.64841396", "0.64322925", "0.6409194", "0.62912184", "0.61778444", "0.61707366", "0.61648107", "0.61387", "0.61295456", "0.61006415", "0.6096237", "0.60647774", "0.6016523", "0.60130996", "0.60088736", "0.5994669", "0.59659505", "0.5962705", "0.595673", "0.5955192", "0.5945301", "0.5928616", "0.5895739", "0.58908963", "0.5890593", "0.5877478", "0.5871534", "0.58563113", "0.5835075", "0.5829848", "0.5829764", "0.58297175", "0.5820969", "0.58135974", "0.5810831", "0.5810177", "0.5802739", "0.57963175", "0.57911676", "0.5789061", "0.5784177", "0.5782268", "0.5782122", "0.57810724", "0.5778522", "0.5771971", "0.5765128", "0.5760198", "0.57565737", "0.57445097", "0.57421106", "0.5734919", "0.57188517", "0.57097864", "0.5708283", "0.570608", "0.5702667", "0.56992185", "0.5697502", "0.5694468", "0.5687505", "0.5686261", "0.568571", "0.5682172", "0.5679274", "0.56700325", "0.56687444", "0.5659246", "0.5655964", "0.5655964", "0.5651134", "0.5643902", "0.56422126", "0.5641476", "0.56411034", "0.5636247", "0.56314737", "0.56268305", "0.56225604", "0.5622448", "0.5619217", "0.5615728", "0.561524", "0.561105" ]
0.56207705
96
ToHTTPRequest returns a RequestFunc that injects an OpenTracing Span found in context into the HTTP Headers. If no such Span can be found, the RequestFunc is a noop.
func ToHTTPRequest(tracer opentracing.Tracer) RequestFunc { return func(req *http.Request) *http.Request { // Retrieve the Span from context. if span := opentracing.SpanFromContext(req.Context()); span != nil { // We are going to use this span in a client request, so mark as such. ext.SpanKindRPCClient.Set(span) // Add some standard OpenTracing tags, useful in an HTTP request. ext.HTTPMethod.Set(span, req.Method) span.SetTag(zipkincore.HTTP_HOST, req.URL.Host) span.SetTag(zipkincore.HTTP_PATH, req.URL.Path) ext.HTTPUrl.Set( span, fmt.Sprintf("%s://%s%s", req.URL.Scheme, req.URL.Host, req.URL.Path), ) // Add information on the peer service we're about to contact. if host, portString, err := net.SplitHostPort(req.URL.Host); err == nil { ext.PeerHostname.Set(span, host) if port, err := strconv.Atoi(portString); err != nil { ext.PeerPort.Set(span, uint16(port)) } } else { ext.PeerHostname.Set(span, req.URL.Host) } // Inject the Span context into the outgoing HTTP Request. if err := tracer.Inject( span.Context(), opentracing.TextMap, opentracing.HTTPHeadersCarrier(req.Header), ); err != nil { fmt.Printf("error encountered while trying to inject span: %+v\n", err) } } return req } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func FromHTTPRequest(tracer opentracing.Tracer, operationName string,\n) HandlerFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\t\t// Try to join to a trace propagated in `req`.\n\t\t\twireContext, err := tracer.Extract(\n\t\t\t\topentracing.TextMap,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\tfmt.Printf(\"error encountered while trying to extract span: %+v\\n\", err)\n\t\t\t}\n\n\t\t\t// create span\n\t\t\tspan := tracer.StartSpan(operationName, ext.RPCServerOption(wireContext))\n\t\t\tdefer span.Finish()\n\n\t\t\t// store span in context\n\t\t\tctx := opentracing.ContextWithSpan(req.Context(), span)\n\n\t\t\t// update request context to include our new span\n\t\t\treq = req.WithContext(ctx)\n\n\t\t\t// next middleware or actual request handler\n\t\t\tnext.ServeHTTP(w, req)\n\t\t})\n\t}\n}", "func (s *Span) ToHTTPReq(req *http.Request) (*http.Request, error) {\n\tif s == nil {\n\t\treturn req, nil\n\t}\n\thc, ok := client.(HTTPCarrier)\n\tif !ok {\n\t\treturn req, errors.New(\"not supported\")\n\t}\n\terr := hc.ToReq(req, s.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func SpanContextToRequest(span *trace.Span, req *http.Request) {\n\tformat := tracecontext.HTTPFormat{}\n\tformat.SpanContextToRequest(span.SpanContext(), req)\n}", "func ToWire(spanCtx opentracing.SpanContext, r *http.Request) error {\n\tcarrier := opentracing.HTTPHeadersCarrier(r.Header)\n\terr := opentracing.GlobalTracer().Inject(\n\t\tspanCtx,\n\t\topentracing.HTTPHeaders,\n\t\tcarrier)\n\treturn err\n}", "func StartSpan(req *restful.Request, operationName string) (opentracing.Span, context.Context) {\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range req.Request.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\t}\n\n\tspanContext, err := ExtractRequestHeader(req)\n\n\tvar span opentracing.Span\n\n\tif err != nil {\n\t\tspan = StartSpanSafe(operationName)\n\t} else {\n\t\tspan = StartSpanSafe(\n\t\t\toperationName,\n\t\t\topentracing.ChildOf(spanContext),\n\t\t)\n\t}\n\n\text.HTTPMethod.Set(span, req.Request.Method)\n\text.HTTPUrl.Set(span, req.Request.Host+req.Request.RequestURI)\n\n\tif abTraceID := req.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\tAddTag(span, event.TraceIDKey, abTraceID)\n\t}\n\n\treturn span, opentracing.ContextWithSpan(req.Request.Context(), span)\n}", "func OpenTracingHandler() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif !opentracing.IsGlobalTracerRegistered() {\n\t\t\tc.Next()\n\t\t\treturn\n\t\t}\n\t\tvar span opentracing.Span\n\t\ttracer := opentracing.GlobalTracer()\n\t\tspCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tif err != nil {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.Request.URL.Path,\n\t\t\t\topentracing.Tag{Key: string(ext.Component), Value: \"HTTP\"},\n\t\t\t\text.SpanKindRPCServer,\n\t\t\t)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.Request.URL.Path,\n\t\t\t\topentracing.ChildOf(spCtx),\n\t\t\t\topentracing.Tag{Key: string(ext.Component), Value: \"HTTP\"},\n\t\t\t\text.SpanKindRPCServer,\n\t\t\t)\n\t\t}\n\t\t// 设置http.url, http.method\n\t\text.HTTPMethod.Set(span, c.Request.Method)\n\t\text.HTTPUrl.Set(span, c.Request.URL.String())\n\n\t\tdefer span.Finish()\n\t\t// request context 中添加span 信息 用来传递\n\t\tc.Request = c.Request.WithContext(opentracing.ContextWithSpan(c.Request.Context(), span))\n\t\t_ = tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tc.Next()\n\t}\n}", "func TracingMiddleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Attempt to join a span by getting trace info from the headers.\n\t\t// To start with use the URL as the opName since we haven't gotten to the router yet and\n\t\t// the router knows about opNames\n\t\topName := r.URL.Path\n\t\tvar sp opentracing.Span\n\t\tif sc, err := opentracing.GlobalTracer().\n\t\t\tExtract(opentracing.HTTPHeaders,\n\t\t\t\topentracing.HTTPHeadersCarrier(r.Header)); err != nil {\n\t\t\tsp = opentracing.StartSpan(opName)\n\t\t} else {\n\t\t\tsp = opentracing.StartSpan(opName, opentracing.ChildOf(sc))\n\t\t}\n\t\tdefer sp.Finish()\n\n\t\t// inject span ID into logs to aid in request debugging\n\t\tt := make(map[string]string)\n\t\tif err := sp.Tracer().Inject(sp.Context(), opentracing.TextMap,\n\t\t\topentracing.TextMapCarrier(t)); err == nil {\n\t\t\tif spanid, ok := t[\"ot-tracer-spanid\"]; ok {\n\t\t\t\tlogger.FromContext(r.Context()).AddContext(\"ot-tracer-spanid\", spanid)\n\t\t\t}\n\t\t}\n\n\t\tsp.LogEvent(\"request_received\")\n\t\tdefer func() {\n\t\t\tsp.LogEvent(\"request_finished\")\n\t\t}()\n\t\tnewCtx := opentracing.ContextWithSpan(r.Context(), sp)\n\t\t// Use a string pointer so layers below can modify it\n\t\tstrPtr := \"\"\n\t\tnewCtx = context.WithValue(newCtx, tracingOpName{}, &strPtr)\n\n\t\tsrw := &statusResponseWriter{\n\t\t\tstatus: 200,\n\t\t\tResponseWriter: w,\n\t\t}\n\n\t\ttags.HTTPMethod.Set(sp, r.Method)\n\t\ttags.SpanKind.Set(sp, tags.SpanKindRPCServerEnum)\n\t\ttags.HTTPUrl.Set(sp, r.URL.Path)\n\t\tsp.LogFields(opentracinglog.String(\"url-query\", r.URL.RawQuery))\n\n\t\tdefer func() {\n\t\t\ttags.HTTPStatusCode.Set(sp, uint16(srw.status))\n\t\t\tif srw.status >= 500 {\n\t\t\t\ttags.Error.Set(sp, true)\n\t\t\t}\n\t\t\t// Now that we have the opName let's try setting it\n\t\t\topName, ok := newCtx.Value(tracingOpName{}).(*string)\n\t\t\tif ok && opName != nil {\n\t\t\t\tsp.SetOperationName(*opName)\n\t\t\t}\n\t\t}()\n\n\t\th.ServeHTTP(srw, r.WithContext(newCtx))\n\t})\n}", "func OpenTracing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttracer := opentracing.GlobalTracer()\n\n\t\t// Get any incoming tracing context via HTTP headers & create the span.\n\t\tctx, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))\n\t\tspan := tracer.StartSpan(\"http.request\", ext.RPCServerOption(ctx))\n\t\tdefer span.Finish()\n\n\t\t// Set basic HTTP info\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\t\text.Component.Set(span, \"huma\")\n\t\tspan.SetTag(\"span.type\", \"web\")\n\n\t\t// Update context & continue the middleware chain.\n\t\tr = r.WithContext(opentracing.ContextWithSpan(r.Context(), span))\n\t\tws := statusRecorder{ResponseWriter: w}\n\t\tnext.ServeHTTP(&ws, r)\n\n\t\t// If we have a Chi route template, save it\n\t\tif chictx := chi.RouteContext(r.Context()); chictx != nil {\n\t\t\tspan.SetTag(\"resource.name\", chictx.RoutePattern())\n\t\t\tspan.SetOperationName(r.Method + \" \" + chictx.RoutePattern())\n\t\t}\n\n\t\t// Save the status code\n\t\text.HTTPStatusCode.Set(span, uint16(ws.status))\n\t})\n}", "func OpenTracingMiddleware(handlerPackageName string) gin.HandlerFunc {\n\tif !opentracing.IsGlobalTracerRegistered() {\n\t\tfmt.Println(\"OpenTracing global tracer ever register yet\")\n\t\treturn nil\n\t}\n\treturn func(c *gin.Context) {\n\t\tvar span opentracing.Span\n\t\t// Extract trace context from HTTP Header\n\t\ttraceContext, err := opentracing.GlobalTracer().Extract(\n\t\t\topentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tvar opts []opentracing.StartSpanOption\n\t\tif err == nil {\n\t\t\topts = append(opts, opentracing.ChildOf(traceContext))\n\t\t}\n\t\tspan = opentracing.StartSpan(unknownOperation, opts...)\n\t\tspan.SetBaggageItem(BaggageRequestID, c.GetString(CtxRequestID))\n\n\t\tc.Set(CtxTraceSpan, span)\n\t\t// Keep going on next handlers\n\t\tc.Next()\n\n\t\t// Getting operation name from context if manually set\n\t\toperationName := c.GetString(CtxTraceOperationName)\n\t\tif operationName == \"\" {\n\t\t\toperationName = getHandlerName(handlerPackageName, c.HandlerNames())\n\t\t}\n\t\tspan.SetOperationName(operationName)\n\t\tc.Set(CtxTraceOperationName, operationName)\n\t\t// Set HTTP related information\n\t\tspan.SetTag(TagHTTPURL, c.Request.URL.String())\n\t\tspan.SetTag(TagHTTPMethod, c.Request.Method)\n\t\tspan.SetTag(TagHTTPUserAgent, c.Request.UserAgent())\n\t\tspan.SetTag(TagHTTPClientIP, c.ClientIP())\n\t\tspan.SetTag(TagHTTPStatusCode, c.Writer.Status())\n\t\t// Report to server\n\t\tspan.Finish()\n\t}\n}", "func HTTPToContext() http.RequestFunc {\n\treturn func(ctx context.Context, r *stdhttp.Request) context.Context {\n\t\ttoken, ok := extractTokenFromAuthHeader(r.Header.Get(\"Authorization\"))\n\t\tif !ok {\n\t\t\treturn ctx\n\t\t}\n\n\t\treturn context.WithValue(ctx, JWTContextKey, token)\n\t}\n}", "func (c *Contextor) HTTPToContext(family, title string) kithttp.RequestFunc {\n\treturn func(ctx context.Context, req *http.Request) context.Context {\n\t\tif atomic.LoadInt32(&c.enabled) != 1 {\n\t\t\treturn ctx\n\t\t}\n\t\ttracer := NewTracer(family, title)\n\t\treturn NewContext(ctx, tracer)\n\t}\n}", "func ContextToHTTP() http.RequestFunc {\n\treturn func(ctx context.Context, r *stdhttp.Request) context.Context {\n\t\ttoken, ok := ctx.Value(JWTContextKey).(string)\n\t\tif ok {\n\t\t\tr.Header.Add(\"Authorization\", generateAuthHeaderFromToken(token))\n\t\t}\n\t\treturn ctx\n\t}\n}", "func FromWire(r *http.Request) (opentracing.SpanContext, error) {\n\treturn opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))\n}", "func InjectTrace(ctx context.Context, incomingReq *restful.Request,\n\toutgoingReq *http.Request) (*http.Request, opentracing.Span, context.Context) {\n\tspan, newCtx := StartSpanFromContext(ctx, \"outgoing request\")\n\tif span != nil {\n\t\text.HTTPUrl.Set(span, outgoingReq.Host+outgoingReq.RequestURI)\n\t\text.HTTPMethod.Set(span, outgoingReq.Method)\n\t\t_ = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(outgoingReq.Header))\n\n\t\tfor _, header := range forwardHeaders {\n\t\t\tif value := incomingReq.Request.Header.Get(header); value != \"\" {\n\t\t\t\toutgoingReq.Header.Set(header, value)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn outgoingReq, nil, nil\n\t}\n\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range outgoingReq.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"outgoing header : \", header)\n\t}\n\n\tif abTraceID := incomingReq.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\toutgoingReq.Header.Set(event.TraceIDKey, abTraceID)\n\t}\n\n\treturn outgoingReq, span, newCtx\n}", "func StartSpanFromHTTPContext(ctx context.Context, name string) (context.Context, *Span) {\n\tlogger := globalTracer.getLogger()\n\tspan := newSpan(nil, name, SpanTypeServer)\n\tdefer func() {\n\t\tonCreateServerSpan(span)\n\t\tspan.onStart()\n\t}()\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.TraceIDContextKey); ok {\n\t\tif id, err := strconv.ParseUint(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed trace id in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.traceID = id\n\t\t}\n\t}\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.SpanIDContextKey); ok {\n\t\tif id, err := strconv.ParseUint(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed parent id in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.parentID = id\n\t\t}\n\t}\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.SpanFlagsContextKey); ok {\n\t\tif flags, err := strconv.ParseInt(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed flags in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.flags = flags\n\t\t}\n\t}\n\tstr, ok := httpbp.GetHeader(ctx, httpbp.SpanSampledContextKey)\n\tsampled := ok && str == thriftbp.HeaderTracingSampledTrue\n\tspan.trace.sampled = sampled\n\n\treturn ctx, span\n}", "func GetOpenTracingSpanFromContext(c *gin.Context) opentracing.Span {\n\trawSpan, ok := c.Get(CtxTraceSpan)\n\tif ok {\n\t\treturn rawSpan.(opentracing.Span)\n\t}\n\treturn opentracing.StartSpan(unknownOperation)\n}", "func HTTPMiddleware(tracer opentracing.Tracer, name string, logger log.Logger, next http.Handler) http.HandlerFunc {\n\toperationName := fmt.Sprintf(\"/%s HTTP[server]\", name)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\twireContext, err := tracer.Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header),\n\t\t)\n\t\tif err != nil && err != opentracing.ErrSpanContextNotFound {\n\t\t\tlevel.Error(logger).Log(\"msg\", \"failed to extract tracer from request\", \"operationName\", operationName, \"err\", err)\n\t\t}\n\n\t\topts := []opentracing.StartSpanOption{ext.RPCServerOption(wireContext)}\n\t\t// Check for force tracing header and add it as a tag at the start of span.\n\t\t// This is required for the OpenTelemetry sampler to force tracing.\n\t\tif r.Header.Get(ForceTracingBaggageKey) != \"\" {\n\t\t\topts = append(opts, opentracing.Tag{Key: migration.ForceTracingAttributeKey, Value: \"true\"})\n\t\t}\n\n\t\tspan := tracer.StartSpan(\n\t\t\toperationName,\n\t\t\topts...,\n\t\t)\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\n\t\t// If client specified ForceTracingBaggageKey header, ensure span includes it to force tracing.\n\t\tspan.SetBaggageItem(strings.ToLower(ForceTracingBaggageKey), r.Header.Get(ForceTracingBaggageKey))\n\n\t\tif t, ok := tracer.(Tracer); ok {\n\t\t\tif traceID, ok := t.GetTraceIDFromSpanContext(span.Context()); ok {\n\t\t\t\tw.Header().Set(traceIDResponseHeader, traceID)\n\t\t\t}\n\t\t} else {\n\t\t\t// Alternative to set trace ID header, if bridge tracer is being used.\n\t\t\tif traceID, ok := migration.GetTraceIDFromBridgeSpan(span); ok {\n\t\t\t\tw.Header().Set(traceIDResponseHeader, traceID)\n\t\t\t}\n\t\t}\n\n\t\tnext.ServeHTTP(w, r.WithContext(opentracing.ContextWithSpan(ContextWithTracer(r.Context(), tracer), span)))\n\t\tspan.Finish()\n\t}\n}", "func Inject(span opentracing.Span, request *http.Request) error {\n\treturn span.Tracer().Inject(\n\t\tspan.Context(),\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(request.Header))\n}", "func FromHTTPReq(req *http.Request) (*Span, error) {\n\thc, ok := client.(HTTPCarrier)\n\tif !ok {\n\t\treturn nil, errors.New(\"not supported\")\n\t}\n\tid, err := hc.FromReq(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Span{ID: id}, nil\n}", "func NewWithTracer(tracer opentracing.Tracer) tracing.StartSpan {\n\treturn func(serviceId string, operationId string, protocol tracing.WireProtocol, r *http.Request) (context.Context, tracing.ServerSpan) {\n\t\tspanName := serviceId + OperationDelimiter + operationId\n\t\twireContext, err := tracer.Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.Debug(\"Failed to extract opentracing headers\")\n\t\t}\n\n\t\t// Create the span referring to the RPC client if available.\n\t\t// If wireContext == nil, a root span will be created.\n\t\t// ext.RPCServerOption() sets tag span.kind=server\n\t\tserverSpan := tracer.StartSpan(\n\t\t\tspanName,\n\t\t\text.RPCServerOption(wireContext))\n\n\t\t//Set tag for the component\n\t\tserverSpan.SetTag(\"component\", ComponentTag)\n\n\t\t//Set headers, if header is not present the tag will be set to \"\"\n\t\tserverSpan.SetTag(\"http.user_agent\", r.Header.Get(\"User-Agent\"))\n\t\tserverSpan.SetTag(\"peer.address\", peerAddress(r))\n\t\tserverSpan.SetTag(\"wire.protocol\", protocol)\n\t\tserverSpan.SetTag(\"is_internal\", isInternal(r))\n\n\t\tspan := NewServerSpan(serverSpan)\n\n\t\tctx := opentracing.ContextWithSpan(r.Context(), serverSpan)\n\n\t\treturn ctx, span\n\t}\n}", "func WithTracing(handler http.Handler, tp oteltrace.TracerProvider, serviceName string) http.Handler {\n\topts := []otelhttp.Option{\n\t\totelhttp.WithPropagators(Propagators()),\n\t\totelhttp.WithTracerProvider(tp),\n\t}\n\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\treturn otelhttp.NewHandler(handler, serviceName, opts...)\n}", "func SpanTransferFromContextToHeader(ctx context.Context) context.Context {\n\tvar parentCtx opentracing.SpanContext\n\tif parent := opentracing.SpanFromContext(ctx); parent != nil {\n\t\tparentCtx = parent.Context()\n\t}\n\tsp := opentracing.StartSpan(\n\t\t\"GRPCToHTTP\",\n\t\topentracing.FollowsFrom(parentCtx),\n\t\text.SpanKindRPCClient,\n\t)\n\tdefer sp.Finish()\n\treturn opentracing.ContextWithSpan(context.Background(), sp)\n}", "func OpenTelemetryMiddleware(next http.Handler) http.Handler {\n\ttracer := global.Tracer(\"covidshield/request\")\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tattrs, entries, spanCtx := httptrace.Extract(r.Context(), r)\n\n\t\tr = r.WithContext(correlation.ContextWithMap(r.Context(), correlation.NewMap(correlation.MapUpdate{\n\t\t\tMultiKV: entries,\n\t\t})))\n\t\t_, span := tracer.Start(\n\t\t\ttrace.ContextWithRemoteSpanContext(r.Context(), spanCtx),\n\t\t\t\"HTTP Request\",\n\t\t\ttrace.WithAttributes(attrs...),\n\t\t)\n\t\tdefer span.End()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func TraceOutbound(r *http.Request, span opentracing.Span) error {\n\treturn opentracing.GlobalTracer().Inject(\n\t\tspan.Context(),\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(r.Header))\n}", "func SpanContextFromRequest(req *http.Request) (trace.SpanContext, bool) {\n\tformat := tracecontext.HTTPFormat{}\n\treturn format.SpanContextFromRequest(req)\n}", "func GetSpan(r *http.Request) opentracing.Span {\n\treturn opentracing.SpanFromContext(r.Context())\n}", "func newOpenTelemetryWrapper(\n\tctx context.Context,\n\tspanName string,\n) (openTelemetryWrapper, error) {\n\tif spanName == \"\" {\n\t\tspanName = defaultSpanName\n\t}\n\n\tot := openTelemetryWrapper{\n\t\tspanName: spanName,\n\t}\n\n\tversion, _ := caddy.Version()\n\tres, err := ot.newResource(webEngineName, version)\n\tif err != nil {\n\t\treturn ot, fmt.Errorf(\"creating resource error: %w\", err)\n\t}\n\n\ttraceExporter, err := otlptracegrpc.New(ctx)\n\tif err != nil {\n\t\treturn ot, fmt.Errorf(\"creating trace exporter error: %w\", err)\n\t}\n\n\tot.propagators = autoprop.NewTextMapPropagator()\n\n\ttracerProvider := globalTracerProvider.getTracerProvider(\n\t\tsdktrace.WithBatcher(traceExporter),\n\t\tsdktrace.WithResource(res),\n\t)\n\n\tot.handler = otelhttp.NewHandler(http.HandlerFunc(ot.serveHTTP),\n\t\tot.spanName,\n\t\totelhttp.WithTracerProvider(tracerProvider),\n\t\totelhttp.WithPropagators(ot.propagators),\n\t\totelhttp.WithSpanNameFormatter(ot.spanNameFormatter),\n\t)\n\n\treturn ot, nil\n}", "func Trace() gin.HandlerFunc {\n\n\treturn func(c *gin.Context) {\n\n\t\ttracer := opentracing.GlobalTracer()\n\t\twireContext, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tvar span opentracing.Span\n\n\t\tif err != nil {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.HandlerName(),\n\t\t\t)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.HandlerName(),\n\t\t\t\text.RPCServerOption(wireContext),\n\t\t\t)\n\t\t}\n\n\t\tspan.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCServerEnum))\n\t\tspan.SetTag(string(ext.PeerHostname), c.Request.Host)\n\t\tspan.SetTag(string(ext.HTTPUrl), c.Request.URL.Path)\n\t\tspan.SetTag(string(ext.HTTPMethod), c.Request.Method)\n\n\t\t// Wrap the request with span context\n\t\tc.Request = wrapRequestWithSpanContext(c.Request, span)\n\t\tc.Set(ContextKey, span)\n\t\t// call the next\n\t\t// set the response headers\n\t\ttracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Writer.Header()))\n\t\tc.Next()\n\t\tspan.SetTag(string(ext.HTTPStatusCode), c.Writer.Status())\n\n\t\tspan.Finish()\n\n\t}\n}", "func Tracing() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\t//no tracing for static files\n\t\t\tif c.Path() == \"/*\" || c.Path() == \"/metrics\" {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\ttracer := opentracing.GlobalTracer()\n\t\t\treq := c.Request()\n\t\t\topName := \"HTTP \" + req.Method + \" URL: \" + c.Path()\n\n\t\t\tvar span opentracing.Span\n\t\t\tif ctx, err := tracer.Extract(opentracing.HTTPHeaders,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\t\tspan = tracer.StartSpan(opName)\n\t\t\t} else {\n\t\t\t\tspan = tracer.StartSpan(opName, ext.RPCServerOption(ctx))\n\t\t\t}\n\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\text.HTTPUrl.Set(span, req.URL.String())\n\t\t\text.Component.Set(span, \"rest\")\n\n\t\t\treq = req.WithContext(opentracing.ContextWithSpan(req.Context(), span))\n\t\t\tc.SetRequest(req)\n\n\t\t\tc.Set(\"span\", span)\n\n\t\t\tdefer func() {\n\t\t\t\tstatus := c.Response().Status\n\t\t\t\tcommitted := c.Response().Committed\n\t\t\t\text.HTTPStatusCode.Set(span, uint16(status))\n\t\t\t\tif status >= http.StatusInternalServerError || !committed {\n\t\t\t\t\text.Error.Set(span, true)\n\t\t\t\t}\n\t\t\t\tspan.Finish()\n\t\t\t}()\n\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func (c *MockedHTTPContext) Span() tracing.Span {\n\tif c.MockedSpan != nil {\n\t\treturn c.MockedSpan()\n\t}\n\treturn tracing.NewSpan(tracing.NoopTracing, \"mocked\")\n}", "func SpanFromContext(tracer opentracing.Tracer, operationName string,\n\tadvancedOpts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tvar opts []opentracing.StartSpanOption\n\t\tparentSpanI, _ := ctx.Get(spanContextKey)\n\t\tif parentSpan, typeOk := parentSpanI.(opentracing.Span); parentSpan != nil && typeOk {\n\t\t\topts = append(opts, opentracing.ChildOf(parentSpan.Context()))\n\t\t} else {\n\t\t\tif AbortOnErrors {\n\t\t\t\tctx.AbortWithError(http.StatusInternalServerError, ErrSpanNotFound)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\topts = append(opts, advancedOpts...)\n\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func (t *TraceTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tvar tr opentracing.Span\n\tif t.activeSpanKey != \"\" {\n\t\tacvspans := req.Context().Value(t.activeSpanKey)\n\t\tif acvspans == nil{\n\t\t\treturn rt.RoundTrip(req)\n\t\t}\n\t\ttr = opentracing.SpanFromContext(opentracing.ContextWithSpan(req.Context(), acvspans.(opentracing.Span)))\n\t} else {\n\t\ttr = opentracing.SpanFromContext(req.Context())\n\t}\n\n\tif tr == nil {\n\t\treturn rt.RoundTrip(req)\n\t}\n\toperationName := \"HTTP:\" + req.Method\n\t//get start new tracer\n\ttracer := tr.Tracer()\n\tspan := tracer.StartSpan(operationName, opentracing.ChildOf(tr.Context()))\n\n\text.DBType.Set(span, \"http\")\n\t//ext.PeerAddress.Set(span, req.URL.String())\n\text.HTTPMethod.Set(span,req.Method)\n\text.HTTPUrl.Set(span, req.URL.String())\n\t/*ext.SpanKind.Set(span, ext.SpanKindRPCClientEnum)*/\n\text.Component.Set(span,_defaultComponentName)\n\t//end\n\tif t.peerService != \"\" {\n\t\text.PeerService.Set(span,t.peerService)\n\t}\n\tfor _, v := range t.extraTags {\n\t\tspan.SetTag(v.Key, v.Value)\n\t}\n\t// inject trace to http header\n\ttracer.Inject(span.Context(),opentracing.HTTPHeaders,req.Header)\n\n\t// ct := clientTracer{tr: tr}\n\t// req = req.WithContext(httptrace.WithClientTrace(req.Context(), ct.clientTrace()))\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\text.Error.Set(span, true)\n\t\tspan.LogFields(log.String(\"event\", \"error\"), log.String(\"message\", err.Error()))\n\t\tspan.Finish()\n\t\treturn resp, err\n\t}\n\n\text.HTTPStatusCode.Set(span,uint16(resp.StatusCode))\n\tif resp.StatusCode >= 400 {\n\t\text.Error.Set(span, true)\n\t}\n\tspan.Finish()\n\treturn resp, err\n}", "func Tracing(operationName string) echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tspan := opentracing.SpanFromContext(c.Request().Context())\n\t\t\tif span == nil {\n\t\t\t\tspan = opentracing.StartSpan(operationName)\n\t\t\t}\n\t\t\tdefer span.Finish()\n\n\t\t\ttraceID := \"\"\n\t\t\tswitch sp := span.Context().(type) {\n\t\t\tcase jaeger.SpanContext:\n\t\t\t\ttraceID = sp.TraceID().String()\n\t\t\t}\n\t\t\tc.Set(\"trace_id\", traceID)\n\n\t\t\tspan.SetTag(\"component\", operationName)\n\t\t\tspan.SetTag(\"span.kind\", \"server\")\n\t\t\tspan.SetTag(\"http.url\", c.Request().Host+c.Request().RequestURI)\n\t\t\tspan.SetTag(\"http.method\", c.Request().Method)\n\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tspan.SetTag(\"error\", true)\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tspan.SetTag(\"http.status_code\", c.Response().Status)\n\t\t\tif c.Response().Status < 200 || c.Response().Status > 299 {\n\t\t\t\tspan.SetTag(\"error\", true)\n\t\t\t} else {\n\t\t\t\tspan.SetTag(\"error\", false)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func TraceHandler(sensor instana.TracerLogger, routeID, pathTemplate string, handler fiber.Handler) fiber.Handler {\n\treturn func(c *fiber.Ctx) error {\n\t\tctx := c.UserContext()\n\t\treq := c.Request() // This is a fasthttp request and not a net/http request\n\n\t\theaders := collectAllHeaders(req)\n\n\t\topts := initSpanOptions(req, routeID)\n\n\t\ttracer := sensor.Tracer()\n\t\tif ps, ok := instana.SpanFromContext(ctx); ok {\n\t\t\ttracer = ps.Tracer()\n\t\t\topts = append(opts, ot.ChildOf(ps.Context()))\n\t\t}\n\n\t\topts = append(opts, extractStartSpanOptionsFromFastHTTPHeaders(tracer, req, headers, sensor)...)\n\n\t\tif isSynthetic(req) {\n\t\t\topts = append(opts, ot.Tag{Key: \"synthetic_call\", Value: true})\n\t\t}\n\n\t\tif isCustomPathTemplate(req, pathTemplate) {\n\t\t\topts = append(opts, ot.Tag{Key: \"http.path_tpl\", Value: pathTemplate})\n\t\t}\n\n\t\tspan := tracer.StartSpan(\"g.http\", opts...)\n\t\tdefer span.Finish()\n\n\t\tvar params url.Values\n\t\tcollectedHeaders := make(map[string]string)\n\n\t\t// ensure collected headers/params are sent in case of panic/error\n\t\tdefer func() {\n\t\t\tif len(collectedHeaders) > 0 {\n\t\t\t\tspan.SetTag(\"http.header\", collectedHeaders)\n\t\t\t}\n\t\t\tif len(params) > 0 {\n\t\t\t\tspan.SetTag(\"http.params\", params.Encode())\n\t\t\t}\n\t\t}()\n\n\t\tparams = collectHTTPParams(req, tracer)\n\n\t\tcollectableHTTPHeaders := configuredCollectableHeaders(tracer)\n\t\tcollectRequestHeaders(headers, collectableHTTPHeaders, collectedHeaders)\n\n\t\tdefer func() {\n\t\t\t// Be sure to capture any kind of panic/error\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tif e, ok := err.(error); ok {\n\t\t\t\t\tspan.SetTag(\"http.error\", e.Error())\n\t\t\t\t\tspan.LogFields(otlog.Error(e))\n\t\t\t\t} else {\n\t\t\t\t\tspan.SetTag(\"http.error\", err)\n\t\t\t\t\tspan.LogFields(otlog.Object(\"error\", err))\n\t\t\t\t}\n\n\t\t\t\tspan.SetTag(string(ext.HTTPStatusCode), http.StatusInternalServerError)\n\n\t\t\t\t// re-throw the panic\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\n\t\t// Inject the span details to the headers\n\t\th := make(ot.HTTPHeadersCarrier)\n\t\ttracer.Inject(span.Context(), ot.HTTPHeaders, h)\n\t\tfor k, v := range h {\n\t\t\tc.Response().Header.Del(k)\n\t\t\tc.Set(k, strings.Join(v, \",\"))\n\t\t}\n\n\t\tc.SetUserContext(instana.ContextWithSpan(ctx, span))\n\t\terr := handler(c)\n\n\t\tcollectResponseHeaders(c.Response(), collectableHTTPHeaders, collectedHeaders)\n\t\tprocessResponseStatus(c.Response().StatusCode(), span)\n\n\t\treturn err\n\t}\n}", "func Trace(globalLogger *zap.Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlogger := logging.FromContext(r.Context())\n\t\t\tid, err := uuid.NewV4()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(errors.Wrap(err, \"error creating trace id\").Error())\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstrID := id.String()\n\n\t\t\t// decorate the span with the id\n\t\t\tsdktrace.SpanFromContext(r.Context()).SetAttributes(attribute.String(traceHeader, strID))\n\n\t\t\t// Let a caller see what the traceID is\n\t\t\tw.Header().Add(traceHeader, strID)\n\n\t\t\t// Also insert as a key, value pair in the http request context\n\t\t\tnext.ServeHTTP(w, r.WithContext(trace.NewContext(r.Context(), id)))\n\t\t})\n\t}\n}", "func TraceRequest(header string, nextRequestID IdGenerator) mux.MiddlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx := r.Context()\n\n\t\t\tvar err error\n\n\t\t\t// If request has the id then use it else generate one\n\t\t\trequestID := r.Header.Get(header)\n\t\t\tif requestID == \"\" {\n\t\t\t\trequestID, err = nextRequestID()\n\t\t\t}\n\n\t\t\t// No error then set it in the context & response\n\t\t\tif err == nil {\n\t\t\t\tctx = context.WithValue(ctx, header, requestID)\n\n\t\t\t\tw.Header().Set(header, requestID)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"oops\", err)\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func traceWrap(c *gin.Context) {\n\tappIDKey, err := tag.NewKey(\"fn.app_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tfnKey, err := tag.NewKey(\"fn.fn_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tctx, err := tag.New(c.Request.Context(),\n\t\ttag.Insert(appIDKey, c.Param(api.AppID)),\n\t\ttag.Insert(fnKey, c.Param(api.FnID)),\n\t)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\t// TODO inspect opencensus more and see if we need to define a header ourselves\n\t// to trigger per-request spans (we will want this), we can set sampler here per request.\n\n\tctx, span := trace.StartSpan(ctx, \"serve_http\")\n\tdefer span.End()\n\n\t// spans like these, not tags\n\tspan.AddAttributes(\n\t\ttrace.StringAttribute(\"fn.app_id\", c.Param(api.AppID)),\n\t\ttrace.StringAttribute(\"fn.fn_id\", c.Param(api.FnID)),\n\t)\n\n\tc.Request = c.Request.WithContext(ctx)\n\tc.Next()\n}", "func OpenTracingServerInterceptor(parentSpan opentracing.Span) grpc.UnaryServerInterceptor {\n\ttracingInterceptor := otgrpc.OpenTracingServerInterceptor(\n\t\t// Use the globally installed tracer\n\t\topentracing.GlobalTracer(),\n\t\t// Log full payloads along with trace spans\n\t\totgrpc.LogPayloads(),\n\t)\n\tif parentSpan == nil {\n\t\treturn tracingInterceptor\n\t}\n\tspanContext := parentSpan.Context()\n\treturn func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo,\n\t\thandler grpc.UnaryHandler) (interface{}, error) {\n\n\t\tmd, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\tmd = metadata.New(nil)\n\t\t}\n\t\tcarrier := metadataReaderWriter{md}\n\t\t_, err := opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, carrier)\n\t\tif err == opentracing.ErrSpanContextNotFound {\n\t\t\tcontract.IgnoreError(opentracing.GlobalTracer().Inject(spanContext, opentracing.HTTPHeaders, carrier))\n\t\t}\n\t\treturn tracingInterceptor(ctx, req, info, handler)\n\t}\n\n}", "func SpanFromHeaders(tracer opentracing.Tracer, operationName string,\n\tpsr ParentSpanReferenceFunc, advancedOpts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tspanContext, err := tracer.Extract(opentracing.TextMap, opentracing.HTTPHeadersCarrier(ctx.Request.Header))\n\t\tif err != nil {\n\t\t\tif AbortOnErrors {\n\t\t\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\topts := append([]opentracing.StartSpanOption{psr(spanContext)}, advancedOpts...)\n\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func GetRequestSpan(r *http.Request) (*tracer.Span, bool) {\n\tspan, ok := tracer.SpanFromContext(r.Context())\n\treturn span, ok\n}", "func Wrap(ctx context.Context, operationName string, opts []tracer.StartSpanOption, f func(ctx context.Context) error) (err error) {\n\tspan, ctx := tracer.StartSpanFromContext(\n\t\tctx,\n\t\toperationName,\n\t\topts...,\n\t)\n\tdefer func() { span.Finish(tracer.WithError(err)) }()\n\n\terr = f(ctx)\n\treturn\n}", "func (t *HadeTraceService) InjectHTTP(req *http.Request, tc *contract.TraceContext) *http.Request {\n\treq.Header.Add(contract.TraceKeyTraceID, tc.TraceID)\n\treq.Header.Add(contract.TraceKeySpanID, tc.SpanID)\n\treq.Header.Add(contract.TraceKeyCspanID, tc.CspanID)\n\treq.Header.Add(contract.TraceKeyParentID, tc.ParentID)\n\treturn req\n}", "func StartSpanFromContext(ctx context.Context) (opentracing.Span, context.Context) {\n\tpc, _, _, _ := runtime.Caller(1)\n\tfunctionName := runtime.FuncForPC(pc).Name()\n\toperationName := functionName[strings.LastIndex(functionName, \"/\")+1:]\n\treturn opentracing.StartSpanFromContext(ctx, operationName)\n}", "func MakeTracingHandler(h http.Handler, component string) http.Handler {\n\t// Wrap the provided handler with one that will inject\n\t// any propagated tracing context provided via a query parameter\n\t// if there isn't already a header containing tracing context.\n\t// This is required for scenarios using web sockets as headers\n\t// cannot be modified to inject the tracing context.\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\t// ensure headers have priority over query parameters\n\t\tif r.Header.Get(tracing.TraceParent) != \"\" {\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttraceParent := r.URL.Query()[tracing.TraceParent]\n\t\tif len(traceParent) > 0 {\n\t\t\tr.Header.Add(tracing.TraceParent, traceParent[0])\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n\n\treturn otelhttp.NewHandler(http.HandlerFunc(handler), component, otelhttp.WithSpanNameFormatter(tracehttp.HandlerFormatter))\n}", "func StartSpanIfParentSpanExist(req *restful.Request, operationName string) (opentracing.Span, context.Context) {\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range req.Request.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"incoming header : \", header)\n\t}\n\n\tspanContext, err := ExtractRequestHeader(req)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tspan := StartSpanSafe(\n\t\toperationName,\n\t\topentracing.ChildOf(spanContext),\n\t)\n\text.HTTPMethod.Set(span, req.Request.Method)\n\text.HTTPUrl.Set(span, req.Request.Host+req.Request.RequestURI)\n\n\tif abTraceID := req.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\tAddTag(span, event.TraceIDKey, abTraceID)\n\t}\n\n\treturn span, opentracing.ContextWithSpan(req.Request.Context(), span)\n}", "func StartSpanWhenRequestRouted(ctx context.Context) (context.Context, error) {\n\tmethodName, ok := twirp.MethodName(ctx)\n\tif !ok {\n\t\treturn ctx, errNoMethodName\n\t}\n\n\tctx, _ = trace.StartSpan(ctx, methodName)\n\treturn ctx, nil\n}", "func (m *MuxTracer) trace(req *http.Request) (*http.Request, *tracer.Span) {\n\troute := mux.CurrentRoute(req)\n\tpath, err := route.GetPathTemplate()\n\tif err != nil {\n\t\t// when route doesn't define a path\n\t\tpath = \"unknown\"\n\t}\n\n\tresource := req.Method + \" \" + path\n\n\tspan := m.tracer.NewRootSpan(\"mux.request\", m.service, resource)\n\tspan.Type = ext.HTTPType\n\tspan.SetMeta(ext.HTTPMethod, req.Method)\n\tspan.SetMeta(ext.HTTPURL, path)\n\n\t// patch the span onto the request context.\n\ttreq := SetRequestSpan(req, span)\n\treturn treq, span\n}", "func (h *httpTracePolicy) Do(req *policy.Request) (resp *http.Response, err error) {\n\trawTracer := req.Raw().Context().Value(shared.CtxWithTracingTracer{})\n\tif tracer, ok := rawTracer.(tracing.Tracer); ok {\n\t\tattributes := []tracing.Attribute{\n\t\t\t{Key: attrHTTPMethod, Value: req.Raw().Method},\n\t\t\t{Key: attrHTTPURL, Value: getSanitizedURL(*req.Raw().URL, h.allowedQP)},\n\t\t\t{Key: attrNetPeerName, Value: req.Raw().URL.Host},\n\t\t}\n\n\t\tif ua := req.Raw().Header.Get(shared.HeaderUserAgent); ua != \"\" {\n\t\t\tattributes = append(attributes, tracing.Attribute{Key: attrHTTPUserAgent, Value: ua})\n\t\t}\n\t\tif reqID := req.Raw().Header.Get(shared.HeaderXMSClientRequestID); reqID != \"\" {\n\t\t\tattributes = append(attributes, tracing.Attribute{Key: attrAZClientReqID, Value: reqID})\n\t\t}\n\n\t\tctx := req.Raw().Context()\n\t\tctx, span := tracer.Start(ctx, \"HTTP \"+req.Raw().Method, &tracing.SpanOptions{\n\t\t\tKind: tracing.SpanKindClient,\n\t\t\tAttributes: attributes,\n\t\t})\n\n\t\tdefer func() {\n\t\t\tif resp != nil {\n\t\t\t\tspan.SetAttributes(tracing.Attribute{Key: attrHTTPStatusCode, Value: resp.StatusCode})\n\t\t\t\tif resp.StatusCode > 399 {\n\t\t\t\t\tspan.SetStatus(tracing.SpanStatusError, resp.Status)\n\t\t\t\t}\n\t\t\t\tif reqID := resp.Header.Get(shared.HeaderXMSRequestID); reqID != \"\" {\n\t\t\t\t\tspan.SetAttributes(tracing.Attribute{Key: attrAZServiceReqID, Value: reqID})\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\t// including the output from err.Error() might disclose URL query parameters.\n\t\t\t\t// so instead of attempting to sanitize the output, we simply output the error type.\n\t\t\t\tspan.SetStatus(tracing.SpanStatusError, fmt.Sprintf(\"%T\", err))\n\t\t\t}\n\t\t\tspan.End()\n\t\t}()\n\n\t\treq = req.WithContext(ctx)\n\t}\n\tresp, err = req.Next()\n\treturn\n}", "func StartSpanFromContext(ctx context.Context, operationName string) (opentracing.Span, context.Context) {\n\tglobalTracerAccessMutex.Lock()\n\tdefer globalTracerAccessMutex.Unlock()\n\n\tif ctx != nil {\n\t\tchildSpan, childCtx := opentracing.StartSpanFromContext(ctx, operationName)\n\t\treturn childSpan, childCtx\n\t}\n\n\treturn nil, ctx\n}", "func GetSpanContextFromContext(ctx context.Context) (opentracing.SpanContext, error) {\n\treqMeta, ok := ctx.Value(ReqMetaDataKey).(map[string]string)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\treturn opentracing.GlobalTracer().Extract(\n\t\topentracing.TextMap,\n\t\topentracing.TextMapCarrier(reqMeta))\n}", "func NewTracer(\n\tserviceName string,\n\tsampler Sampler,\n\treporter Reporter,\n\toptions ...TracerOption,\n) (opentracing.Tracer, io.Closer) {\n\tt := &Tracer{\n\t\tserviceName: serviceName,\n\t\tsampler: samplerV1toV2(sampler),\n\t\treporter: reporter,\n\t\tinjectors: make(map[interface{}]Injector),\n\t\textractors: make(map[interface{}]Extractor),\n\t\tmetrics: *NewNullMetrics(),\n\t\tspanAllocator: simpleSpanAllocator{},\n\t}\n\n\tfor _, option := range options {\n\t\toption(t)\n\t}\n\n\t// register default injectors/extractors unless they are already provided via options\n\ttextPropagator := NewTextMapPropagator(getDefaultHeadersConfig(), t.metrics)\n\tt.addCodec(opentracing.TextMap, textPropagator, textPropagator)\n\n\thttpHeaderPropagator := NewHTTPHeaderPropagator(getDefaultHeadersConfig(), t.metrics)\n\tt.addCodec(opentracing.HTTPHeaders, httpHeaderPropagator, httpHeaderPropagator)\n\n\tbinaryPropagator := NewBinaryPropagator(t)\n\tt.addCodec(opentracing.Binary, binaryPropagator, binaryPropagator)\n\n\t// TODO remove after TChannel supports OpenTracing\n\tinteropPropagator := &jaegerTraceContextPropagator{tracer: t}\n\tt.addCodec(SpanContextFormat, interopPropagator, interopPropagator)\n\n\tzipkinPropagator := &zipkinPropagator{tracer: t}\n\tt.addCodec(ZipkinSpanFormat, zipkinPropagator, zipkinPropagator)\n\n\tif t.baggageRestrictionManager != nil {\n\t\tt.baggageSetter = newBaggageSetter(t.baggageRestrictionManager, &t.metrics)\n\t} else {\n\t\tt.baggageSetter = newBaggageSetter(baggage.NewDefaultRestrictionManager(0), &t.metrics)\n\t}\n\tif t.debugThrottler == nil {\n\t\tt.debugThrottler = throttler.DefaultThrottler{}\n\t}\n\n\tif t.randomNumber == nil {\n\t\tseedGenerator := utils.NewRand(time.Now().UnixNano())\n\t\tpool := sync.Pool{\n\t\t\tNew: func() interface{} {\n\t\t\t\treturn rand.NewSource(seedGenerator.Int63())\n\t\t\t},\n\t\t}\n\n\t\tt.randomNumber = func() uint64 {\n\t\t\tgenerator := pool.Get().(rand.Source)\n\t\t\tnumber := uint64(generator.Int63())\n\t\t\tpool.Put(generator)\n\t\t\treturn number\n\t\t}\n\t}\n\tif t.timeNow == nil {\n\t\tt.timeNow = time.Now\n\t}\n\tif t.logger == nil {\n\t\tt.logger = log.NullLogger\n\t}\n\t// Set tracer-level tags\n\tt.tags = append(t.tags, Tag{key: JaegerClientVersionTagKey, value: JaegerClientVersion})\n\tif hostname, err := os.Hostname(); err == nil {\n\t\tt.tags = append(t.tags, Tag{key: TracerHostnameTagKey, value: hostname})\n\t}\n\tif ipval, ok := t.getTag(TracerIPTagKey); ok {\n\t\tipv4, err := utils.ParseIPToUint32(ipval.(string))\n\t\tif err != nil {\n\t\t\tt.hostIPv4 = 0\n\t\t\tt.logger.Error(\"Unable to convert the externally provided ip to uint32: \" + err.Error())\n\t\t} else {\n\t\t\tt.hostIPv4 = ipv4\n\t\t}\n\t} else if ip, err := utils.HostIP(); err == nil {\n\t\tt.tags = append(t.tags, Tag{key: TracerIPTagKey, value: ip.String()})\n\t\tt.hostIPv4 = utils.PackIPAsUint32(ip)\n\t} else {\n\t\tt.logger.Error(\"Unable to determine this host's IP address: \" + err.Error())\n\t}\n\n\tif t.options.gen128Bit {\n\t\tif t.options.highTraceIDGenerator == nil {\n\t\t\tt.options.highTraceIDGenerator = t.randomNumber\n\t\t}\n\t} else if t.options.highTraceIDGenerator != nil {\n\t\tt.logger.Error(\"Overriding high trace ID generator but not generating \" +\n\t\t\t\"128 bit trace IDs, consider enabling the \\\"Gen128Bit\\\" option\")\n\t}\n\tif t.options.maxTagValueLength == 0 {\n\t\tt.options.maxTagValueLength = DefaultMaxTagValueLength\n\t}\n\tt.process = Process{\n\t\tService: serviceName,\n\t\tUUID: strconv.FormatUint(t.randomNumber(), 16),\n\t\tTags: t.tags,\n\t}\n\tif throttler, ok := t.debugThrottler.(ProcessSetter); ok {\n\t\tthrottler.SetProcess(t.process)\n\t}\n\n\treturn t, t\n}", "func LogRequest(span opentracing.Span, r *http.Request) {\n\tif span != nil && r != nil {\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\t\tspan.SetTag(\"http.host\", r.Host)\n\t}\n}", "func GetTracingSpanFromContext(ctx context.Context, key interface{}) opentracing.Span {\n\tif typed, ok := ctx.Value(key).(opentracing.Span); ok {\n\t\treturn typed\n\t}\n\treturn nil\n}", "func InterceptRequest(f func(http.Header)) *RequestInterceptor {\n\treturn &RequestInterceptor{Intercept: f}\n}", "func (h *OpenTracing) Handler(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar span opentracing.Span\n\t\tvar err error\n\n\t\t// Attempt to join a trace by getting trace context from the headers.\n\t\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\t// If for whatever reason we can't join, go ahead an start a new root span.\n\t\t\tspan = opentracing.StartSpan(r.URL.Path)\n\t\t} else {\n\t\t\tspan = opentracing.StartSpan(r.URL.Path, opentracing.ChildOf(wireContext))\n\t\t}\n\t\tdefer span.Finish()\n\n\t\thost, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to get host name\")\n\t\t}\n\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(\n\t\t\tspan,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", map[bool]string{true: \"https\", false: \"http\"}[h.https], r.Host, r.URL.Path),\n\t\t)\n\t\text.Component.Set(span, \"janus\")\n\t\text.SpanKind.Set(span, \"server\")\n\n\t\tspan.SetTag(\"peer.address\", r.RemoteAddr)\n\t\tspan.SetTag(\"host.name\", host)\n\n\t\t// Add information on the peer service we're about to contact.\n\t\tif host, portString, err := net.SplitHostPort(r.URL.Host); err == nil {\n\t\t\text.PeerHostname.Set(span, host)\n\t\t\tif port, err := strconv.Atoi(portString); err != nil {\n\t\t\t\text.PeerPort.Set(span, uint16(port))\n\t\t\t}\n\t\t} else {\n\t\t\text.PeerHostname.Set(span, r.URL.Host)\n\t\t}\n\n\t\terr = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Could not inject span context into header\")\n\t\t}\n\n\t\thandler.ServeHTTP(w, base.ToContext(r, span))\n\t})\n}", "func NewOpenTracing(https bool) *OpenTracing {\n\treturn &OpenTracing{https}\n}", "func WrapperFor(tp oteltrace.TracerProvider) transport.WrapperFunc {\n\treturn func(rt http.RoundTripper) http.RoundTripper {\n\t\topts := []otelhttp.Option{\n\t\t\totelhttp.WithPropagators(Propagators()),\n\t\t\totelhttp.WithTracerProvider(tp),\n\t\t}\n\t\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\t\treturn otelhttp.NewTransport(rt, opts...)\n\t}\n}", "func NewSpan(tracer opentracing.Tracer, operationName string, opts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func FromContext(ctx context.Context, name string) func() {\n\tspan, _ := opentracing.StartSpanFromContext(ctx, name)\n\treturn span.Finish\n}", "func StartSpanFromContext(ctx opentracing.SpanContext, operationName string) opentracing.Span {\n\ttracer := opentracing.GlobalTracer()\n\tif tracer == nil {\n\t\treturn nil\n\t}\n\n\tspan := tracer.StartSpan(\n\t\toperationName,\n\t\topentracing.ChildOf(ctx),\n\t\text.SpanKindRPCClient,\n\t)\n\n\tif ctx == nil {\n\t\tspan.SetTag(\"parent.context\", \"nil\")\n\t}\n\n\treturn span\n}", "func StartSpanFromContext(ctx context.Context, operationName string, opts ...opentracing.StartSpanOption) (opentracing.Span, context.Context) {\n\t// without a tracing specified this call will fail\n\tif isDebug {\n\t\tspan, ctx := opentracing.StartSpanFromContext(ctx, operationName, opts...)\n\t\treturn span, ctx\n\t}\n\n\t// so we fallback to this one\n\tspan := opentracing.StartSpan(operationName, opts...)\n\treturn span, ctx\n}", "func JaegerTracer() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\ttracer := opentracing.GlobalTracer()\n\t\t\t// if tracer not found, skip.\n\t\t\tif tracer == nil {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\tctx := req.Context()\n\n\t\t\t// 创建 rootSpan\n\t\t\tvar rootCtx opentracing.SpanContext\n\t\t\tif rootSpan := opentracing.SpanFromContext(ctx); rootSpan != nil {\n\t\t\t\trootCtx = rootSpan.Context()\n\t\t\t}\n\n\t\t\tspan := tracer.StartSpan(\n\t\t\t\treq.URL.Path,\n\t\t\t\topentracing.ChildOf(rootCtx),\n\t\t\t\text.SpanKindRPCClient,\n\t\t\t)\n\t\t\tdefer span.Finish()\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\text.HTTPUrl.Set(span, req.URL.RequestURI())\n\t\t\t// make the Span current in the context\n\t\t\tctx = opentracing.ContextWithSpan(ctx, span)\n\n\t\t\tc.SetRequest(req.WithContext(ctx))\n\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\n\t\t\tres := c.Response()\n\n\t\t\text.HTTPStatusCode.Set(span, uint16(res.Status))\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func WithContext(ctx context.Context) RequestOptionFunc {\n\treturn func(req *retryablehttp.Request) error {\n\t\t*req = *req.WithContext(ctx)\n\t\treturn nil\n\t}\n}", "func (r InboundRequest) WithContext(ctx context.Context) *InboundRequest {\n return &InboundRequest{\n Request: *r.Request.WithContext(ctx),\n PathParams: r.PathParams,\n }\n}", "func newRequestScope(now time.Time, logger *logrus.Logger, request *http.Request) RequestScope {\n\tl := NewLogger(logger, logrus.Fields{})\n\trequestID := request.Header.Get(\"X-Request-Id\")\n\tif requestID != \"\" {\n\t\tl.SetField(\"RequestID\", requestID)\n\t}\n\treturn &requestScope{\n\t\tLogger: l,\n\t\tnow: now,\n\t\trequestID: requestID,\n\t}\n}", "func EchoRestTracerMiddleware(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\treq := c.Request()\n\t\ttracer := opentracing.GlobalTracer()\n\t\toperationName := fmt.Sprintf(\"%s %s%s\", req.Method, req.Host, req.URL.Path)\n\n\t\tvar span opentracing.Span\n\t\tvar ctx context.Context\n\t\tif spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\tspan, ctx = opentracing.StartSpanFromContext(req.Context(), operationName)\n\t\t\text.SpanKindRPCServer.Set(span)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption((spanCtx)))\n\t\t\tctx = opentracing.ContextWithSpan(req.Context(), span)\n\t\t\text.SpanKindRPCClient.Set(span)\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tif len(body) < maxPacketSize { // limit request body size to 65000 bytes (if higher tracer cannot show root span)\n\t\t\tspan.SetTag(\"request.body\", string(body))\n\t\t} else {\n\t\t\tspan.SetTag(\"request.body.size\", len(body))\n\t\t}\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // reuse body\n\n\t\tspan.SetTag(\"http.headers\", req.Header)\n\t\text.HTTPUrl.Set(span, req.Host+req.RequestURI)\n\t\text.HTTPMethod.Set(span, req.Method)\n\n\t\tspan.LogEvent(\"start_handling_request\")\n\n\t\tdefer func() {\n\t\t\tspan.LogEvent(\"complete_handling_request\")\n\t\t\tspan.Finish()\n\t\t\tlogger.LogGreen(GetTraceURL(ctx))\n\t\t}()\n\n\t\tresBody := new(bytes.Buffer)\n\t\tmw := io.MultiWriter(c.Response().Writer, resBody)\n\t\twriter := &httpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}\n\t\tc.Response().Writer = writer\n\t\tc.SetRequest(req.WithContext(ctx))\n\n\t\terr := next(c)\n\t\tstatusCode := c.Response().Status\n\t\text.HTTPStatusCode.Set(span, uint16(statusCode))\n\t\tif statusCode >= http.StatusBadRequest {\n\t\t\text.Error.Set(span, true)\n\t\t}\n\n\t\tif resBody.Len() < maxPacketSize { // limit response body size to 65000 bytes (if higher tracer cannot show root span)\n\t\t\tspan.SetTag(\"response.body\", resBody.String())\n\t\t} else {\n\t\t\tspan.SetTag(\"response.body.size\", resBody.Len())\n\t\t}\n\t\treturn err\n\t}\n}", "func StartSpan(ctx context.Context, name string) context.Context {\n\tif tracer != nil {\n\t\treturn tracer.StartSpan(ctx, name)\n\t}\n\treturn ctx\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\t// Collect request parameters to add them to the entry HTTP span. We also need to make\n\t// sure that a proper span kind is set for the entry span, so that Instana could combine\n\t// it and its children into a call.\n\topts := []opentracing.StartSpanOption{\n\t\text.SpanKindRPCServer,\n\t\topentracing.Tags{\n\t\t\t\"http.host\": req.Host,\n\t\t\t\"http.method\": req.Method,\n\t\t\t\"http.protocol\": req.URL.Scheme,\n\t\t\t\"http.path\": req.URL.Path,\n\t\t},\n\t}\n\n\t// Check if there is an ongoing trace context provided with request and use\n\t// it as a parent for our entry span to ensure continuation.\n\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t)\n\tif err != nil {\n\t\topts = append(opts, ext.RPCServerOption(wireContext))\n\t}\n\n\t// Start the entry span adding collected tags and optional parent. The span name here\n\t// matters, as it allows Instana backend to classify the call as an HTTP one.\n\tspan := opentracing.GlobalTracer().StartSpan(\"g.http\", opts...)\n\tdefer span.Finish()\n\n\ttime.Sleep(300 * time.Millisecond)\n\tw.Write([]byte(\"Hello, world!\\n\"))\n}", "func ExtractRequestHeader(req *restful.Request) (opentracing.SpanContext, error) {\n\tglobalTracerAccessMutex.Lock()\n\tdefer globalTracerAccessMutex.Unlock()\n\n\treturn opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Request.Header))\n}", "func HTTPRequest(url, reqbody string) (string, error) {\n\treturn HTTPRequestWithHeaders(url, reqbody, map[string]string{})\n}", "func (i *instrumentor) tracingBegin(ctx context.Context, eventJSON []byte) (context.Context, trace.Span) {\n\t// Add trace id to context\n\tmc := i.configuration.EventToCarrier(eventJSON)\n\tctx = i.configuration.Propagator.Extract(ctx, mc)\n\n\tvar span trace.Span\n\tspanName := os.Getenv(\"AWS_LAMBDA_FUNCTION_NAME\")\n\n\tvar attributes []attribute.KeyValue\n\tlc, ok := lambdacontext.FromContext(ctx)\n\tif !ok {\n\t\terrorLogger.Println(\"failed to load lambda context from context, ensure tracing enabled in Lambda\")\n\t}\n\tif lc != nil {\n\t\tctxRequestID := lc.AwsRequestID\n\t\tattributes = append(attributes, semconv.FaaSExecution(ctxRequestID))\n\n\t\t// Some resource attrs added as span attrs because lambda\n\t\t// resource detectors are created before a lambda\n\t\t// invocation and therefore lack lambdacontext.\n\t\t// Create these attrs upon first invocation\n\t\tif len(i.resAttrs) == 0 {\n\t\t\tctxFunctionArn := lc.InvokedFunctionArn\n\t\t\tattributes = append(attributes, semconv.FaaSID(ctxFunctionArn))\n\t\t\tarnParts := strings.Split(ctxFunctionArn, \":\")\n\t\t\tif len(arnParts) >= 5 {\n\t\t\t\tattributes = append(attributes, semconv.CloudAccountID(arnParts[4]))\n\t\t\t}\n\t\t}\n\t\tattributes = append(attributes, i.resAttrs...)\n\t}\n\n\tctx, span = i.tracer.Start(ctx, spanName, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes(attributes...))\n\n\treturn ctx, span\n}", "func (tracer Tracer) WithRequest(r *http.Request) *http.Request {\n\tif !tracer.IsSampled() {\n\t\treturn r\n\t}\n\tctx := r.Context()\n\tctx = httptrace.WithClientTrace(ctx, tracer.trace)\n\treturn r.WithContext(ctx)\n}", "func GetOpencensusSpanContextFromContext(ctx context.Context) (*trace.SpanContext, error) {\n\treqMeta, ok := ctx.Value(ReqMetaDataKey).(map[string]string)\n\tif !ok {\n\t\treturn nil, nil\n\t}\n\tspanKey := reqMeta[OpencensusSpanRequestKey]\n\tif spanKey == \"\" {\n\t\treturn nil, errors.New(\"key not found\")\n\t}\n\n\tdata := []byte(spanKey)\n\t_ = data[23]\n\n\tt := &trace.SpanContext{}\n\tcopy(t.TraceID[:], data[:16])\n\tcopy(t.SpanID[:], data[16:24])\n\n\treturn t, nil\n}", "func WithTrace(ctx context.Context, r *http.Request) context.Context {\n\tvar trace string\n\tif clients.projectID != \"\" { // should we log an error here since this won't work without it. \"Must call InitLogging\"\n\t\ttraceHeader := r.Header.Get(traceHeader)\n\t\ttraceParts := strings.Split(traceHeader, \"/\")\n\t\tif len(traceParts) > 0 && len(traceParts[0]) > 0 {\n\t\t\ttrace = fmt.Sprintf(\"projects/%s/traces/%s\", clients.projectID, traceParts[0])\n\t\t}\n\t}\n\treturn gotils.With(ctx, traceHeader, trace)\n}", "func (req *GetRequest) Context(ctx context.Context) *GetRequest {\n\treq.impl = req.impl.Context(ctx)\n\n\treturn req\n}", "func (r *Request) WithContext(ctx context.Context) *Request", "func spanToRequestData(span *tracepb.Span) *contracts.RequestData {\n\t/*\n\t\tRequest type comes from a few attributes.\n\n\t\tHTTP\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-http.md\n\n\t\tRPC (gRPC)\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-rpc.md\n\n\t\tDatabase\n\t\thttps://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/data-database.md\n\t*/\n\n\t// https://github.com/microsoft/ApplicationInsights-Go/blob/master/appinsights/contracts/requestdata.go\n\t// Start with some reasonable default for server spans.\n\tdata := contracts.NewRequestData()\n\tdata.Id = idToHex(span.SpanId)\n\tdata.Name = span.Name.Value\n\tdata.Duration = formatSpanDuration(span)\n\tdata.Properties = make(map[string]string)\n\tdata.Measurements = make(map[string]float64)\n\tdata.ResponseCode = \"0\"\n\tdata.Success = true\n\n\tif span.Attributes != nil && span.Attributes.AttributeMap != nil {\n\t\tattributes := span.Attributes.AttributeMap\n\t\tcomponent := \"\"\n\t\tonAttributeStringValueExists(attributes, spanAttributeKeyComponent, func(val string) { component = val })\n\n\t\t// TODO remove this once the OpenTelemetry wire format protocol is adopted.\n\t\t// The specs indicate that component is a required tag\n\t\tonAttributeStringValueExists(attributes, spanAttributeKeyHTTPMethod, func(val string) { component = \"http\" })\n\n\t\tswitch component {\n\t\tcase \"\":\n\t\t\tfillRequestDataInternal(span, data)\n\t\tcase \"http\":\n\t\t\tfillRequestDataHTTP(span, data)\n\t\tcase \"grpc\":\n\t\t\tfillRequestDataGrpc(span, data)\n\t\tdefault:\n\t\t}\n\t}\n\n\treturn data\n}", "func StartSpan(ctx context.Context, name string) (context.Context, trace.Span) {\n\t// ensure context\n\tif ctx == nil {\n\t\tctx = context.Background()\n\t}\n\n\t// start span\n\tctx, span := GetGlobalTracer().Start(ctx, name)\n\n\treturn ctx, span\n}", "func WithHTTPRequestHeaders(ctx context.Context, h http.Header) (context.Context, error) {\n\tif _, ok := h[\"Content-Type\"]; ok {\n\t\treturn nil, errors.New(\"provided header cannot set Content-Type\")\n\t}\n\tif _, ok := h[\"XService-Version\"]; ok {\n\t\treturn nil, errors.New(\"provided header cannot set Xservice-Version\")\n\t}\n\n\tcopied := make(http.Header, len(h))\n\tfor k, vv := range h {\n\t\tif vv == nil {\n\t\t\tcopied[k] = nil\n\t\t\tcontinue\n\t\t}\n\t\tcopied[k] = make([]string, len(vv))\n\t\tcopy(copied[k], vv)\n\t}\n\n\treturn context.WithValue(ctx, RequestHeaderKey, copied), nil\n}", "func Extract(tracer opentracing.Tracer, r *http.Request) (opentracing.SpanContext, error) {\n\treturn tracer.Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(r.Header))\n}", "func StartSpanFromTrustedRequest(\n\tctx context.Context,\n\tname string,\n\ttruster HeaderTrustHandler,\n\tr *http.Request,\n) (context.Context, *tracing.Span) {\n\tvar spanHeaders tracing.Headers\n\tvar sampled bool\n\n\tif truster.TrustSpan(r) {\n\t\tif isHeaderSet(r.Header, TraceIDHeader) {\n\t\t\tspanHeaders.TraceID = r.Header.Get(TraceIDHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanIDHeader) {\n\t\t\tspanHeaders.SpanID = r.Header.Get(SpanIDHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanFlagsHeader) {\n\t\t\tspanHeaders.Flags = r.Header.Get(SpanFlagsHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanSampledHeader) {\n\t\t\tsampled = r.Header.Get(SpanSampledHeader) == spanSampledTrue\n\t\t\tspanHeaders.Sampled = &sampled\n\t\t}\n\t}\n\n\treturn tracing.StartSpanFromHeaders(ctx, name, spanHeaders)\n}", "func SpanID(r *http.Request) appdash.SpanID {\n\tif v := gcontext.Get(r, spanID); v != nil {\n\t\treturn v.(appdash.SpanID)\n\t}\n\treturn appdash.SpanID{}\n}", "func tracedTransport(\n\tcomponent string,\n\tpeerService string,\n\tspanNamer func(operation string, req *http.Request) string,\n\tpropagateTraceContext bool,\n) http.RoundTripper {\n\topts := []otelhttp.Option{\n\t\totelhttp.WithSpanNameFormatter(spanNamer),\n\t\totelhttp.WithSpanOptions(\n\t\t\ttrace.WithSpanKind(trace.SpanKindClient),\n\t\t\ttrace.WithAttributes(attribute.String(\"peer.service\", peerService), attribute.String(\"component\", component)),\n\t\t),\n\t}\n\tif !propagateTraceContext {\n\t\topts = append(opts, otelhttp.WithPropagators(noopPropagator{}))\n\t}\n\treturn otelhttp.NewTransport(http.DefaultTransport,\n\t\topts...,\n\t)\n}", "func newRequestScope(now time.Time, logger *logrus.Logger, request *http.Request, db *mongo.Database) RequestScope {\n\tl := log.NewLogger(logger, logrus.Fields{})\n\trequestID := request.Header.Get(\"X-Request-Id\")\n\tif requestID != \"\" {\n\t\tl.SetField(\"RequestID\", requestID)\n\t}\n\n\treturn &requestScope{\n\t\tLogger: l,\n\t\tnow: now,\n\t\trequestID: requestID,\n\t\tdb: db,\n\t\trequest: request,\n\t}\n}", "func (r *request) toHTTP() (*http.Request, error) {\n\t// Encode the query parameters\n\tr.url.RawQuery = r.params.Encode()\n\n\t// Check if we should encode the body\n\tif r.body == nil && r.obj != nil {\n\t\tif b, err := encodeBody(r.obj); err != nil {\n\t\t\treturn nil, err\n\t\t} else {\n\t\t\tr.body = b\n\t\t}\n\t}\n\n\tctx := func() context.Context {\n\t\tif r.ctx != nil {\n\t\t\treturn r.ctx\n\t\t}\n\t\treturn context.Background()\n\t}()\n\n\t// Create the HTTP request\n\treq, err := http.NewRequestWithContext(ctx, r.method, r.url.RequestURI(), r.body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header = r.header\n\n\t// Optionally configure HTTP basic authentication\n\tif r.url.User != nil {\n\t\tusername := r.url.User.Username()\n\t\tpassword, _ := r.url.User.Password()\n\t\treq.SetBasicAuth(username, password)\n\t} else if r.config.HttpAuth != nil {\n\t\treq.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)\n\t}\n\n\treq.Header.Add(\"Accept-Encoding\", \"gzip\")\n\tif r.token != \"\" {\n\t\treq.Header.Set(\"X-Nomad-Token\", r.token)\n\t}\n\n\treq.URL.Host = r.url.Host\n\treq.URL.Scheme = r.url.Scheme\n\treq.Host = r.url.Host\n\treturn req, nil\n}", "func NewSpanRequestFactory(options ...ClientOption) (RequestFactory, error) {\n\tf := &requestFactory{\n\t\tapiKeyHeader: apiKeyHeader,\n\t\tendpoint: \"trace-api.newrelic.com\",\n\t\tpath: \"/trace/v1\",\n\t\tuserAgent: defaultUserAgent,\n\t\tscheme: defaultScheme,\n\t\tzippers: newGzipPool(gzip.DefaultCompression),\n\t\tuncompressedBuffers: newUncompressedBufferPool(),\n\t}\n\terr := configure(f, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &hashRequestFactory{requestFactory: f}, nil\n}", "func (t *Trace) NewSpanFromRequest(r *http.Request) platform.Span {\n\ts := NewSpan(r.URL.Path).(*Span)\n\ts.logger = t.logger\n\treturn s\n}", "func TraceHandler(pattern string, handler http.Handler) (string, http.Handler) {\n\treturn pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Look for the request caller's SpanContext in the headers\n\t\t// If not found create a new SpanContext\n\t\tcarrier := opentracing.HTTPHeadersCarrier(r.Header)\n\t\ttracer := opentracing.GlobalTracer()\n\t\tparentSpanContext, _ := tracer.Extract(opentracing.HTTPHeaders, carrier)\n\n\t\tspanName := r.Method + \" \" + pattern\n\t\tvar span opentracing.Span\n\t\tif parentSpanContext == nil {\n\t\t\tspan = opentracing.StartSpan(spanName)\n\t\t} else {\n\t\t\tspan = opentracing.StartSpan(spanName, opentracing.ChildOf(parentSpanContext))\n\t\t}\n\t\tdefer span.Finish()\n\t\tr = r.WithContext(opentracing.ContextWithSpan(r.Context(), span))\n\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func FromHttpRequest(req *http.Request) TraceOption {\n\treturn func(t *Trace) {\n\t\tt.event = newHttpServerEvent(t.event.Message(), req)\n\t}\n}", "func NewRequestScope(now time.Time, ctx *iris.Context) RequestScope {\n\trequestID := ctx.Header().Get(\"X-Request-Id\")\n\treturn &requestScope{\n\t\tnow: now,\n\t\trequestID: requestID,\n\t}\n}", "func withRequestID(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\trequestID := r.Header.Get(\"x-request-id\")\n\t\tif requestID == \"\" {\n\t\t\trequestID = uuid.Must(uuid.NewV4()).String()\n\t\t}\n\n\t\tctx := log.With(r.Context(), zap.String(\"request_id\", requestID))\n\t\tr = r.WithContext(ctx)\n\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func DoRequestWithTrace(client *http.Client, req *http.Request) (*Trace, *http.Response, error) {\n\tclientTrace, ctx := NewTrace(req.URL.String())\n\treq = req.WithContext(ctx)\n\n\tresp, err := client.Do(req)\n\tif resp != nil {\n\t\tresp.Body = spyBodyReader{\n\t\t\tReadCloser: resp.Body,\n\t\t\tbodyReadTime: &clientTrace.BodyReadTime,\n\t\t}\n\t}\n\n\treturn clientTrace, resp, err\n}", "func TraceHandler(t trace.Tracer) server.HandlerWrapper {\n\t// return a handler wrapper\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\t// return a function that returns a function\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\t// don't store traces for debug\n\t\t\tif strings.HasPrefix(req.Endpoint(), \"Debug.\") {\n\t\t\t\treturn h(ctx, req, rsp)\n\t\t\t}\n\n\t\t\t// get the span\n\t\t\tnewCtx, s := t.Start(ctx, req.Service()+\".\"+req.Endpoint())\n\t\t\ts.Type = trace.SpanTypeRequestInbound\n\n\t\t\terr := h(newCtx, req, rsp)\n\t\t\tif err != nil {\n\t\t\t\ts.Metadata[\"error\"] = err.Error()\n\t\t\t}\n\n\t\t\t// finish\n\t\t\tt.Finish(s)\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func TraceHandler(t trace.Tracer) server.HandlerWrapper {\n\t// return a handler wrapper\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\t// return a function that returns a function\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\t// don't store traces for debug\n\t\t\tif strings.HasPrefix(req.Endpoint(), \"Debug.\") {\n\t\t\t\treturn h(ctx, req, rsp)\n\t\t\t}\n\n\t\t\t// get the span\n\t\t\tnewCtx, s := t.Start(ctx, req.Service()+\".\"+req.Endpoint())\n\t\t\ts.Type = trace.SpanTypeRequestInbound\n\n\t\t\terr := h(newCtx, req, rsp)\n\t\t\tif err != nil {\n\t\t\t\ts.Metadata[\"error\"] = err.Error()\n\t\t\t}\n\n\t\t\t// finish\n\t\t\tt.Finish(s)\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (c *Executor) newHTTPRequest(request *Request) (*http.Request, error) {\n\tif request.context == nil {\n\t\treturn nil, errNilContext\n\t}\n\tif !isSupportedHTTPMethod(request.method) {\n\t\treturn nil, fmt.Errorf(\"error executing request, found unsupport HTTP method %s\", request.method)\n\t}\n\n\t// JSON encode the object and use that as the body if specified, otherwise use the body as-is\n\treqBody := request.body\n\tif request.object != nil {\n\t\tb, err := encodeBody(request.object)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error executing request, failed to encode the request object to JSON: %w\", err)\n\t\t}\n\t\treqBody = b\n\t}\n\tu := path.Join(c.apiAddress, request.pathAndQuery)\n\n\tr, err := http.NewRequestWithContext(request.context, request.method, u, reqBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error executing request, failed to create a new underlying HTTP request: %w\", err)\n\t}\n\tr.Header.Set(\"User-Agent\", c.userAgent)\n\tif request.contentType != \"\" {\n\t\tr.Header.Set(\"Content-type\", request.contentType)\n\t}\n\tif request.contentLength != nil {\n\t\tr.ContentLength = *request.contentLength\n\t}\n\tfor k, v := range request.headers {\n\t\tr.Header.Set(k, v)\n\t}\n\n\treturn r, nil\n}", "func (s Server) WithTracing(next http.HandlerFunc) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\ttracingID, err := uuid.NewV1()\n\t\tif err != nil {\n\t\t\t// in case creating of tracing ID fails - don't border but server request!\n\t\t\tlogrus.Infof(\"[Server.WithTracing] could not create tracing ID: %v\\n\", err)\n\t\t\tnext(w, r)\n\t\t\treturn\n\t\t}\n\t\t// add tracing ID to request context for other function involved in the request\n\t\t// to have access to it\n\t\tctx := ctx_value.AddValue(r.Context(), \"tracingID\", fmt.Sprintf(\"%x\", tracingID.Bytes()[:4]))\n\t\tnext(w, r.WithContext(ctx))\n\t}\n}", "func RequestTracking(n janice.HandlerFunc) janice.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) error {\n\t\tid := uuid.NewString()\n\t\tctx := context.WithValue(r.Context(), reqIDKey, id)\n\n\t\treturn n(w, r.WithContext(ctx))\n\t}\n}", "func (f *lazyCallReq) Span() Span {\n\treturn callReqSpan(f.Frame)\n}", "func Middleware(service string, opts ...Option) echo.MiddlewareFunc {\n\tcfg := config{}\n\tfor _, opt := range opts {\n\t\topt.apply(&cfg)\n\t}\n\tif cfg.TracerProvider == nil {\n\t\tcfg.TracerProvider = otel.GetTracerProvider()\n\t}\n\ttracer := cfg.TracerProvider.Tracer(\n\t\ttracerName,\n\t\toteltrace.WithInstrumentationVersion(Version()),\n\t)\n\tif cfg.Propagators == nil {\n\t\tcfg.Propagators = otel.GetTextMapPropagator()\n\t}\n\n\tif cfg.Skipper == nil {\n\t\tcfg.Skipper = middleware.DefaultSkipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif cfg.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tc.Set(tracerKey, tracer)\n\t\t\trequest := c.Request()\n\t\t\tsavedCtx := request.Context()\n\t\t\tdefer func() {\n\t\t\t\trequest = request.WithContext(savedCtx)\n\t\t\t\tc.SetRequest(request)\n\t\t\t}()\n\t\t\tctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(request.Header))\n\t\t\topts := []oteltrace.SpanStartOption{\n\t\t\t\toteltrace.WithAttributes(semconvutil.HTTPServerRequest(service, request)...),\n\t\t\t\toteltrace.WithSpanKind(oteltrace.SpanKindServer),\n\t\t\t}\n\t\t\tif path := c.Path(); path != \"\" {\n\t\t\t\trAttr := semconv.HTTPRoute(path)\n\t\t\t\topts = append(opts, oteltrace.WithAttributes(rAttr))\n\t\t\t}\n\t\t\tspanName := c.Path()\n\t\t\tif spanName == \"\" {\n\t\t\t\tspanName = fmt.Sprintf(\"HTTP %s route not found\", request.Method)\n\t\t\t}\n\n\t\t\tctx, span := tracer.Start(ctx, spanName, opts...)\n\t\t\tdefer span.End()\n\n\t\t\t// pass the span through the request context\n\t\t\tc.SetRequest(request.WithContext(ctx))\n\n\t\t\t// serve the request to the next middleware\n\t\t\terr := next(c)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetAttributes(attribute.String(\"echo.error\", err.Error()))\n\t\t\t\t// invokes the registered HTTP error handler\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tstatus := c.Response().Status\n\t\t\tspan.SetStatus(semconvutil.HTTPServerStatus(status))\n\t\t\tif status > 0 {\n\t\t\t\tspan.SetAttributes(semconv.HTTPStatusCode(status))\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func WithSpanContextFunc(f func(context.Context) trace.SpanContext) Option {\n\treturn spanContextFuncOption{SpanContextFunc: f}\n}" ]
[ "0.693788", "0.6726092", "0.6687453", "0.6629484", "0.6353521", "0.62921053", "0.62571603", "0.62220114", "0.6179533", "0.617378", "0.6160135", "0.60833883", "0.6062903", "0.603451", "0.598833", "0.59190667", "0.58868927", "0.5860056", "0.583779", "0.57853985", "0.57668227", "0.5756513", "0.57359403", "0.5724136", "0.57077473", "0.563252", "0.55838037", "0.5575551", "0.55091226", "0.5496142", "0.5447925", "0.5377563", "0.5377085", "0.53582287", "0.5337397", "0.53348804", "0.5331677", "0.530136", "0.5292158", "0.5291443", "0.52819127", "0.52573234", "0.52495056", "0.5246276", "0.5221941", "0.5219465", "0.51854026", "0.51683617", "0.51597476", "0.51568943", "0.5154373", "0.51456356", "0.513215", "0.5104669", "0.5101574", "0.50972664", "0.5079711", "0.5074247", "0.50736547", "0.5059165", "0.5056126", "0.5047636", "0.504496", "0.50305116", "0.50274307", "0.50216043", "0.501548", "0.5002937", "0.4999947", "0.49964464", "0.49802348", "0.4975477", "0.49731016", "0.49505374", "0.49473482", "0.49445936", "0.49424243", "0.49342465", "0.49341515", "0.49263868", "0.49233702", "0.4914714", "0.4914428", "0.4910594", "0.49048364", "0.48988467", "0.48923713", "0.4879313", "0.48690358", "0.48687732", "0.4866872", "0.48660597", "0.48570883", "0.48570883", "0.4856614", "0.48389858", "0.48374882", "0.4831623", "0.4829475", "0.48233947" ]
0.7557659
0
FromHTTPRequest returns a Middleware HandlerFunc that tries to join with an OpenTracing trace found in the HTTP request headers and starts a new Span called `operationName`. If no trace could be found in the HTTP request headers, the Span will be a trace root. The Span is incorporated in the HTTP Context object and can be retrieved with opentracing.SpanFromContext(ctx).
func FromHTTPRequest(tracer opentracing.Tracer, operationName string, ) HandlerFunc { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // Try to join to a trace propagated in `req`. wireContext, err := tracer.Extract( opentracing.TextMap, opentracing.HTTPHeadersCarrier(req.Header), ) if err != nil { fmt.Printf("error encountered while trying to extract span: %+v\n", err) } // create span span := tracer.StartSpan(operationName, ext.RPCServerOption(wireContext)) defer span.Finish() // store span in context ctx := opentracing.ContextWithSpan(req.Context(), span) // update request context to include our new span req = req.WithContext(ctx) // next middleware or actual request handler next.ServeHTTP(w, req) }) } }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TracingMiddleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Attempt to join a span by getting trace info from the headers.\n\t\t// To start with use the URL as the opName since we haven't gotten to the router yet and\n\t\t// the router knows about opNames\n\t\topName := r.URL.Path\n\t\tvar sp opentracing.Span\n\t\tif sc, err := opentracing.GlobalTracer().\n\t\t\tExtract(opentracing.HTTPHeaders,\n\t\t\t\topentracing.HTTPHeadersCarrier(r.Header)); err != nil {\n\t\t\tsp = opentracing.StartSpan(opName)\n\t\t} else {\n\t\t\tsp = opentracing.StartSpan(opName, opentracing.ChildOf(sc))\n\t\t}\n\t\tdefer sp.Finish()\n\n\t\t// inject span ID into logs to aid in request debugging\n\t\tt := make(map[string]string)\n\t\tif err := sp.Tracer().Inject(sp.Context(), opentracing.TextMap,\n\t\t\topentracing.TextMapCarrier(t)); err == nil {\n\t\t\tif spanid, ok := t[\"ot-tracer-spanid\"]; ok {\n\t\t\t\tlogger.FromContext(r.Context()).AddContext(\"ot-tracer-spanid\", spanid)\n\t\t\t}\n\t\t}\n\n\t\tsp.LogEvent(\"request_received\")\n\t\tdefer func() {\n\t\t\tsp.LogEvent(\"request_finished\")\n\t\t}()\n\t\tnewCtx := opentracing.ContextWithSpan(r.Context(), sp)\n\t\t// Use a string pointer so layers below can modify it\n\t\tstrPtr := \"\"\n\t\tnewCtx = context.WithValue(newCtx, tracingOpName{}, &strPtr)\n\n\t\tsrw := &statusResponseWriter{\n\t\t\tstatus: 200,\n\t\t\tResponseWriter: w,\n\t\t}\n\n\t\ttags.HTTPMethod.Set(sp, r.Method)\n\t\ttags.SpanKind.Set(sp, tags.SpanKindRPCServerEnum)\n\t\ttags.HTTPUrl.Set(sp, r.URL.Path)\n\t\tsp.LogFields(opentracinglog.String(\"url-query\", r.URL.RawQuery))\n\n\t\tdefer func() {\n\t\t\ttags.HTTPStatusCode.Set(sp, uint16(srw.status))\n\t\t\tif srw.status >= 500 {\n\t\t\t\ttags.Error.Set(sp, true)\n\t\t\t}\n\t\t\t// Now that we have the opName let's try setting it\n\t\t\topName, ok := newCtx.Value(tracingOpName{}).(*string)\n\t\t\tif ok && opName != nil {\n\t\t\t\tsp.SetOperationName(*opName)\n\t\t\t}\n\t\t}()\n\n\t\th.ServeHTTP(srw, r.WithContext(newCtx))\n\t})\n}", "func StartSpan(req *restful.Request, operationName string) (opentracing.Span, context.Context) {\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range req.Request.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\t}\n\n\tspanContext, err := ExtractRequestHeader(req)\n\n\tvar span opentracing.Span\n\n\tif err != nil {\n\t\tspan = StartSpanSafe(operationName)\n\t} else {\n\t\tspan = StartSpanSafe(\n\t\t\toperationName,\n\t\t\topentracing.ChildOf(spanContext),\n\t\t)\n\t}\n\n\text.HTTPMethod.Set(span, req.Request.Method)\n\text.HTTPUrl.Set(span, req.Request.Host+req.Request.RequestURI)\n\n\tif abTraceID := req.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\tAddTag(span, event.TraceIDKey, abTraceID)\n\t}\n\n\treturn span, opentracing.ContextWithSpan(req.Request.Context(), span)\n}", "func HTTPMiddleware(tracer opentracing.Tracer, name string, logger log.Logger, next http.Handler) http.HandlerFunc {\n\toperationName := fmt.Sprintf(\"/%s HTTP[server]\", name)\n\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\twireContext, err := tracer.Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header),\n\t\t)\n\t\tif err != nil && err != opentracing.ErrSpanContextNotFound {\n\t\t\tlevel.Error(logger).Log(\"msg\", \"failed to extract tracer from request\", \"operationName\", operationName, \"err\", err)\n\t\t}\n\n\t\topts := []opentracing.StartSpanOption{ext.RPCServerOption(wireContext)}\n\t\t// Check for force tracing header and add it as a tag at the start of span.\n\t\t// This is required for the OpenTelemetry sampler to force tracing.\n\t\tif r.Header.Get(ForceTracingBaggageKey) != \"\" {\n\t\t\topts = append(opts, opentracing.Tag{Key: migration.ForceTracingAttributeKey, Value: \"true\"})\n\t\t}\n\n\t\tspan := tracer.StartSpan(\n\t\t\toperationName,\n\t\t\topts...,\n\t\t)\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\n\t\t// If client specified ForceTracingBaggageKey header, ensure span includes it to force tracing.\n\t\tspan.SetBaggageItem(strings.ToLower(ForceTracingBaggageKey), r.Header.Get(ForceTracingBaggageKey))\n\n\t\tif t, ok := tracer.(Tracer); ok {\n\t\t\tif traceID, ok := t.GetTraceIDFromSpanContext(span.Context()); ok {\n\t\t\t\tw.Header().Set(traceIDResponseHeader, traceID)\n\t\t\t}\n\t\t} else {\n\t\t\t// Alternative to set trace ID header, if bridge tracer is being used.\n\t\t\tif traceID, ok := migration.GetTraceIDFromBridgeSpan(span); ok {\n\t\t\t\tw.Header().Set(traceIDResponseHeader, traceID)\n\t\t\t}\n\t\t}\n\n\t\tnext.ServeHTTP(w, r.WithContext(opentracing.ContextWithSpan(ContextWithTracer(r.Context(), tracer), span)))\n\t\tspan.Finish()\n\t}\n}", "func OpenTracingMiddleware(handlerPackageName string) gin.HandlerFunc {\n\tif !opentracing.IsGlobalTracerRegistered() {\n\t\tfmt.Println(\"OpenTracing global tracer ever register yet\")\n\t\treturn nil\n\t}\n\treturn func(c *gin.Context) {\n\t\tvar span opentracing.Span\n\t\t// Extract trace context from HTTP Header\n\t\ttraceContext, err := opentracing.GlobalTracer().Extract(\n\t\t\topentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tvar opts []opentracing.StartSpanOption\n\t\tif err == nil {\n\t\t\topts = append(opts, opentracing.ChildOf(traceContext))\n\t\t}\n\t\tspan = opentracing.StartSpan(unknownOperation, opts...)\n\t\tspan.SetBaggageItem(BaggageRequestID, c.GetString(CtxRequestID))\n\n\t\tc.Set(CtxTraceSpan, span)\n\t\t// Keep going on next handlers\n\t\tc.Next()\n\n\t\t// Getting operation name from context if manually set\n\t\toperationName := c.GetString(CtxTraceOperationName)\n\t\tif operationName == \"\" {\n\t\t\toperationName = getHandlerName(handlerPackageName, c.HandlerNames())\n\t\t}\n\t\tspan.SetOperationName(operationName)\n\t\tc.Set(CtxTraceOperationName, operationName)\n\t\t// Set HTTP related information\n\t\tspan.SetTag(TagHTTPURL, c.Request.URL.String())\n\t\tspan.SetTag(TagHTTPMethod, c.Request.Method)\n\t\tspan.SetTag(TagHTTPUserAgent, c.Request.UserAgent())\n\t\tspan.SetTag(TagHTTPClientIP, c.ClientIP())\n\t\tspan.SetTag(TagHTTPStatusCode, c.Writer.Status())\n\t\t// Report to server\n\t\tspan.Finish()\n\t}\n}", "func OpenTracing(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\ttracer := opentracing.GlobalTracer()\n\n\t\t// Get any incoming tracing context via HTTP headers & create the span.\n\t\tctx, _ := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))\n\t\tspan := tracer.StartSpan(\"http.request\", ext.RPCServerOption(ctx))\n\t\tdefer span.Finish()\n\n\t\t// Set basic HTTP info\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\t\text.Component.Set(span, \"huma\")\n\t\tspan.SetTag(\"span.type\", \"web\")\n\n\t\t// Update context & continue the middleware chain.\n\t\tr = r.WithContext(opentracing.ContextWithSpan(r.Context(), span))\n\t\tws := statusRecorder{ResponseWriter: w}\n\t\tnext.ServeHTTP(&ws, r)\n\n\t\t// If we have a Chi route template, save it\n\t\tif chictx := chi.RouteContext(r.Context()); chictx != nil {\n\t\t\tspan.SetTag(\"resource.name\", chictx.RoutePattern())\n\t\t\tspan.SetOperationName(r.Method + \" \" + chictx.RoutePattern())\n\t\t}\n\n\t\t// Save the status code\n\t\text.HTTPStatusCode.Set(span, uint16(ws.status))\n\t})\n}", "func Tracing(operationName string) echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tspan := opentracing.SpanFromContext(c.Request().Context())\n\t\t\tif span == nil {\n\t\t\t\tspan = opentracing.StartSpan(operationName)\n\t\t\t}\n\t\t\tdefer span.Finish()\n\n\t\t\ttraceID := \"\"\n\t\t\tswitch sp := span.Context().(type) {\n\t\t\tcase jaeger.SpanContext:\n\t\t\t\ttraceID = sp.TraceID().String()\n\t\t\t}\n\t\t\tc.Set(\"trace_id\", traceID)\n\n\t\t\tspan.SetTag(\"component\", operationName)\n\t\t\tspan.SetTag(\"span.kind\", \"server\")\n\t\t\tspan.SetTag(\"http.url\", c.Request().Host+c.Request().RequestURI)\n\t\t\tspan.SetTag(\"http.method\", c.Request().Method)\n\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tspan.SetTag(\"error\", true)\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tspan.SetTag(\"http.status_code\", c.Response().Status)\n\t\t\tif c.Response().Status < 200 || c.Response().Status > 299 {\n\t\t\t\tspan.SetTag(\"error\", true)\n\t\t\t} else {\n\t\t\t\tspan.SetTag(\"error\", false)\n\t\t\t}\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func OpenTelemetryMiddleware(next http.Handler) http.Handler {\n\ttracer := global.Tracer(\"covidshield/request\")\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tattrs, entries, spanCtx := httptrace.Extract(r.Context(), r)\n\n\t\tr = r.WithContext(correlation.ContextWithMap(r.Context(), correlation.NewMap(correlation.MapUpdate{\n\t\t\tMultiKV: entries,\n\t\t})))\n\t\t_, span := tracer.Start(\n\t\t\ttrace.ContextWithRemoteSpanContext(r.Context(), spanCtx),\n\t\t\t\"HTTP Request\",\n\t\t\ttrace.WithAttributes(attrs...),\n\t\t)\n\t\tdefer span.End()\n\t\tnext.ServeHTTP(w, r)\n\t})\n}", "func OpenTracingHandler() gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tif !opentracing.IsGlobalTracerRegistered() {\n\t\t\tc.Next()\n\t\t\treturn\n\t\t}\n\t\tvar span opentracing.Span\n\t\ttracer := opentracing.GlobalTracer()\n\t\tspCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tif err != nil {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.Request.URL.Path,\n\t\t\t\topentracing.Tag{Key: string(ext.Component), Value: \"HTTP\"},\n\t\t\t\text.SpanKindRPCServer,\n\t\t\t)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.Request.URL.Path,\n\t\t\t\topentracing.ChildOf(spCtx),\n\t\t\t\topentracing.Tag{Key: string(ext.Component), Value: \"HTTP\"},\n\t\t\t\text.SpanKindRPCServer,\n\t\t\t)\n\t\t}\n\t\t// 设置http.url, http.method\n\t\text.HTTPMethod.Set(span, c.Request.Method)\n\t\text.HTTPUrl.Set(span, c.Request.URL.String())\n\n\t\tdefer span.Finish()\n\t\t// request context 中添加span 信息 用来传递\n\t\tc.Request = c.Request.WithContext(opentracing.ContextWithSpan(c.Request.Context(), span))\n\t\t_ = tracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tc.Next()\n\t}\n}", "func ToHTTPRequest(tracer opentracing.Tracer) RequestFunc {\n\treturn func(req *http.Request) *http.Request {\n\t\t// Retrieve the Span from context.\n\t\tif span := opentracing.SpanFromContext(req.Context()); span != nil {\n\n\t\t\t// We are going to use this span in a client request, so mark as such.\n\t\t\text.SpanKindRPCClient.Set(span)\n\n\t\t\t// Add some standard OpenTracing tags, useful in an HTTP request.\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\tspan.SetTag(zipkincore.HTTP_HOST, req.URL.Host)\n\t\t\tspan.SetTag(zipkincore.HTTP_PATH, req.URL.Path)\n\t\t\text.HTTPUrl.Set(\n\t\t\t\tspan,\n\t\t\t\tfmt.Sprintf(\"%s://%s%s\", req.URL.Scheme, req.URL.Host, req.URL.Path),\n\t\t\t)\n\n\t\t\t// Add information on the peer service we're about to contact.\n\t\t\tif host, portString, err := net.SplitHostPort(req.URL.Host); err == nil {\n\t\t\t\text.PeerHostname.Set(span, host)\n\t\t\t\tif port, err := strconv.Atoi(portString); err != nil {\n\t\t\t\t\text.PeerPort.Set(span, uint16(port))\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\text.PeerHostname.Set(span, req.URL.Host)\n\t\t\t}\n\n\t\t\t// Inject the Span context into the outgoing HTTP Request.\n\t\t\tif err := tracer.Inject(\n\t\t\t\tspan.Context(),\n\t\t\t\topentracing.TextMap,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t\t\t); err != nil {\n\t\t\t\tfmt.Printf(\"error encountered while trying to inject span: %+v\\n\", err)\n\t\t\t}\n\t\t}\n\t\treturn req\n\t}\n}", "func StartSpanFromHTTPContext(ctx context.Context, name string) (context.Context, *Span) {\n\tlogger := globalTracer.getLogger()\n\tspan := newSpan(nil, name, SpanTypeServer)\n\tdefer func() {\n\t\tonCreateServerSpan(span)\n\t\tspan.onStart()\n\t}()\n\tctx = opentracing.ContextWithSpan(ctx, span)\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.TraceIDContextKey); ok {\n\t\tif id, err := strconv.ParseUint(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed trace id in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.traceID = id\n\t\t}\n\t}\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.SpanIDContextKey); ok {\n\t\tif id, err := strconv.ParseUint(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed parent id in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.parentID = id\n\t\t}\n\t}\n\tif str, ok := httpbp.GetHeader(ctx, httpbp.SpanFlagsContextKey); ok {\n\t\tif flags, err := strconv.ParseInt(str, 10, 64); err != nil {\n\t\t\tlogger(fmt.Sprintf(\n\t\t\t\t\"Malformed flags in http ctx: %q, %v\",\n\t\t\t\tstr,\n\t\t\t\terr,\n\t\t\t))\n\t\t} else {\n\t\t\tspan.trace.flags = flags\n\t\t}\n\t}\n\tstr, ok := httpbp.GetHeader(ctx, httpbp.SpanSampledContextKey)\n\tsampled := ok && str == thriftbp.HeaderTracingSampledTrue\n\tspan.trace.sampled = sampled\n\n\treturn ctx, span\n}", "func FromHTTPReq(req *http.Request) (*Span, error) {\n\thc, ok := client.(HTTPCarrier)\n\tif !ok {\n\t\treturn nil, errors.New(\"not supported\")\n\t}\n\tid, err := hc.FromReq(req)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Span{ID: id}, nil\n}", "func (m *MuxTracer) trace(req *http.Request) (*http.Request, *tracer.Span) {\n\troute := mux.CurrentRoute(req)\n\tpath, err := route.GetPathTemplate()\n\tif err != nil {\n\t\t// when route doesn't define a path\n\t\tpath = \"unknown\"\n\t}\n\n\tresource := req.Method + \" \" + path\n\n\tspan := m.tracer.NewRootSpan(\"mux.request\", m.service, resource)\n\tspan.Type = ext.HTTPType\n\tspan.SetMeta(ext.HTTPMethod, req.Method)\n\tspan.SetMeta(ext.HTTPURL, path)\n\n\t// patch the span onto the request context.\n\ttreq := SetRequestSpan(req, span)\n\treturn treq, span\n}", "func TraceRequest(header string, nextRequestID IdGenerator) mux.MiddlewareFunc {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tctx := r.Context()\n\n\t\t\tvar err error\n\n\t\t\t// If request has the id then use it else generate one\n\t\t\trequestID := r.Header.Get(header)\n\t\t\tif requestID == \"\" {\n\t\t\t\trequestID, err = nextRequestID()\n\t\t\t}\n\n\t\t\t// No error then set it in the context & response\n\t\t\tif err == nil {\n\t\t\t\tctx = context.WithValue(ctx, header, requestID)\n\n\t\t\t\tw.Header().Set(header, requestID)\n\t\t\t} else {\n\t\t\t\tlog.Println(\"oops\", err)\n\t\t\t}\n\n\t\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t\t})\n\t}\n}", "func HandleRequest(w http.ResponseWriter, req *http.Request) {\n\t// Collect request parameters to add them to the entry HTTP span. We also need to make\n\t// sure that a proper span kind is set for the entry span, so that Instana could combine\n\t// it and its children into a call.\n\topts := []opentracing.StartSpanOption{\n\t\text.SpanKindRPCServer,\n\t\topentracing.Tags{\n\t\t\t\"http.host\": req.Host,\n\t\t\t\"http.method\": req.Method,\n\t\t\t\"http.protocol\": req.URL.Scheme,\n\t\t\t\"http.path\": req.URL.Path,\n\t\t},\n\t}\n\n\t// Check if there is an ongoing trace context provided with request and use\n\t// it as a parent for our entry span to ensure continuation.\n\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t)\n\tif err != nil {\n\t\topts = append(opts, ext.RPCServerOption(wireContext))\n\t}\n\n\t// Start the entry span adding collected tags and optional parent. The span name here\n\t// matters, as it allows Instana backend to classify the call as an HTTP one.\n\tspan := opentracing.GlobalTracer().StartSpan(\"g.http\", opts...)\n\tdefer span.Finish()\n\n\ttime.Sleep(300 * time.Millisecond)\n\tw.Write([]byte(\"Hello, world!\\n\"))\n}", "func FromWire(r *http.Request) (opentracing.SpanContext, error) {\n\treturn opentracing.GlobalTracer().Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(r.Header))\n}", "func InjectTrace(ctx context.Context, incomingReq *restful.Request,\n\toutgoingReq *http.Request) (*http.Request, opentracing.Span, context.Context) {\n\tspan, newCtx := StartSpanFromContext(ctx, \"outgoing request\")\n\tif span != nil {\n\t\text.HTTPUrl.Set(span, outgoingReq.Host+outgoingReq.RequestURI)\n\t\text.HTTPMethod.Set(span, outgoingReq.Method)\n\t\t_ = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(outgoingReq.Header))\n\n\t\tfor _, header := range forwardHeaders {\n\t\t\tif value := incomingReq.Request.Header.Get(header); value != \"\" {\n\t\t\t\toutgoingReq.Header.Set(header, value)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn outgoingReq, nil, nil\n\t}\n\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range outgoingReq.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"outgoing header : \", header)\n\t}\n\n\tif abTraceID := incomingReq.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\toutgoingReq.Header.Set(event.TraceIDKey, abTraceID)\n\t}\n\n\treturn outgoingReq, span, newCtx\n}", "func SpanContextFromRequest(req *http.Request) (trace.SpanContext, bool) {\n\tformat := tracecontext.HTTPFormat{}\n\treturn format.SpanContextFromRequest(req)\n}", "func Middleware(service string, opts ...Option) echo.MiddlewareFunc {\n\tcfg := config{}\n\tfor _, opt := range opts {\n\t\topt.apply(&cfg)\n\t}\n\tif cfg.TracerProvider == nil {\n\t\tcfg.TracerProvider = otel.GetTracerProvider()\n\t}\n\ttracer := cfg.TracerProvider.Tracer(\n\t\ttracerName,\n\t\toteltrace.WithInstrumentationVersion(Version()),\n\t)\n\tif cfg.Propagators == nil {\n\t\tcfg.Propagators = otel.GetTextMapPropagator()\n\t}\n\n\tif cfg.Skipper == nil {\n\t\tcfg.Skipper = middleware.DefaultSkipper\n\t}\n\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\tif cfg.Skipper(c) {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\tc.Set(tracerKey, tracer)\n\t\t\trequest := c.Request()\n\t\t\tsavedCtx := request.Context()\n\t\t\tdefer func() {\n\t\t\t\trequest = request.WithContext(savedCtx)\n\t\t\t\tc.SetRequest(request)\n\t\t\t}()\n\t\t\tctx := cfg.Propagators.Extract(savedCtx, propagation.HeaderCarrier(request.Header))\n\t\t\topts := []oteltrace.SpanStartOption{\n\t\t\t\toteltrace.WithAttributes(semconvutil.HTTPServerRequest(service, request)...),\n\t\t\t\toteltrace.WithSpanKind(oteltrace.SpanKindServer),\n\t\t\t}\n\t\t\tif path := c.Path(); path != \"\" {\n\t\t\t\trAttr := semconv.HTTPRoute(path)\n\t\t\t\topts = append(opts, oteltrace.WithAttributes(rAttr))\n\t\t\t}\n\t\t\tspanName := c.Path()\n\t\t\tif spanName == \"\" {\n\t\t\t\tspanName = fmt.Sprintf(\"HTTP %s route not found\", request.Method)\n\t\t\t}\n\n\t\t\tctx, span := tracer.Start(ctx, spanName, opts...)\n\t\t\tdefer span.End()\n\n\t\t\t// pass the span through the request context\n\t\t\tc.SetRequest(request.WithContext(ctx))\n\n\t\t\t// serve the request to the next middleware\n\t\t\terr := next(c)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetAttributes(attribute.String(\"echo.error\", err.Error()))\n\t\t\t\t// invokes the registered HTTP error handler\n\t\t\t\tc.Error(err)\n\t\t\t}\n\n\t\t\tstatus := c.Response().Status\n\t\t\tspan.SetStatus(semconvutil.HTTPServerStatus(status))\n\t\t\tif status > 0 {\n\t\t\t\tspan.SetAttributes(semconv.HTTPStatusCode(status))\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func Tracing() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\t//no tracing for static files\n\t\t\tif c.Path() == \"/*\" || c.Path() == \"/metrics\" {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\ttracer := opentracing.GlobalTracer()\n\t\t\treq := c.Request()\n\t\t\topName := \"HTTP \" + req.Method + \" URL: \" + c.Path()\n\n\t\t\tvar span opentracing.Span\n\t\t\tif ctx, err := tracer.Extract(opentracing.HTTPHeaders,\n\t\t\t\topentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\t\tspan = tracer.StartSpan(opName)\n\t\t\t} else {\n\t\t\t\tspan = tracer.StartSpan(opName, ext.RPCServerOption(ctx))\n\t\t\t}\n\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\text.HTTPUrl.Set(span, req.URL.String())\n\t\t\text.Component.Set(span, \"rest\")\n\n\t\t\treq = req.WithContext(opentracing.ContextWithSpan(req.Context(), span))\n\t\t\tc.SetRequest(req)\n\n\t\t\tc.Set(\"span\", span)\n\n\t\t\tdefer func() {\n\t\t\t\tstatus := c.Response().Status\n\t\t\t\tcommitted := c.Response().Committed\n\t\t\t\text.HTTPStatusCode.Set(span, uint16(status))\n\t\t\t\tif status >= http.StatusInternalServerError || !committed {\n\t\t\t\t\text.Error.Set(span, true)\n\t\t\t\t}\n\t\t\t\tspan.Finish()\n\t\t\t}()\n\n\t\t\treturn next(c)\n\t\t}\n\t}\n}", "func NewWithTracer(tracer opentracing.Tracer) tracing.StartSpan {\n\treturn func(serviceId string, operationId string, protocol tracing.WireProtocol, r *http.Request) (context.Context, tracing.ServerSpan) {\n\t\tspanName := serviceId + OperationDelimiter + operationId\n\t\twireContext, err := tracer.Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.Debug(\"Failed to extract opentracing headers\")\n\t\t}\n\n\t\t// Create the span referring to the RPC client if available.\n\t\t// If wireContext == nil, a root span will be created.\n\t\t// ext.RPCServerOption() sets tag span.kind=server\n\t\tserverSpan := tracer.StartSpan(\n\t\t\tspanName,\n\t\t\text.RPCServerOption(wireContext))\n\n\t\t//Set tag for the component\n\t\tserverSpan.SetTag(\"component\", ComponentTag)\n\n\t\t//Set headers, if header is not present the tag will be set to \"\"\n\t\tserverSpan.SetTag(\"http.user_agent\", r.Header.Get(\"User-Agent\"))\n\t\tserverSpan.SetTag(\"peer.address\", peerAddress(r))\n\t\tserverSpan.SetTag(\"wire.protocol\", protocol)\n\t\tserverSpan.SetTag(\"is_internal\", isInternal(r))\n\n\t\tspan := NewServerSpan(serverSpan)\n\n\t\tctx := opentracing.ContextWithSpan(r.Context(), serverSpan)\n\n\t\treturn ctx, span\n\t}\n}", "func newOpenTelemetryWrapper(\n\tctx context.Context,\n\tspanName string,\n) (openTelemetryWrapper, error) {\n\tif spanName == \"\" {\n\t\tspanName = defaultSpanName\n\t}\n\n\tot := openTelemetryWrapper{\n\t\tspanName: spanName,\n\t}\n\n\tversion, _ := caddy.Version()\n\tres, err := ot.newResource(webEngineName, version)\n\tif err != nil {\n\t\treturn ot, fmt.Errorf(\"creating resource error: %w\", err)\n\t}\n\n\ttraceExporter, err := otlptracegrpc.New(ctx)\n\tif err != nil {\n\t\treturn ot, fmt.Errorf(\"creating trace exporter error: %w\", err)\n\t}\n\n\tot.propagators = autoprop.NewTextMapPropagator()\n\n\ttracerProvider := globalTracerProvider.getTracerProvider(\n\t\tsdktrace.WithBatcher(traceExporter),\n\t\tsdktrace.WithResource(res),\n\t)\n\n\tot.handler = otelhttp.NewHandler(http.HandlerFunc(ot.serveHTTP),\n\t\tot.spanName,\n\t\totelhttp.WithTracerProvider(tracerProvider),\n\t\totelhttp.WithPropagators(ot.propagators),\n\t\totelhttp.WithSpanNameFormatter(ot.spanNameFormatter),\n\t)\n\n\treturn ot, nil\n}", "func Trace() gin.HandlerFunc {\n\n\treturn func(c *gin.Context) {\n\n\t\ttracer := opentracing.GlobalTracer()\n\t\twireContext, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Request.Header))\n\t\tvar span opentracing.Span\n\n\t\tif err != nil {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.HandlerName(),\n\t\t\t)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(\n\t\t\t\tc.HandlerName(),\n\t\t\t\text.RPCServerOption(wireContext),\n\t\t\t)\n\t\t}\n\n\t\tspan.SetTag(string(ext.SpanKind), string(ext.SpanKindRPCServerEnum))\n\t\tspan.SetTag(string(ext.PeerHostname), c.Request.Host)\n\t\tspan.SetTag(string(ext.HTTPUrl), c.Request.URL.Path)\n\t\tspan.SetTag(string(ext.HTTPMethod), c.Request.Method)\n\n\t\t// Wrap the request with span context\n\t\tc.Request = wrapRequestWithSpanContext(c.Request, span)\n\t\tc.Set(ContextKey, span)\n\t\t// call the next\n\t\t// set the response headers\n\t\ttracer.Inject(span.Context(), opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(c.Writer.Header()))\n\t\tc.Next()\n\t\tspan.SetTag(string(ext.HTTPStatusCode), c.Writer.Status())\n\n\t\tspan.Finish()\n\n\t}\n}", "func EchoRestTracerMiddleware(next echo.HandlerFunc) echo.HandlerFunc {\n\treturn func(c echo.Context) error {\n\t\treq := c.Request()\n\t\ttracer := opentracing.GlobalTracer()\n\t\toperationName := fmt.Sprintf(\"%s %s%s\", req.Method, req.Host, req.URL.Path)\n\n\t\tvar span opentracing.Span\n\t\tvar ctx context.Context\n\t\tif spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\tspan, ctx = opentracing.StartSpanFromContext(req.Context(), operationName)\n\t\t\text.SpanKindRPCServer.Set(span)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption((spanCtx)))\n\t\t\tctx = opentracing.ContextWithSpan(req.Context(), span)\n\t\t\text.SpanKindRPCClient.Set(span)\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tif len(body) < maxPacketSize { // limit request body size to 65000 bytes (if higher tracer cannot show root span)\n\t\t\tspan.SetTag(\"request.body\", string(body))\n\t\t} else {\n\t\t\tspan.SetTag(\"request.body.size\", len(body))\n\t\t}\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // reuse body\n\n\t\tspan.SetTag(\"http.headers\", req.Header)\n\t\text.HTTPUrl.Set(span, req.Host+req.RequestURI)\n\t\text.HTTPMethod.Set(span, req.Method)\n\n\t\tspan.LogEvent(\"start_handling_request\")\n\n\t\tdefer func() {\n\t\t\tspan.LogEvent(\"complete_handling_request\")\n\t\t\tspan.Finish()\n\t\t\tlogger.LogGreen(GetTraceURL(ctx))\n\t\t}()\n\n\t\tresBody := new(bytes.Buffer)\n\t\tmw := io.MultiWriter(c.Response().Writer, resBody)\n\t\twriter := &httpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}\n\t\tc.Response().Writer = writer\n\t\tc.SetRequest(req.WithContext(ctx))\n\n\t\terr := next(c)\n\t\tstatusCode := c.Response().Status\n\t\text.HTTPStatusCode.Set(span, uint16(statusCode))\n\t\tif statusCode >= http.StatusBadRequest {\n\t\t\text.Error.Set(span, true)\n\t\t}\n\n\t\tif resBody.Len() < maxPacketSize { // limit response body size to 65000 bytes (if higher tracer cannot show root span)\n\t\t\tspan.SetTag(\"response.body\", resBody.String())\n\t\t} else {\n\t\t\tspan.SetTag(\"response.body.size\", resBody.Len())\n\t\t}\n\t\treturn err\n\t}\n}", "func Trace(globalLogger *zap.Logger) func(next http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlogger := logging.FromContext(r.Context())\n\t\t\tid, err := uuid.NewV4()\n\t\t\tif err != nil {\n\t\t\t\tlogger.Error(errors.Wrap(err, \"error creating trace id\").Error())\n\t\t\t\tnext.ServeHTTP(w, r)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tstrID := id.String()\n\n\t\t\t// decorate the span with the id\n\t\t\tsdktrace.SpanFromContext(r.Context()).SetAttributes(attribute.String(traceHeader, strID))\n\n\t\t\t// Let a caller see what the traceID is\n\t\t\tw.Header().Add(traceHeader, strID)\n\n\t\t\t// Also insert as a key, value pair in the http request context\n\t\t\tnext.ServeHTTP(w, r.WithContext(trace.NewContext(r.Context(), id)))\n\t\t})\n\t}\n}", "func AddAsGetRequestMiddleware(stack *middleware.Stack) error {\n\treturn stack.Serialize.Insert(&asGetRequest{}, \"OperationSerializer\", middleware.After)\n}", "func WithTracing(handler http.Handler, tp oteltrace.TracerProvider, serviceName string) http.Handler {\n\topts := []otelhttp.Option{\n\t\totelhttp.WithPropagators(Propagators()),\n\t\totelhttp.WithTracerProvider(tp),\n\t}\n\t// With Noop TracerProvider, the otelhttp still handles context propagation.\n\t// See https://github.com/open-telemetry/opentelemetry-go/tree/main/example/passthrough\n\treturn otelhttp.NewHandler(handler, serviceName, opts...)\n}", "func MakeTracingHandler(h http.Handler, component string) http.Handler {\n\t// Wrap the provided handler with one that will inject\n\t// any propagated tracing context provided via a query parameter\n\t// if there isn't already a header containing tracing context.\n\t// This is required for scenarios using web sockets as headers\n\t// cannot be modified to inject the tracing context.\n\thandler := func(w http.ResponseWriter, r *http.Request) {\n\t\t// ensure headers have priority over query parameters\n\t\tif r.Header.Get(tracing.TraceParent) != \"\" {\n\t\t\th.ServeHTTP(w, r)\n\t\t\treturn\n\t\t}\n\n\t\ttraceParent := r.URL.Query()[tracing.TraceParent]\n\t\tif len(traceParent) > 0 {\n\t\t\tr.Header.Add(tracing.TraceParent, traceParent[0])\n\t\t}\n\n\t\th.ServeHTTP(w, r)\n\t}\n\n\treturn otelhttp.NewHandler(http.HandlerFunc(handler), component, otelhttp.WithSpanNameFormatter(tracehttp.HandlerFormatter))\n}", "func TraceHandler(t trace.Tracer) server.HandlerWrapper {\n\t// return a handler wrapper\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\t// return a function that returns a function\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\t// don't store traces for debug\n\t\t\tif strings.HasPrefix(req.Endpoint(), \"Debug.\") {\n\t\t\t\treturn h(ctx, req, rsp)\n\t\t\t}\n\n\t\t\t// get the span\n\t\t\tnewCtx, s := t.Start(ctx, req.Service()+\".\"+req.Endpoint())\n\t\t\ts.Type = trace.SpanTypeRequestInbound\n\n\t\t\terr := h(newCtx, req, rsp)\n\t\t\tif err != nil {\n\t\t\t\ts.Metadata[\"error\"] = err.Error()\n\t\t\t}\n\n\t\t\t// finish\n\t\t\tt.Finish(s)\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func TraceHandler(t trace.Tracer) server.HandlerWrapper {\n\t// return a handler wrapper\n\treturn func(h server.HandlerFunc) server.HandlerFunc {\n\t\t// return a function that returns a function\n\t\treturn func(ctx context.Context, req server.Request, rsp interface{}) error {\n\t\t\t// don't store traces for debug\n\t\t\tif strings.HasPrefix(req.Endpoint(), \"Debug.\") {\n\t\t\t\treturn h(ctx, req, rsp)\n\t\t\t}\n\n\t\t\t// get the span\n\t\t\tnewCtx, s := t.Start(ctx, req.Service()+\".\"+req.Endpoint())\n\t\t\ts.Type = trace.SpanTypeRequestInbound\n\n\t\t\terr := h(newCtx, req, rsp)\n\t\t\tif err != nil {\n\t\t\t\ts.Metadata[\"error\"] = err.Error()\n\t\t\t}\n\n\t\t\t// finish\n\t\t\tt.Finish(s)\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func TraceHandler(pattern string, handler http.Handler) (string, http.Handler) {\n\treturn pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t// Look for the request caller's SpanContext in the headers\n\t\t// If not found create a new SpanContext\n\t\tcarrier := opentracing.HTTPHeadersCarrier(r.Header)\n\t\ttracer := opentracing.GlobalTracer()\n\t\tparentSpanContext, _ := tracer.Extract(opentracing.HTTPHeaders, carrier)\n\n\t\tspanName := r.Method + \" \" + pattern\n\t\tvar span opentracing.Span\n\t\tif parentSpanContext == nil {\n\t\t\tspan = opentracing.StartSpan(spanName)\n\t\t} else {\n\t\t\tspan = opentracing.StartSpan(spanName, opentracing.ChildOf(parentSpanContext))\n\t\t}\n\t\tdefer span.Finish()\n\t\tr = r.WithContext(opentracing.ContextWithSpan(r.Context(), span))\n\n\t\thandler.ServeHTTP(w, r)\n\t})\n}", "func StartSpanWhenRequestRouted(ctx context.Context) (context.Context, error) {\n\tmethodName, ok := twirp.MethodName(ctx)\n\tif !ok {\n\t\treturn ctx, errNoMethodName\n\t}\n\n\tctx, _ = trace.StartSpan(ctx, methodName)\n\treturn ctx, nil\n}", "func (h *OpenTracing) Handler(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tvar span opentracing.Span\n\t\tvar err error\n\n\t\t// Attempt to join a trace by getting trace context from the headers.\n\t\twireContext, err := opentracing.GlobalTracer().Extract(\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\t// If for whatever reason we can't join, go ahead an start a new root span.\n\t\t\tspan = opentracing.StartSpan(r.URL.Path)\n\t\t} else {\n\t\t\tspan = opentracing.StartSpan(r.URL.Path, opentracing.ChildOf(wireContext))\n\t\t}\n\t\tdefer span.Finish()\n\n\t\thost, err := os.Hostname()\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Failed to get host name\")\n\t\t}\n\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(\n\t\t\tspan,\n\t\t\tfmt.Sprintf(\"%s://%s%s\", map[bool]string{true: \"https\", false: \"http\"}[h.https], r.Host, r.URL.Path),\n\t\t)\n\t\text.Component.Set(span, \"janus\")\n\t\text.SpanKind.Set(span, \"server\")\n\n\t\tspan.SetTag(\"peer.address\", r.RemoteAddr)\n\t\tspan.SetTag(\"host.name\", host)\n\n\t\t// Add information on the peer service we're about to contact.\n\t\tif host, portString, err := net.SplitHostPort(r.URL.Host); err == nil {\n\t\t\text.PeerHostname.Set(span, host)\n\t\t\tif port, err := strconv.Atoi(portString); err != nil {\n\t\t\t\text.PeerPort.Set(span, uint16(port))\n\t\t\t}\n\t\t} else {\n\t\t\text.PeerHostname.Set(span, r.URL.Host)\n\t\t}\n\n\t\terr = span.Tracer().Inject(\n\t\t\tspan.Context(),\n\t\t\topentracing.HTTPHeaders,\n\t\t\topentracing.HTTPHeadersCarrier(r.Header))\n\t\tif err != nil {\n\t\t\tlog.WithError(err).Error(\"Could not inject span context into header\")\n\t\t}\n\n\t\thandler.ServeHTTP(w, base.ToContext(r, span))\n\t})\n}", "func Trace(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\ttraceID, err := getTraceID(req)\n\t\tif err != nil {\n\t\t\tErrf(w, http.StatusInternalServerError, \"getting trace ID: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tctx := req.Context()\n\t\tctx = context.WithValue(ctx, traceIDKey, traceID)\n\t\treq = req.WithContext(ctx)\n\t\tnext.ServeHTTP(w, req)\n\t})\n}", "func TraceHandler(sensor instana.TracerLogger, routeID, pathTemplate string, handler fiber.Handler) fiber.Handler {\n\treturn func(c *fiber.Ctx) error {\n\t\tctx := c.UserContext()\n\t\treq := c.Request() // This is a fasthttp request and not a net/http request\n\n\t\theaders := collectAllHeaders(req)\n\n\t\topts := initSpanOptions(req, routeID)\n\n\t\ttracer := sensor.Tracer()\n\t\tif ps, ok := instana.SpanFromContext(ctx); ok {\n\t\t\ttracer = ps.Tracer()\n\t\t\topts = append(opts, ot.ChildOf(ps.Context()))\n\t\t}\n\n\t\topts = append(opts, extractStartSpanOptionsFromFastHTTPHeaders(tracer, req, headers, sensor)...)\n\n\t\tif isSynthetic(req) {\n\t\t\topts = append(opts, ot.Tag{Key: \"synthetic_call\", Value: true})\n\t\t}\n\n\t\tif isCustomPathTemplate(req, pathTemplate) {\n\t\t\topts = append(opts, ot.Tag{Key: \"http.path_tpl\", Value: pathTemplate})\n\t\t}\n\n\t\tspan := tracer.StartSpan(\"g.http\", opts...)\n\t\tdefer span.Finish()\n\n\t\tvar params url.Values\n\t\tcollectedHeaders := make(map[string]string)\n\n\t\t// ensure collected headers/params are sent in case of panic/error\n\t\tdefer func() {\n\t\t\tif len(collectedHeaders) > 0 {\n\t\t\t\tspan.SetTag(\"http.header\", collectedHeaders)\n\t\t\t}\n\t\t\tif len(params) > 0 {\n\t\t\t\tspan.SetTag(\"http.params\", params.Encode())\n\t\t\t}\n\t\t}()\n\n\t\tparams = collectHTTPParams(req, tracer)\n\n\t\tcollectableHTTPHeaders := configuredCollectableHeaders(tracer)\n\t\tcollectRequestHeaders(headers, collectableHTTPHeaders, collectedHeaders)\n\n\t\tdefer func() {\n\t\t\t// Be sure to capture any kind of panic/error\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tif e, ok := err.(error); ok {\n\t\t\t\t\tspan.SetTag(\"http.error\", e.Error())\n\t\t\t\t\tspan.LogFields(otlog.Error(e))\n\t\t\t\t} else {\n\t\t\t\t\tspan.SetTag(\"http.error\", err)\n\t\t\t\t\tspan.LogFields(otlog.Object(\"error\", err))\n\t\t\t\t}\n\n\t\t\t\tspan.SetTag(string(ext.HTTPStatusCode), http.StatusInternalServerError)\n\n\t\t\t\t// re-throw the panic\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}()\n\n\t\t// Inject the span details to the headers\n\t\th := make(ot.HTTPHeadersCarrier)\n\t\ttracer.Inject(span.Context(), ot.HTTPHeaders, h)\n\t\tfor k, v := range h {\n\t\t\tc.Response().Header.Del(k)\n\t\t\tc.Set(k, strings.Join(v, \",\"))\n\t\t}\n\n\t\tc.SetUserContext(instana.ContextWithSpan(ctx, span))\n\t\terr := handler(c)\n\n\t\tcollectResponseHeaders(c.Response(), collectableHTTPHeaders, collectedHeaders)\n\t\tprocessResponseStatus(c.Response().StatusCode(), span)\n\n\t\treturn err\n\t}\n}", "func FromHttpRequest(req *http.Request) TraceOption {\n\treturn func(t *Trace) {\n\t\tt.event = newHttpServerEvent(t.event.Message(), req)\n\t}\n}", "func Trace(name string) gin.HandlerFunc {\n\treturn func(c *gin.Context) {\n\t\tvar tracer trace.Trace\n\t\tif id := c.Request.Header.Get(\"x-request-id\"); len(id) > 0 {\n\t\t\ttracer = trace.WithID(name, id)\n\t\t} else {\n\t\t\ttracer = trace.New(name)\n\t\t}\n\t\tc.Writer.Header().Set(\"x-request-id\", tracer.ID())\n\n\t\tlastRoute, ip := func(r *http.Request) (string, string) {\n\t\t\tlastRoute := strings.Split(r.RemoteAddr, \":\")[0]\n\t\t\tif ip, exists := r.Header[\"X-Real-IP\"]; exists && len(ip) > 0 {\n\t\t\t\treturn lastRoute, ip[0]\n\t\t\t}\n\t\t\tif ips, exists := r.Header[\"X-Forwarded-For\"]; exists && len(ips) > 0 {\n\t\t\t\treturn lastRoute, ips[0]\n\t\t\t}\n\t\t\treturn lastRoute, lastRoute\n\t\t}(c.Request)\n\n\t\ttracer.Infof(\"event=[request-in] remote=[%s] route=[%s] method=[%s] url=[%s]\", ip, lastRoute, c.Request.Method, c.Request.URL.String())\n\t\tdefer tracer.Info(\"event=[request-out]\")\n\n\t\tctx := context.WithValue(c.Request.Context(), tracerLogHandlerID, tracer)\n\t\tctx = context.WithValue(ctx, realIPValueID, ip)\n\t\tc.Request = c.Request.WithContext(ctx)\n\n\t\tc.Next()\n\t}\n}", "func GetOpenTracingSpanFromContext(c *gin.Context) opentracing.Span {\n\trawSpan, ok := c.Get(CtxTraceSpan)\n\tif ok {\n\t\treturn rawSpan.(opentracing.Span)\n\t}\n\treturn opentracing.StartSpan(unknownOperation)\n}", "func (t *HadeTraceService) InjectHTTP(req *http.Request, tc *contract.TraceContext) *http.Request {\n\treq.Header.Add(contract.TraceKeyTraceID, tc.TraceID)\n\treq.Header.Add(contract.TraceKeySpanID, tc.SpanID)\n\treq.Header.Add(contract.TraceKeyCspanID, tc.CspanID)\n\treq.Header.Add(contract.TraceKeyParentID, tc.ParentID)\n\treturn req\n}", "func (m *SpanManager) NewSpanFromRequest(name string, req Request) *Span {\n\tif req.Sampled != nil && !*req.Sampled {\n\t\treturn NewDisabledTrace()\n\t}\n\n\tflags := int64(0)\n\tif req.Flags != nil {\n\t\tflags = *req.Flags\n\t}\n\n\tif req.TraceId == nil || req.SpanId == nil {\n\t\tif req.Sampled != nil {\n\t\t\treturn m.NewSampledTrace(name, flags&1 > 0)\n\t\t}\n\t\treturn m.NewTrace(name)\n\t}\n\n\treturn &Span{\n\t\tdata: zipkin.Span{\n\t\t\tTraceId: *req.TraceId,\n\t\t\tName: name,\n\t\t\tId: *req.SpanId,\n\t\t\tParentId: req.ParentId,\n\t\t\tDebug: flags&1 > 0},\n\t\tserver: true,\n\t\tmanager: m}\n}", "func (h *httpTracePolicy) Do(req *policy.Request) (resp *http.Response, err error) {\n\trawTracer := req.Raw().Context().Value(shared.CtxWithTracingTracer{})\n\tif tracer, ok := rawTracer.(tracing.Tracer); ok {\n\t\tattributes := []tracing.Attribute{\n\t\t\t{Key: attrHTTPMethod, Value: req.Raw().Method},\n\t\t\t{Key: attrHTTPURL, Value: getSanitizedURL(*req.Raw().URL, h.allowedQP)},\n\t\t\t{Key: attrNetPeerName, Value: req.Raw().URL.Host},\n\t\t}\n\n\t\tif ua := req.Raw().Header.Get(shared.HeaderUserAgent); ua != \"\" {\n\t\t\tattributes = append(attributes, tracing.Attribute{Key: attrHTTPUserAgent, Value: ua})\n\t\t}\n\t\tif reqID := req.Raw().Header.Get(shared.HeaderXMSClientRequestID); reqID != \"\" {\n\t\t\tattributes = append(attributes, tracing.Attribute{Key: attrAZClientReqID, Value: reqID})\n\t\t}\n\n\t\tctx := req.Raw().Context()\n\t\tctx, span := tracer.Start(ctx, \"HTTP \"+req.Raw().Method, &tracing.SpanOptions{\n\t\t\tKind: tracing.SpanKindClient,\n\t\t\tAttributes: attributes,\n\t\t})\n\n\t\tdefer func() {\n\t\t\tif resp != nil {\n\t\t\t\tspan.SetAttributes(tracing.Attribute{Key: attrHTTPStatusCode, Value: resp.StatusCode})\n\t\t\t\tif resp.StatusCode > 399 {\n\t\t\t\t\tspan.SetStatus(tracing.SpanStatusError, resp.Status)\n\t\t\t\t}\n\t\t\t\tif reqID := resp.Header.Get(shared.HeaderXMSRequestID); reqID != \"\" {\n\t\t\t\t\tspan.SetAttributes(tracing.Attribute{Key: attrAZServiceReqID, Value: reqID})\n\t\t\t\t}\n\t\t\t} else if err != nil {\n\t\t\t\t// including the output from err.Error() might disclose URL query parameters.\n\t\t\t\t// so instead of attempting to sanitize the output, we simply output the error type.\n\t\t\t\tspan.SetStatus(tracing.SpanStatusError, fmt.Sprintf(\"%T\", err))\n\t\t\t}\n\t\t\tspan.End()\n\t\t}()\n\n\t\treq = req.WithContext(ctx)\n\t}\n\tresp, err = req.Next()\n\treturn\n}", "func (i *instrumentor) tracingBegin(ctx context.Context, eventJSON []byte) (context.Context, trace.Span) {\n\t// Add trace id to context\n\tmc := i.configuration.EventToCarrier(eventJSON)\n\tctx = i.configuration.Propagator.Extract(ctx, mc)\n\n\tvar span trace.Span\n\tspanName := os.Getenv(\"AWS_LAMBDA_FUNCTION_NAME\")\n\n\tvar attributes []attribute.KeyValue\n\tlc, ok := lambdacontext.FromContext(ctx)\n\tif !ok {\n\t\terrorLogger.Println(\"failed to load lambda context from context, ensure tracing enabled in Lambda\")\n\t}\n\tif lc != nil {\n\t\tctxRequestID := lc.AwsRequestID\n\t\tattributes = append(attributes, semconv.FaaSExecution(ctxRequestID))\n\n\t\t// Some resource attrs added as span attrs because lambda\n\t\t// resource detectors are created before a lambda\n\t\t// invocation and therefore lack lambdacontext.\n\t\t// Create these attrs upon first invocation\n\t\tif len(i.resAttrs) == 0 {\n\t\t\tctxFunctionArn := lc.InvokedFunctionArn\n\t\t\tattributes = append(attributes, semconv.FaaSID(ctxFunctionArn))\n\t\t\tarnParts := strings.Split(ctxFunctionArn, \":\")\n\t\t\tif len(arnParts) >= 5 {\n\t\t\t\tattributes = append(attributes, semconv.CloudAccountID(arnParts[4]))\n\t\t\t}\n\t\t}\n\t\tattributes = append(attributes, i.resAttrs...)\n\t}\n\n\tctx, span = i.tracer.Start(ctx, spanName, trace.WithSpanKind(trace.SpanKindServer), trace.WithAttributes(attributes...))\n\n\treturn ctx, span\n}", "func LogRequest(span opentracing.Span, r *http.Request) {\n\tif span != nil && r != nil {\n\t\text.HTTPMethod.Set(span, r.Method)\n\t\text.HTTPUrl.Set(span, r.URL.String())\n\t\tspan.SetTag(\"http.host\", r.Host)\n\t}\n}", "func traceWrap(c *gin.Context) {\n\tappIDKey, err := tag.NewKey(\"fn.app_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tfnKey, err := tag.NewKey(\"fn.fn_id\")\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\tctx, err := tag.New(c.Request.Context(),\n\t\ttag.Insert(appIDKey, c.Param(api.AppID)),\n\t\ttag.Insert(fnKey, c.Param(api.FnID)),\n\t)\n\tif err != nil {\n\t\tlogrus.Fatal(err)\n\t}\n\n\t// TODO inspect opencensus more and see if we need to define a header ourselves\n\t// to trigger per-request spans (we will want this), we can set sampler here per request.\n\n\tctx, span := trace.StartSpan(ctx, \"serve_http\")\n\tdefer span.End()\n\n\t// spans like these, not tags\n\tspan.AddAttributes(\n\t\ttrace.StringAttribute(\"fn.app_id\", c.Param(api.AppID)),\n\t\ttrace.StringAttribute(\"fn.fn_id\", c.Param(api.FnID)),\n\t)\n\n\tc.Request = c.Request.WithContext(ctx)\n\tc.Next()\n}", "func (t *Trace) NewSpanFromRequest(r *http.Request) platform.Span {\n\ts := NewSpan(r.URL.Path).(*Span)\n\ts.logger = t.logger\n\treturn s\n}", "func (t *TraceWrapper) generateSpanFromRequest(r *http.Request) *SpanWrapper {\n\ts := &SpanWrapper{\n\t\tspanList: make([]platform.Span, len(t.traceList)),\n\t}\n\tfor i, tr := range t.traceList {\n\t\tspan := tr.NewSpanFromRequest(r)\n\t\ts.spanList[i] = span\n\t}\n\tt.setDefaultDataset(s)\n\treturn s\n}", "func NewTraceMiddleware() func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn traceMiddleware(next)\n\t}\n}", "func Middleware(h http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {\n\t\ttracer := opentracing.GlobalTracer()\n\t\toperationName := fmt.Sprintf(\"%s %s%s\", req.Method, req.Host, req.URL.Path)\n\n\t\tvar span opentracing.Span\n\t\tvar ctx context.Context\n\t\tif spanCtx, err := tracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(req.Header)); err != nil {\n\t\t\tspan, ctx = opentracing.StartSpanFromContext(req.Context(), operationName)\n\t\t\text.SpanKindRPCServer.Set(span)\n\t\t} else {\n\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption((spanCtx)))\n\t\t\tctx = opentracing.ContextWithSpan(req.Context(), span)\n\t\t\text.SpanKindRPCClient.Set(span)\n\t\t}\n\n\t\tbody, _ := ioutil.ReadAll(req.Body)\n\t\tbodyString := string(golib.MaskJSONPassword(body))\n\t\tbodyString = golib.MaskPassword(bodyString)\n\n\t\tisRemoveBody, ok := req.Context().Value(\"remove-tag-body\").(bool)\n\t\tif ok {\n\t\t\tif !isRemoveBody {\n\t\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t\t}\n\t\t} else {\n\t\t\tspan.SetTag(\"body\", bodyString)\n\t\t}\n\n\t\treq.Body = ioutil.NopCloser(bytes.NewBuffer(body)) // reuse body\n\n\t\tspan.SetTag(\"http.headers\", req.Header)\n\t\text.HTTPUrl.Set(span, req.Host+req.RequestURI)\n\t\text.HTTPMethod.Set(span, req.Method)\n\n\t\tspan.LogEvent(\"start_handling_request\")\n\n\t\tdefer func() {\n\t\t\tspan.LogEvent(\"complete_handling_request\")\n\t\t\tspan.Finish()\n\t\t}()\n\n\t\th.ServeHTTP(w, req.WithContext(ctx))\n\t})\n}", "func StartSpanIfParentSpanExist(req *restful.Request, operationName string) (opentracing.Span, context.Context) {\n\tif logrus.GetLevel() >= logrus.DebugLevel {\n\t\theader := make(map[string]string)\n\n\t\tfor key, val := range req.Request.Header {\n\t\t\tkey = strings.ToLower(key)\n\t\t\tif !strings.Contains(key, \"auth\") {\n\t\t\t\theader[key] = val[0]\n\t\t\t}\n\t\t}\n\n\t\tlogrus.Debug(\"incoming header : \", header)\n\t}\n\n\tspanContext, err := ExtractRequestHeader(req)\n\tif err != nil {\n\t\treturn nil, nil\n\t}\n\n\tspan := StartSpanSafe(\n\t\toperationName,\n\t\topentracing.ChildOf(spanContext),\n\t)\n\text.HTTPMethod.Set(span, req.Request.Method)\n\text.HTTPUrl.Set(span, req.Request.Host+req.Request.RequestURI)\n\n\tif abTraceID := req.Request.Header.Get(event.TraceIDKey); abTraceID != \"\" {\n\t\tAddTag(span, event.TraceIDKey, abTraceID)\n\t}\n\n\treturn span, opentracing.ContextWithSpan(req.Request.Context(), span)\n}", "func formatHTTPRequest(r *HTTPRequest) httpRequestGKE {\n\treturn httpRequestGKE{\n\t\tRequestMethod: r.Request.Method,\n\t\tRequestURL: r.Request.URL.String(),\n\t\tReferer: r.Request.Referer(),\n\t\tProtocol: r.Request.Proto,\n\t\tRequestSize: fmt.Sprintf(\"%d\", r.RequestSize),\n\t\tStatus: r.Status,\n\t\tResponseSize: fmt.Sprintf(\"%d\", r.ResponseSize),\n\t\tUserAgent: r.Request.UserAgent(),\n\t\tRemoteIP: r.RemoteIP,\n\t\tServerIP: r.ServerIP,\n\t\tLatency: fmt.Sprintf(\"%fs\", r.Latency.Seconds()),\n\t\tCacheLookup: r.CacheLookup,\n\t\tCacheHit: r.CacheHit,\n\t\tCacheFillBytes: r.CacheFillBytes,\n\t\t// CacheValidatedWithOriginServer: r.CacheValidatedWithOriginServer,\n\t}\n}", "func (t *TraceTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\trt := t.RoundTripper\n\tif rt == nil {\n\t\trt = http.DefaultTransport\n\t}\n\tvar tr opentracing.Span\n\tif t.activeSpanKey != \"\" {\n\t\tacvspans := req.Context().Value(t.activeSpanKey)\n\t\tif acvspans == nil{\n\t\t\treturn rt.RoundTrip(req)\n\t\t}\n\t\ttr = opentracing.SpanFromContext(opentracing.ContextWithSpan(req.Context(), acvspans.(opentracing.Span)))\n\t} else {\n\t\ttr = opentracing.SpanFromContext(req.Context())\n\t}\n\n\tif tr == nil {\n\t\treturn rt.RoundTrip(req)\n\t}\n\toperationName := \"HTTP:\" + req.Method\n\t//get start new tracer\n\ttracer := tr.Tracer()\n\tspan := tracer.StartSpan(operationName, opentracing.ChildOf(tr.Context()))\n\n\text.DBType.Set(span, \"http\")\n\t//ext.PeerAddress.Set(span, req.URL.String())\n\text.HTTPMethod.Set(span,req.Method)\n\text.HTTPUrl.Set(span, req.URL.String())\n\t/*ext.SpanKind.Set(span, ext.SpanKindRPCClientEnum)*/\n\text.Component.Set(span,_defaultComponentName)\n\t//end\n\tif t.peerService != \"\" {\n\t\text.PeerService.Set(span,t.peerService)\n\t}\n\tfor _, v := range t.extraTags {\n\t\tspan.SetTag(v.Key, v.Value)\n\t}\n\t// inject trace to http header\n\ttracer.Inject(span.Context(),opentracing.HTTPHeaders,req.Header)\n\n\t// ct := clientTracer{tr: tr}\n\t// req = req.WithContext(httptrace.WithClientTrace(req.Context(), ct.clientTrace()))\n\tresp, err := rt.RoundTrip(req)\n\n\tif err != nil {\n\t\text.Error.Set(span, true)\n\t\tspan.LogFields(log.String(\"event\", \"error\"), log.String(\"message\", err.Error()))\n\t\tspan.Finish()\n\t\treturn resp, err\n\t}\n\n\text.HTTPStatusCode.Set(span,uint16(resp.StatusCode))\n\tif resp.StatusCode >= 400 {\n\t\text.Error.Set(span, true)\n\t}\n\tspan.Finish()\n\treturn resp, err\n}", "func (op OperationRequest) HTTPRequest(horizonURL string) (*http.Request, error) {\n\tendpoint, err := op.BuildURL()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn http.NewRequest(\"GET\", horizonURL+endpoint, nil)\n}", "func (ot *openTelemetryWrapper) spanNameFormatter(operation string, r *http.Request) string {\n\treturn r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer).ReplaceAll(operation, \"\")\n}", "func InterceptRequest(f func(http.Header)) *RequestInterceptor {\n\treturn &RequestInterceptor{Intercept: f}\n}", "func LogHTTPRequest(next http.Handler) http.Handler {\n\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlogData := &HTTPLogInfo{\n\t\t\tMethod: r.Method,\n\t\t\tProto: r.Proto,\n\t\t\tURI: r.URL.String(),\n\t\t\tHost: r.Host,\n\t\t\tUserAgent: r.UserAgent(),\n\t\t}\n\t\tlogData.IPAddr = getRemoteAddress(r)\n\n\t\t_, err := r.Cookie(\"cookie-name\")\n\t\tif err == nil {\n\t\t\tlogData.UserID = getUserIDFromSession(w, r)\n\t\t}\n\n\t\thttpResponseData := httpsnoop.CaptureMetrics(next, w, r)\n\n\t\tlogData.StatusCode = httpResponseData.Code\n\t\tlogData.ContentLength = httpResponseData.Written\n\t\tlogData.Date = time.Now().UTC().Format(layout)\n\t\tlogData.Duration = httpResponseData.Duration\n\n\t\tutils.LogHTTP.Println(getFormattedLog(logData))\n\t})\n}", "func MakeTracingMiddleware(component string) func(http.Handler) http.Handler {\n\treturn func(next http.Handler) http.Handler {\n\t\treturn MakeTracingHandler(next, component)\n\t}\n}", "func SpanFromHeaders(tracer opentracing.Tracer, operationName string,\n\tpsr ParentSpanReferenceFunc, advancedOpts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tspanContext, err := tracer.Extract(opentracing.TextMap, opentracing.HTTPHeadersCarrier(ctx.Request.Header))\n\t\tif err != nil {\n\t\t\tif AbortOnErrors {\n\t\t\t\tctx.AbortWithError(http.StatusInternalServerError, err)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\topts := append([]opentracing.StartSpanOption{psr(spanContext)}, advancedOpts...)\n\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func SpanFromContext(tracer opentracing.Tracer, operationName string,\n\tadvancedOpts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tvar opts []opentracing.StartSpanOption\n\t\tparentSpanI, _ := ctx.Get(spanContextKey)\n\t\tif parentSpan, typeOk := parentSpanI.(opentracing.Span); parentSpan != nil && typeOk {\n\t\t\topts = append(opts, opentracing.ChildOf(parentSpan.Context()))\n\t\t} else {\n\t\t\tif AbortOnErrors {\n\t\t\t\tctx.AbortWithError(http.StatusInternalServerError, ErrSpanNotFound)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\t\topts = append(opts, advancedOpts...)\n\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func Tracing(tracer opentracing.Tracer) zenrpc.MiddlewareFunc {\n\treturn func(invoke zenrpc.InvokeFunc) zenrpc.InvokeFunc {\n\t\treturn func(ctx context.Context, method string, params json.RawMessage) zenrpc.Response {\n\t\t\toperationName := zenrpc.NamespaceFromContext(ctx) + \".\" + method\n\n\t\t\t// Step one\n\t\t\t// Try to join to a trace propagated in `req`.\n\t\t\tif req, ok := zenrpc.RequestFromContext(ctx); ok {\n\t\t\t\tvar span opentracing.Span\n\t\t\t\twireContext, _ := tracer.Extract(\n\t\t\t\t\topentracing.TextMap,\n\t\t\t\t\topentracing.HTTPHeadersCarrier(req.Header),\n\t\t\t\t)\n\t\t\t\tspan = tracer.StartSpan(operationName, ext.RPCServerOption(wireContext))\n\t\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\t\text.HTTPUrl.Set(span, req.URL.String())\n\t\t\t\tctx = opentracing.ContextWithSpan(ctx, span)\n\t\t\t}\n\n\t\t\t// Step two\n\t\t\t// Trace server\n\t\t\tserverSpan := opentracing.SpanFromContext(ctx)\n\t\t\tif serverSpan == nil {\n\t\t\t\t// All we can do is create a new root span.\n\t\t\t\tserverSpan = tracer.StartSpan(method)\n\t\t\t} else {\n\t\t\t\tserverSpan.SetOperationName(method)\n\t\t\t}\n\t\t\tdefer serverSpan.Finish()\n\t\t\text.SpanKindRPCServer.Set(serverSpan)\n\t\t\tctx = opentracing.ContextWithSpan(ctx, serverSpan)\n\n\t\t\treturn invoke(ctx, method, params)\n\t\t}\n\t}\n}", "func ToWire(spanCtx opentracing.SpanContext, r *http.Request) error {\n\tcarrier := opentracing.HTTPHeadersCarrier(r.Header)\n\terr := opentracing.GlobalTracer().Inject(\n\t\tspanCtx,\n\t\topentracing.HTTPHeaders,\n\t\tcarrier)\n\treturn err\n}", "func NewSpan(tracer opentracing.Tracer, operationName string, opts ...opentracing.StartSpanOption) gin.HandlerFunc {\n\treturn func(ctx *gin.Context) {\n\t\tspan := tracer.StartSpan(operationName, opts...)\n\t\tctx.Set(spanContextKey, span)\n\t\tdefer span.Finish()\n\n\t\tctx.Next()\n\t}\n}", "func FormatHTTPRequest(r *http.Request) string {\n\treturn FormatHTTPRequestWithSeparator(r, \"\\n\")\n}", "func Trace(handler http.Handler) http.Handler {\n\tif handler == nil {\n\t\thandler = http.DefaultServeMux\n\t}\n\treturn TracingHandlerFunc(\n\t\thttp.HandlerFunc(\n\t\t\tfunc(w http.ResponseWriter, r *http.Request) {\n\t\t\t\thandler.ServeHTTP(w, r)\n\t\t\t},\n\t\t),\n\t)\n}", "func ExtractRequestHeader(req *restful.Request) (opentracing.SpanContext, error) {\n\tglobalTracerAccessMutex.Lock()\n\tdefer globalTracerAccessMutex.Unlock()\n\n\treturn opentracing.GlobalTracer().Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(req.Request.Header))\n}", "func createRequest(t *testing.T, method string, path string, body io.Reader) (*http.Request, *httptest.ResponseRecorder, *bytes.Buffer) {\n\trecorder := httptest.NewRecorder()\n\treq, err := http.NewRequest(method, path, body)\n\tif err != nil {\n\t\tt.Fatal(err)\n\t}\n\n\tlogger, output := NewFakeLogger()\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.LoggerKey, &logger))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.AuthUserKey, \"test@draupnir\"))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.RefreshTokenKey, \"refresh-token\"))\n\treq = req.WithContext(context.WithValue(req.Context(), middleware.UserIPAddressKey, \"1.2.3.4\"))\n\n\treturn req, recorder, output\n}", "func Extract(tracer opentracing.Tracer, r *http.Request) (opentracing.SpanContext, error) {\n\treturn tracer.Extract(\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(r.Header))\n}", "func SpanContextToRequest(span *trace.Span, req *http.Request) {\n\tformat := tracecontext.HTTPFormat{}\n\tformat.SpanContextToRequest(span.SpanContext(), req)\n}", "func (tracer Tracer) WithRequest(r *http.Request) *http.Request {\n\tif !tracer.IsSampled() {\n\t\treturn r\n\t}\n\tctx := r.Context()\n\tctx = httptrace.WithClientTrace(ctx, tracer.trace)\n\treturn r.WithContext(ctx)\n}", "func NewMiddleware(handler http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tlogger := WithContext(r.Context())\n\n\t\tlogger.Infow(\"Started request\",\n\t\t\t\"method\", r.Method,\n\t\t\t\"path\", r.URL.Path,\n\t\t)\n\n\t\t// reverse proxy replaces original request with target request, so keep original one\n\t\toriginalURL := &url.URL{}\n\t\t*originalURL = *r.URL\n\n\t\tlogger = logger.With(\n\t\t\t\"method\", r.Method,\n\t\t\t\"host\", r.Host,\n\t\t\t\"request\", r.RequestURI,\n\t\t\t\"remote-addr\", r.RemoteAddr,\n\t\t\t\"referer\", r.Referer(),\n\t\t\t\"user-agent\", r.UserAgent(),\n\t\t)\n\n\t\tm := httpsnoop.CaptureMetrics(handler, w, r)\n\n\t\tlogger = logger.With(\n\t\t\t\"code\", m.Code,\n\t\t\t\"duration\", int(m.Duration/time.Millisecond),\n\t\t\t\"duration-fmt\", m.Duration.String(),\n\t\t)\n\n\t\tlogger.Info(\"Completed handling request\")\n\t})\n}", "func NewRequest(method, url string, body io.Reader) (*Request, error) {\n\treq, err := http.NewRequest(method, url, body)\n\n\ttrace := &httptrace.ClientTrace{\n\t\tGetConn: func(hostPort string) {\n\t\t\tfmt.Printf(\"GetConn - hostPort: %s\\n\\tTime: %s\\n\", hostPort, time.Now().String())\n\t\t},\n\t\tGotConn: func(connInfo httptrace.GotConnInfo) {\n\t\t\tfmt.Printf(\"GotCon - connInfo: %v\\n\\tIdletime: %s\\n\\tTime: %s\\n\",\n\t\t\t\tconnInfo, connInfo.IdleTime, time.Now().String())\n\t\t},\n\t\tPutIdleConn: func(err error) {\n\t\t\tfmt.Printf(\"PutIdleConn - err: %v\\n\\tTime: %s\\n\", err, time.Now().String())\n\t\t},\n\t\tGotFirstResponseByte: func() {\n\t\t\tfmt.Printf(\"GotFirstResponseByte - \\n\\tTime: %s\\n\", time.Now().String())\n\t\t},\n\t\tGot100Continue: func() {\n\t\t\tfmt.Printf(\"Got100Continue - \\n\\tTime: %s\\n\", time.Now().String())\n\t\t},\n\t\tGot1xxResponse: func(code int, header textproto.MIMEHeader) error {\n\t\t\tfmt.Printf(\"Got1xxResponse - code: %d\\tMime: %v\\n\\tTime: %s\\n\", code, header, time.Now().String())\n\t\t\treturn nil\n\t\t},\n\t\tDNSStart: func(dsi httptrace.DNSStartInfo) {\n\t\t\tfmt.Printf(\"DNSStart - DNSStartInfo host: %s\\n\\tTime: %s\\n\", dsi.Host, time.Now().String())\n\t\t},\n\t\tDNSDone: func(ddi httptrace.DNSDoneInfo) {\n\t\t\tfmt.Printf(\"DNSDone - DNSDoneInfo: %v\\n\\tTime: %s\\n\", ddi, time.Now().String())\n\t\t},\n\t\tConnectStart: func(network, addr string) {\n\t\t\tfmt.Printf(\"ConnectStart - network: %s\\taddr: %s\\n\\tTime: %s\\n\", network, addr, time.Now().String())\n\t\t},\n\t\tConnectDone: func(network, addr string, err error) {\n\t\t\tfmt.Printf(\"ConnectDone - network: %s\\taddr: %s\\terror: %s\\n\\tTime: %s\\n\", network, addr, err, time.Now().String())\n\t\t},\n\t\tTLSHandshakeStart: func() {\n\t\t\tfmt.Printf(\"TLSHandshakeStart - \\n\\tTime: %s\\n\", time.Now().String())\n\t\t},\n\t\tTLSHandshakeDone: func(cs tls.ConnectionState, err error) {\n\t\t\tfmt.Printf(\"TLSHandshakeDone - ConnectionState completed: %t\\terror: %s\\n\\tTime: %s\\n\", cs.HandshakeComplete, err, time.Now().String())\n\t\t},\n\t\tWroteHeaderField: func(key string, value []string) {\n\t\t\tfmt.Printf(\"WroteHeaderField - key: %s\\tvalue: %v\\n\\tTime: %s\\n\", key, value, time.Now().String())\n\t\t},\n\t\tWroteHeaders: func() {\n\t\t\tfmt.Printf(\"WroteHeaders - \\n\\tTime: %s\\n\", time.Now().String())\n\t\t},\n\t\tWait100Continue: func() {\n\t\t\tfmt.Printf(\"Wait100Continue - \\n\\tTime: %s\\n\", time.Now().String())\n\t\t},\n\t\tWroteRequest: func(wri httptrace.WroteRequestInfo) {\n\t\t\tfmt.Printf(\"WroteRequest - WroteRequestInfo: %v\\n\\tTime: %s\\n\", wri, time.Now().String())\n\t\t},\n\t}\n\n\treq = req.WithContext(httptrace.WithClientTrace(req.Context(), trace))\n\treturn &Request{req}, err\n}", "func Inject(span opentracing.Span, request *http.Request) error {\n\treturn span.Tracer().Inject(\n\t\tspan.Context(),\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(request.Header))\n}", "func TraceMiddleware() Middleware {\n\treturn func(next Service) Service {\n\t\treturn traceMiddleware{\n\t\t\tnext: next,\n\t\t}\n\t}\n}", "func FromHTTPMiddleware(fn func(http.Handler) http.Handler) Handler {\n\treturn HandlerFunc(func(c context.Context) {\n\t\th := fn(mkNextHTTPHandler(c))\n\t\th.ServeHTTP(GetResponseWriter(c), GetRequest(c))\n\t})\n}", "func WithTracingOpName(ctx context.Context, opName string) context.Context {\n\tstrPtr := ctx.Value(tracingOpName{}).(*string)\n\tif strPtr != nil {\n\t\t*strPtr = opName\n\t}\n\treturn ctx\n}", "func JaegerTracer() echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\ttracer := opentracing.GlobalTracer()\n\t\t\t// if tracer not found, skip.\n\t\t\tif tracer == nil {\n\t\t\t\treturn next(c)\n\t\t\t}\n\n\t\t\treq := c.Request()\n\t\t\tctx := req.Context()\n\n\t\t\t// 创建 rootSpan\n\t\t\tvar rootCtx opentracing.SpanContext\n\t\t\tif rootSpan := opentracing.SpanFromContext(ctx); rootSpan != nil {\n\t\t\t\trootCtx = rootSpan.Context()\n\t\t\t}\n\n\t\t\tspan := tracer.StartSpan(\n\t\t\t\treq.URL.Path,\n\t\t\t\topentracing.ChildOf(rootCtx),\n\t\t\t\text.SpanKindRPCClient,\n\t\t\t)\n\t\t\tdefer span.Finish()\n\t\t\text.HTTPMethod.Set(span, req.Method)\n\t\t\text.HTTPUrl.Set(span, req.URL.RequestURI())\n\t\t\t// make the Span current in the context\n\t\t\tctx = opentracing.ContextWithSpan(ctx, span)\n\n\t\t\tc.SetRequest(req.WithContext(ctx))\n\n\t\t\tif err := next(c); err != nil {\n\t\t\t\tlog.Error(err)\n\t\t\t}\n\n\t\t\tres := c.Response()\n\n\t\t\text.HTTPStatusCode.Set(span, uint16(res.Status))\n\n\t\t\treturn nil\n\t\t}\n\t}\n}", "func requestMetrics(l *log.Logger) service {\n\treturn func(h http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tstart := time.Now()\n\t\t\th.ServeHTTP(w, r)\n\t\t\tl.Printf(\"%s request to %s took %vns.\", r.Method, r.URL.Path, time.Since(start).Nanoseconds())\n\t\t})\n\t}\n}", "func (op *Operation) startTrace(ctx context.Context) (*trace.Trace, context.Context) {\n\tif op.context.Tracer == nil {\n\t\treturn nil, ctx\n\t}\n\n\ttr, ctx := op.context.Tracer.New(ctx, op.kebabName, \"\")\n\treturn tr, ctx\n}", "func WrapLog(hfn http.Handler, name string) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\tstart := time.Now()\n\n\t\thfn.ServeHTTP(w, r)\n\n\t\tlog.WithFields(\n\t\t\tlog.Fields{\n\t\t\t\t\"type\": \"request_log\",\n\t\t\t\t\"method\": r.Method,\n\t\t\t\t\"path\": r.RequestURI,\n\t\t\t\t\"action\": name,\n\t\t\t\t\"requester\": gorillaContext.Get(r, \"auth_user_uuid\"),\n\t\t\t\t\"processing_time\": time.Since(start).String(),\n\t\t\t},\n\t\t).Info(\"\")\n\t})\n}", "func Wrap(ctx context.Context, operationName string, opts []tracer.StartSpanOption, f func(ctx context.Context) error) (err error) {\n\tspan, ctx := tracer.StartSpanFromContext(\n\t\tctx,\n\t\toperationName,\n\t\topts...,\n\t)\n\tdefer func() { span.Finish(tracer.WithError(err)) }()\n\n\terr = f(ctx)\n\treturn\n}", "func LogRequest(next http.Handler) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tstart := time.Now()\n\n\t\tnext.ServeHTTP(w, r)\n\n\t\telapsed := time.Since(start)\n\t\tlog.Println(r.Method, r.URL, elapsed.Truncate(time.Millisecond))\n\t})\n}", "func TraceOutbound(r *http.Request, span opentracing.Span) error {\n\treturn opentracing.GlobalTracer().Inject(\n\t\tspan.Context(),\n\t\topentracing.HTTPHeaders,\n\t\topentracing.HTTPHeadersCarrier(r.Header))\n}", "func (req *ServerHTTPRequest) start() {\n\tif req.started {\n\t\t/* coverage ignore next line */\n\t\treq.contextLogger.Error(req.Context(),\n\t\t\t\"Cannot start ServerHTTPRequest twice\",\n\t\t\tzap.String(\"path\", req.URL.Path),\n\t\t)\n\t\t/* coverage ignore next line */\n\t\treturn\n\t}\n\treq.started = true\n\treq.startTime = time.Now()\n\n\t// emit request count\n\treq.scope.Counter(endpointRequest).Inc(1)\n\n\tif req.tracer != nil {\n\t\topName := fmt.Sprintf(\"%s.%s\", req.EndpointName, req.HandlerName)\n\t\turlTag := opentracing.Tag{Key: \"URL\", Value: req.URL}\n\t\tMethodTag := opentracing.Tag{Key: \"Method\", Value: req.Method}\n\t\tcarrier := opentracing.HTTPHeadersCarrier(req.httpRequest.Header)\n\t\tspanContext, err := req.tracer.Extract(opentracing.HTTPHeaders, carrier)\n\t\tvar span opentracing.Span\n\t\tif err != nil {\n\t\t\tif err != opentracing.ErrSpanContextNotFound {\n\t\t\t\t/* coverage ignore next line */\n\t\t\t\treq.contextLogger.WarnZ(req.Context(), \"Error Extracting Trace Headers\", zap.Error(err))\n\t\t\t}\n\t\t\tspan = req.tracer.StartSpan(opName, urlTag, MethodTag)\n\t\t} else {\n\t\t\tspan = req.tracer.StartSpan(opName, urlTag, MethodTag, ext.RPCServerOption(spanContext))\n\t\t}\n\t\treq.span = span\n\t}\n\treq.setupLogFields()\n}", "func StartSpanFromTrustedRequest(\n\tctx context.Context,\n\tname string,\n\ttruster HeaderTrustHandler,\n\tr *http.Request,\n) (context.Context, *tracing.Span) {\n\tvar spanHeaders tracing.Headers\n\tvar sampled bool\n\n\tif truster.TrustSpan(r) {\n\t\tif isHeaderSet(r.Header, TraceIDHeader) {\n\t\t\tspanHeaders.TraceID = r.Header.Get(TraceIDHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanIDHeader) {\n\t\t\tspanHeaders.SpanID = r.Header.Get(SpanIDHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanFlagsHeader) {\n\t\t\tspanHeaders.Flags = r.Header.Get(SpanFlagsHeader)\n\t\t}\n\t\tif isHeaderSet(r.Header, SpanSampledHeader) {\n\t\t\tsampled = r.Header.Get(SpanSampledHeader) == spanSampledTrue\n\t\t\tspanHeaders.Sampled = &sampled\n\t\t}\n\t}\n\n\treturn tracing.StartSpanFromHeaders(ctx, name, spanHeaders)\n}", "func LogRequest(next http.Handler) http.Handler {\n\tfn := func(w http.ResponseWriter, r *http.Request) {\n\t\t// Start timer\n\t\tstart := time.Now()\n\n\t\t// Add a requestID field to logger\n\t\tuid, _ := ulid.NewFromTime(start)\n\t\tl := log.With(zap.String(\"requestID\", uid.String()))\n\t\t// Add logger to context\n\t\tctx := context.WithValue(r.Context(), requestIDKey, l)\n\t\t// Request with this new context.\n\t\tr = r.WithContext(ctx)\n\n\t\t// wrap the ResponseWriter\n\t\tlw := &basicWriter{ResponseWriter: w}\n\n\t\t// Get the real IP even behind a proxy\n\t\trealIP := r.Header.Get(http.CanonicalHeaderKey(\"X-Forwarded-For\"))\n\t\tif realIP == \"\" {\n\t\t\t// if no content in header \"X-Forwarded-For\", get \"X-Real-IP\"\n\t\t\tif xrip := r.Header.Get(http.CanonicalHeaderKey(\"X-Real-IP\")); xrip != \"\" {\n\t\t\t\trealIP = xrip\n\t\t\t} else {\n\t\t\t\trealIP = r.RemoteAddr\n\t\t\t}\n\t\t}\n\n\t\t// Process request\n\t\tnext.ServeHTTP(lw, r)\n\t\tlw.maybeWriteHeader()\n\n\t\t// Stop timer\n\t\tend := time.Now()\n\t\tlatency := end.Sub(start)\n\t\tstatusCode := lw.Status()\n\n\t\tl.Info(\"request\",\n\t\t\tzap.String(\"method\", r.Method),\n\t\t\tzap.String(\"url\", r.RequestURI),\n\t\t\tzap.Int(\"code\", statusCode),\n\t\t\tzap.String(\"clientIP\", realIP),\n\t\t\tzap.Int(\"bytes\", lw.bytes),\n\t\t\tzap.Int64(\"duration\", int64(latency)/int64(time.Microsecond)),\n\t\t)\n\t}\n\n\treturn http.HandlerFunc(fn)\n}", "func (s *Span) ToHTTPReq(req *http.Request) (*http.Request, error) {\n\tif s == nil {\n\t\treturn req, nil\n\t}\n\thc, ok := client.(HTTPCarrier)\n\tif !ok {\n\t\treturn req, errors.New(\"not supported\")\n\t}\n\terr := hc.ToReq(req, s.ID)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn req, nil\n}", "func NewTracer(serviceName, zipkinURL string) (io.Closer, error) {\n\t// Send the tracing in Zipkin format (even if we are using Jaeger as backend).\n\ttransport, err := zipkin.NewHTTPTransport(\"http://\" + zipkinURL + \":9411/api/v1/spans\")\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not init Jaeger Zipkin HTTP transport: %w\", err)\n\t}\n\n\t// Zipkin shares span ID between client and server spans; it must be enabled via the following option.\n\tzipkinPropagator := zk.NewZipkinB3HTTPHeaderPropagator()\n\n\ttracer, closer := jaeger.NewTracer(\n\t\tserviceName,\n\t\tjaeger.NewConstSampler(true), // Trace everything for now.\n\t\tjaeger.NewRemoteReporter(transport),\n\t\tjaeger.TracerOptions.Injector(opentracing.HTTPHeaders, zipkinPropagator),\n\t\tjaeger.TracerOptions.Extractor(opentracing.HTTPHeaders, zipkinPropagator),\n\t\tjaeger.TracerOptions.ZipkinSharedRPCSpan(true),\n\t\tjaeger.TracerOptions.Gen128Bit(true),\n\t)\n\topentracing.SetGlobalTracer(tracer)\n\n\treturn closer, nil\n}", "func TrackRequest(method string, uri string) *DurationTrace {\n\ttraces := make([]*DurationTrace, 0)\n\n\tif traceListeners != nil {\n\t\tfor _, tl := range traceListeners {\n\t\t\ttraces = append(traces, (*tl).TrackRequest(method, uri))\n\t\t}\n\t}\n\n\tdt := newAggregateDurationTrace(traces)\n\treturn &dt\n}", "func InstrumentingMiddleware(label string) mux.MiddlewareFunc {\n\n\thttpTotal := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.total\", label))\n\thttp2xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.2xx\", label))\n\thttp3xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.3xx\", label))\n\thttp4xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.4xx\", label))\n\thttp5xx := kitexpvar.NewCounter(fmt.Sprintf(\"%s.http.count.5xx\", label))\n\thttpLatency := kitexpvar.NewHistogram(fmt.Sprintf(\"%s.http.latency\", label), 50)\n\n\treturn mux.MiddlewareFunc(func(next http.Handler) http.Handler {\n\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\n\t\t\thttpTotal.Add(1)\n\t\t\tiw := &interceptingHttpWriter{delegate: w}\n\t\t\tdefer func(begin time.Time) {\n\t\t\t\tswitch sc := iw.statusCode; {\n\t\t\t\tcase sc >= 200 && sc < 300:\n\t\t\t\t\thttp2xx.Add(1)\n\t\t\t\tcase sc >= 300 && sc < 400:\n\t\t\t\t\thttp3xx.Add(1)\n\t\t\t\tcase sc >= 400 && sc < 500:\n\t\t\t\t\thttp4xx.Add(1)\n\t\t\t\tcase sc >= 500 && sc < 600:\n\t\t\t\t\thttp5xx.Add(1)\n\t\t\t\t}\n\t\t\t\thttpLatency.Observe(time.Since(begin).Seconds() * 1000)\n\n\t\t\t}(time.Now())\n\n\t\t\tnext.ServeHTTP(iw, r)\n\t\t})\n\t})\n}", "func DoRequestWithTrace(client *http.Client, req *http.Request) (*Trace, *http.Response, error) {\n\tclientTrace, ctx := NewTrace(req.URL.String())\n\treq = req.WithContext(ctx)\n\n\tresp, err := client.Do(req)\n\tif resp != nil {\n\t\tresp.Body = spyBodyReader{\n\t\t\tReadCloser: resp.Body,\n\t\t\tbodyReadTime: &clientTrace.BodyReadTime,\n\t\t}\n\t}\n\n\treturn clientTrace, resp, err\n}", "func newHTTPTracePolicy(allowedQueryParams []string) exported.Policy {\n\treturn &httpTracePolicy{allowedQP: getAllowedQueryParams(allowedQueryParams)}\n}", "func NewHTTPHandler(endpoints endpoints.Endpoints, otTracer stdopentracing.Tracer, zipkinTracer *stdzipkin.Tracer, logger log.Logger) http.Handler { // Zipkin HTTP Server Trace can either be instantiated per endpoint with a\n\t// provided operation name or a global tracing service can be instantiated\n\t// without an operation name and fed to each Go kit endpoint as ServerOption.\n\t// In the latter case, the operation name will be the endpoint's http method.\n\t// We demonstrate a global tracing service here.\n\tzipkinServer := zipkin.HTTPServerTrace(zipkinTracer)\n\n\toptions := []httptransport.ServerOption{\n\t\thttptransport.ServerErrorEncoder(httpEncodeError),\n\t\thttptransport.ServerErrorLogger(logger),\n\t\tzipkinServer,\n\t}\n\n\tm := http.NewServeMux()\n\tm.Handle(\"/sum\", httptransport.NewServer(\n\t\tendpoints.SumEndpoint,\n\t\tdecodeHTTPSumRequest,\n\t\thttptransport.EncodeJSONResponse,\n\t\tappend(options, httptransport.ServerBefore(opentracing.HTTPToContext(otTracer, \"Sum\", logger)))...,\n\t))\n\tm.Handle(\"/concat\", httptransport.NewServer(\n\t\tendpoints.ConcatEndpoint,\n\t\tdecodeHTTPConcatRequest,\n\t\thttptransport.EncodeJSONResponse,\n\t\tappend(options, httptransport.ServerBefore(opentracing.HTTPToContext(otTracer, \"Concat\", logger)))...,\n\t))\n\tm.Handle(\"/metrics\", promhttp.Handler())\n\treturn m\n}", "func (c *Executor) newHTTPRequest(request *Request) (*http.Request, error) {\n\tif request.context == nil {\n\t\treturn nil, errNilContext\n\t}\n\tif !isSupportedHTTPMethod(request.method) {\n\t\treturn nil, fmt.Errorf(\"error executing request, found unsupport HTTP method %s\", request.method)\n\t}\n\n\t// JSON encode the object and use that as the body if specified, otherwise use the body as-is\n\treqBody := request.body\n\tif request.object != nil {\n\t\tb, err := encodeBody(request.object)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error executing request, failed to encode the request object to JSON: %w\", err)\n\t\t}\n\t\treqBody = b\n\t}\n\tu := path.Join(c.apiAddress, request.pathAndQuery)\n\n\tr, err := http.NewRequestWithContext(request.context, request.method, u, reqBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error executing request, failed to create a new underlying HTTP request: %w\", err)\n\t}\n\tr.Header.Set(\"User-Agent\", c.userAgent)\n\tif request.contentType != \"\" {\n\t\tr.Header.Set(\"Content-type\", request.contentType)\n\t}\n\tif request.contentLength != nil {\n\t\tr.ContentLength = *request.contentLength\n\t}\n\tfor k, v := range request.headers {\n\t\tr.Header.Set(k, v)\n\t}\n\n\treturn r, nil\n}", "func (ot *openTelemetryWrapper) serveHTTP(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tot.propagators.Inject(ctx, propagation.HeaderCarrier(r.Header))\n\tspanCtx := trace.SpanContextFromContext(ctx)\n\tif spanCtx.IsValid() {\n\t\tif extra, ok := ctx.Value(caddyhttp.ExtraLogFieldsCtxKey).(*caddyhttp.ExtraLogFields); ok {\n\t\t\textra.Add(zap.String(\"traceID\", spanCtx.TraceID().String()))\n\t\t}\n\t}\n\tnext := ctx.Value(nextCallCtxKey).(*nextCall)\n\tnext.err = next.next.ServeHTTP(w, r)\n}", "func (b *Builder) BuildHTTPRequest(o *data.Operation, i *reflect.Value) (*http.Request, error) {\n\tb.operation = o\n\tb.input = i\n\n\terr := b.parse()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn b.build()\n}", "func Trace(w http.ResponseWriter, r *http.Request)", "func RequestLifetimeLogger() Middleware {\n\treturn func(h http.HandlerFunc) http.HandlerFunc {\n\t\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\t\tlogger := log.FromContextWithPackageName(r.Context(), \"go-common/middleware/request\").\n\t\t\t\tWith(log.String(LogKeyRemoteIP, request.IPFromAddr(r.RemoteAddr))).\n\t\t\t\tWith(log.String(LogKeyRequestURL, r.RequestURI))\n\t\t\tlogger.Info(LogMsgStartRequest)\n\t\t\th(w, r)\n\t\t\tlogger.Info(LogMsgFinishRequest)\n\t\t}\n\t}\n}", "func SpanTransferFromContextToHeader(ctx context.Context) context.Context {\n\tvar parentCtx opentracing.SpanContext\n\tif parent := opentracing.SpanFromContext(ctx); parent != nil {\n\t\tparentCtx = parent.Context()\n\t}\n\tsp := opentracing.StartSpan(\n\t\t\"GRPCToHTTP\",\n\t\topentracing.FollowsFrom(parentCtx),\n\t\text.SpanKindRPCClient,\n\t)\n\tdefer sp.Finish()\n\treturn opentracing.ContextWithSpan(context.Background(), sp)\n}", "func logStartOfRequest(\n\tr *stdhttp.Request,\n\textraHeaders []string,\n) {\n\tfields := log.F{}\n\tfor _, header := range extraHeaders {\n\t\t// Strips \"-\" characters and lowercases new logrus.Fields keys to be uniform with the other keys in the logger.\n\t\t// Simplifies querying extended fields.\n\t\tvar headerkey = strings.ToLower(strings.ReplaceAll(header, \"-\", \"\"))\n\t\tfields[headerkey] = r.Header.Get(header)\n\t}\n\tfields[\"subsys\"] = \"http\"\n\tfields[\"path\"] = r.URL.String()\n\tfields[\"method\"] = r.Method\n\tfields[\"ip\"] = r.RemoteAddr\n\tfields[\"host\"] = r.Host\n\tfields[\"useragent\"] = r.Header.Get(\"User-Agent\")\n\tl := log.Ctx(r.Context()).WithFields(fields)\n\n\tl.Info(\"starting request\")\n}", "func TracingHandlerFunc(h http.HandlerFunc) http.HandlerFunc {\n\treturn TracingMiddleware(LoggingMiddleWare(h))\n}", "func DataDogTrace(service string) echo.MiddlewareFunc {\n\treturn func(next echo.HandlerFunc) echo.HandlerFunc {\n\t\treturn func(c echo.Context) error {\n\t\t\trequest := c.Request()\n\t\t\tresource := c.Path()\n\n\t\t\topts := []ddtrace.StartSpanOption{\n\t\t\t\ttracer.ServiceName(service),\n\t\t\t\ttracer.ResourceName(resource),\n\t\t\t\ttracer.SpanType(ext.SpanTypeWeb),\n\t\t\t\ttracer.Tag(ext.HTTPMethod, request.Method),\n\t\t\t\ttracer.Tag(ext.HTTPURL, request.URL.Path),\n\t\t\t\ttracer.Tag(ext.Environment, os.Getenv(\"STAGE\")),\n\t\t\t}\n\n\t\t\tif spanctx, err := tracer.Extract(tracer.HTTPHeadersCarrier(request.Header)); err == nil {\n\t\t\t\topts = append(opts, tracer.ChildOf(spanctx))\n\t\t\t}\n\n\t\t\tspan, ctx := tracer.StartSpanFromContext(request.Context(), \"http.request\", opts...)\n\n\t\t\tdefer span.Finish()\n\n\t\t\t// pass the span through the request context\n\t\t\tc.SetRequest(request.WithContext(ctx))\n\t\t\tc.Set(DataDogTraceID, span.Context().TraceID())\n\t\t\tc.Set(DataDogSpanID, span.Context().SpanID())\n\n\t\t\t// serve the request to the next middleware\n\t\t\tspan.SetTag(ext.HTTPCode, strconv.Itoa(c.Response().Status))\n\n\t\t\terr := next(c)\n\t\t\tif err != nil {\n\t\t\t\tspan.SetTag(ext.Error, err)\n\t\t\t} else if c.Response().Status >= 400 {\n\t\t\t\tspan.SetTag(ext.Error, http.StatusText(c.Response().Status))\n\t\t\t}\n\n\t\t\treturn err\n\t\t}\n\t}\n}", "func (c *Prometheus) TrackRequest(r *http.Request, t timer.Timer, success bool) Client {\n\tb := bucket.NewHTTPRequest(c.httpRequestSection, r, success, c.httpMetricCallback, c.unicode)\n\tmetric := b.Metric()\n\tmetricTotal := b.MetricTotal()\n\n\tmetric = strings.Replace(metric, \"-.\", \"\", -1)\n\tmetric = strings.Replace(metric, \".-\", \"\", -1)\n\tmetric = strings.Replace(metric, \"-\", \"\", -1)\n\tmetric = strings.Replace(metric, \".\", \"_\", -1)\n\n\tmetricTotal = strings.Replace(metricTotal, \"-.\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \"-\", \"\", -1)\n\tmetricTotal = strings.Replace(metricTotal, \".\", \"_\", -1)\n\n\tmetricInc := c.getIncrementer(metric)\n\tmetricTotalInc := c.getIncrementer(metricTotal)\n\n\tlabels := map[string]string{\"success\": strconv.FormatBool(success), \"action\": r.Method}\n\n\tmetric = c.prepareMetric(metric)\n\tmetricTotal = c.prepareMetric(metricTotal)\n\tmetricInc.Increment(metric, labels)\n\tmetricTotalInc.Increment(metricTotal, labels)\n\n\treturn c\n}" ]
[ "0.6402", "0.6174457", "0.6166543", "0.61533904", "0.6144773", "0.6028495", "0.59455067", "0.57898575", "0.5776707", "0.5765095", "0.57545215", "0.57532007", "0.5747777", "0.57324475", "0.56458485", "0.55817235", "0.5564534", "0.5488712", "0.5475404", "0.5467958", "0.53721666", "0.5331407", "0.52859396", "0.520763", "0.51983243", "0.5183033", "0.5172974", "0.51684856", "0.51684856", "0.5159802", "0.51164895", "0.5089252", "0.50862753", "0.50758547", "0.5062227", "0.5051228", "0.50054497", "0.5001484", "0.50002325", "0.49956283", "0.497996", "0.49717742", "0.49650407", "0.4951939", "0.4943935", "0.49341446", "0.4932106", "0.49012768", "0.48989218", "0.48763952", "0.48758638", "0.48709884", "0.4858249", "0.4854874", "0.4851614", "0.48371065", "0.48310962", "0.48117578", "0.48111394", "0.47697747", "0.47596657", "0.47469673", "0.4726905", "0.4722386", "0.47108904", "0.4706084", "0.4691372", "0.46911085", "0.46869642", "0.46842325", "0.46765947", "0.46719623", "0.46702752", "0.46666664", "0.4659428", "0.46517202", "0.46432558", "0.46369952", "0.4633573", "0.46326494", "0.46297064", "0.46245676", "0.46221617", "0.46201804", "0.4615896", "0.46141422", "0.46117258", "0.4599638", "0.45912835", "0.45841786", "0.45835868", "0.45800218", "0.45776677", "0.45725268", "0.45721957", "0.45681694", "0.45655367", "0.45635277", "0.45614037", "0.45549664" ]
0.79822314
0
AddWebhook is used to append a webhook to a slice of webhooks
func (webhooks *Webhooks) AddWebhook(item Webhook) []Webhook { webhooks.Items = append(webhooks.Items, item) return webhooks.Items }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func AddWebhook(ctx context.Context, w *Webhook) error {\n\treturn db.Bun().RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {\n\t\t_, err := tx.NewInsert().Model(w).Exec(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, t := range w.Triggers {\n\t\t\tt.WebhookID = w.ID\n\t\t}\n\n\t\tif len(w.Triggers) != 0 {\n\t\t\t_, err = tx.NewInsert().Model(&w.Triggers).Exec(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (c *Client) AddWebhook(w *Webhook) error {\n\treturn c.AddWebHookContext(context.TODO(), w)\n}", "func (w *Webhook) Add() error {\n\treturn w.AddContext(context.TODO())\n}", "func AddWebhook() (bool, error) {\n\tfmt.Println()\n\tlog.Infof(\"WEBHOOK SETUP\")\n\tlog.Printf(\"For automatic webhook setup for push and PR git events you need administrator rights for your repository\")\n\n\tconst (\n\t\toptionYes = \"Yes\"\n\t\toptionNo = \"No\"\n\t)\n\n\tprompt := promptui.Select{\n\t\tLabel: \"Would you like us to register a webhook for you?\",\n\t\tItems: []string{optionYes, optionNo},\n\t\tTemplates: &promptui.SelectTemplates{\n\t\t\tLabel: fmt.Sprintf(\"%s {{.}} \", promptui.IconInitial),\n\t\t\tSelected: \"Auto register webhook: {{ . | green }}\",\n\t\t},\n\t}\n\n\t_, answer, err := prompt.Run()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"scan user input: %s\", err)\n\t}\n\n\tvar registerWebhook bool\n\tif answer == optionYes {\n\t\tregisterWebhook = true\n\t}\n\n\treturn registerWebhook, nil\n}", "func InsertWebhook(url string, events []models.EventType) (int, error) {\n\tlog.Traceln(\"Adding new webhook\")\n\n\teventsString := strings.Join(events, \",\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstmt, err := tx.Prepare(\"INSERT INTO webhooks(url, events) values(?, ?)\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer stmt.Close()\n\n\tinsertResult, err := stmt.Exec(url, eventsString)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn 0, err\n\t}\n\n\tnewID, err := insertResult.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(newID), err\n}", "func (agent *MonitorAgent) addValidatingWebhooks(foundWebhooks map[string]admissions.ValidatingWebhookConfiguration, webhooks map[string]*pb.WebhookHealthReport) {\n\tfor _, webhookName := range agent.getOctarineValidatingWebhooks() {\n\t\tif webhook, ok := foundWebhooks[webhookName]; ok {\n\t\t\twebhookMsg := agent.buildValidatingWebhookMessage(webhook)\n\t\t\tif _, ok := webhooks[webhookName]; ok {\n\t\t\t\tlogger.Info(\"duplicate webhook name\", \"webhook\", webhookName)\n\t\t\t}\n\t\t\twebhooks[webhookName] = webhookMsg\n\t\t} else {\n\t\t\tlogger.Info(\"octarine validating webhook not found.\", \"webhook\", webhookName)\n\t\t}\n\t}\n}", "func (d *Dispatcher) Add(name string, hook string) {\n\td.Mutex.Lock()\n\tlog.Println(\"Adding:\", name, \"Webhook:\", hook)\n\td.Hooks[name] = hook\n\td.Mutex.Unlock()\n}", "func (t *TauAPI) CreateWebhook(webhook Webhook) (ID int64, error error) {\n\tjsonPostMsg, _ := json.Marshal(webhook)\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"POST\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t\tPostMsg: jsonPostMsg,\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tif string(jsonData) == \"[\\\"Limit reached\\\"]\" {\n\t\treturn 0, fmt.Errorf(\"Limit of webhooks reached (5)\")\n\t}\n\tvar d struct {\n\t\tID int64 `json:\"id\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn 0, fmt.Errorf(\"CreateWebhook -> unmarshal jsonData %v\", err)\n\t}\n\treturn d.ID, nil\n}", "func Add(mgr manager.Manager, hubconfig *rest.Config, tlsKeyFile, tlsCrtFile string, disableTLS bool, createService bool) error {\n\tklog.V(2).Info(\"Setting up webhook listener ...\")\n\n\tif !disableTLS {\n\t\tdir := \"/root/certs\"\n\n\t\tif strings.EqualFold(tlsKeyFile, \"\") || strings.EqualFold(tlsCrtFile, \"\") {\n\t\t\terr := utils.GenerateServerCerts(dir)\n\n\t\t\tif err != nil {\n\t\t\t\tklog.Error(\"Failed to generate a self signed certificate. error: \", err)\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\ttlsKeyFile = filepath.Join(dir, \"tls.key\")\n\t\t\ttlsCrtFile = filepath.Join(dir, \"tls.crt\")\n\t\t}\n\t}\n\n\tvar err error\n\n\twebhookListener, err = CreateWebhookListener(mgr.GetConfig(), hubconfig, mgr.GetScheme(), tlsKeyFile, tlsCrtFile, createService)\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to create synchronizer. error: \", err)\n\t\treturn err\n\t}\n\n\treturn mgr.Add(webhookListener)\n}", "func (s *WebhooksServiceOp) Create(webhook Webhook, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tjsonBody, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn webhookResponse.Data, err\n\t}\n\treqBody := bytes.NewReader(jsonBody)\n\tbody, reqErr := s.client.DoRequest(http.MethodPost, \"/v3/hooks\", reqBody)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\n\treturn webhookResponse.Data, nil\n}", "func SetupWebhooks(mgr ctrl.Manager) error {\n\t/*\n\t\tTotally undocumented and hard-to-find feature is that the builder automatically registers the URL path for the webhook.\n\t\tWhat's more, not even the tests in upstream controller-runtime reveal what this path is _actually_ going to look like.\n\t\tSo here's how the path is built (dots replaced with dash, lower-cased, single-form):\n\t\t /validate-<group>-<version>-<kind>\n\t\t /mutate-<group>-<version>-<kind>\n\t\tExample:\n\t\t /validate-clustercode-github-io-v1alpha1-blueprint\n\t\tThis path has to be given in the `//+kubebuilder:webhook:...` magic comment, see example:\n\t\t +kubebuilder:webhook:verbs=create;update;delete,path=/validate-clustercode-github-io-v1alpha1-blueprint,mutating=false,failurePolicy=fail,groups=clustercode.github.io,resources=blueprints,versions=v1alpha1,name=blueprints.clustercode.github.io,sideEffects=None,admissionReviewVersions=v1\n\t\tPay special attention to the plural forms and correct versions!\n\t*/\n\tfor _, setup := range []func(ctrl.Manager) error{\n\t\tblueprintwebhook.SetupWebhook,\n\t} {\n\t\tif err := setup(mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func CreateWebhook(user string, repo string, accesstoken string, webhookUrl string, secret string) (int, error) {\n\tdata := user + \":\" + accesstoken\n\tsEnc := base64.StdEncoding.EncodeToString([]byte(data))\n\tname := \"web\"\n\tactive := true\n\thook := github.Hook{\n\t\tName: &name,\n\t\tActive: &active,\n\t\tConfig: make(map[string]interface{}),\n\t\tEvents: []string{\"push\"},\n\t}\n\n\thook.Config[\"url\"] = webhookUrl\n\thook.Config[\"content_type\"] = \"json\"\n\thook.Config[\"secret\"] = secret\n\thook.Config[\"insecure_ssl\"] = \"1\"\n\n\tlogrus.Infof(\"hook to create:%v\", hook)\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(hook)\n\thc := http.Client{}\n\tAPIURL := fmt.Sprintf(\"https://api.github.com/repos/%v/%v/hooks\", user, repo)\n\treq, err := http.NewRequest(\"POST\", APIURL, b)\n\n\treq.Header.Add(\"Authorization\", \"Basic \"+sEnc)\n\n\tresp, err := hc.Do(req)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\trespData, err := ioutil.ReadAll(resp.Body)\n\tlogrus.Infof(\"respData:%v\", string(respData))\n\tif resp.StatusCode > 399 {\n\t\treturn -1, errors.New(string(respData))\n\t}\n\terr = json.Unmarshal(respData, &hook)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn hook.GetID(), err\n}", "func registerWebhookAPIs(ws *restful.WebService) {\n\tws.Route(ws.POST(\"/{service_id}/webhook_github\").\n\t\tTo(webhookGithub).\n\t\tDoc(\"webhook from github\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookGithub{}).\n\t\tWrites(api.WebhookResponse{}))\n\n\tws.Route(ws.POST(\"/{service_id}/webhook_gitlab\").\n\t\tTo(webhookGitLab).\n\t\tDoc(\"webhook from gitlab\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookGitlab{}).\n\t\tWrites(api.WebhookResponse{}))\n\n\tws.Route(ws.POST(\"/{service_id}/webhook_svn\").\n\t\tTo(webhookSVN).\n\t\tDoc(\"webhook from svn\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookSVN{}).\n\t\tWrites(api.WebhookResponse{}))\n}", "func TestCreateAndUpdateWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tcreationPayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(creationPayload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\tupdatePayload := []WebhookField{\n\t\tWebhookField{\n\t\t\tOperation: \"replace\",\n\t\t\tPath: \"/event_types\",\n\t\t\tValue: []interface{}{\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"name\": \"PAYMENT.SALE.REFUNDED\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = c.UpdateWebhook(createdWebhook.ID, updatePayload)\n\tif err != nil {\n\t\tt.Errorf(\"Couldn't update webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func (c *Client) AddWebHookContext(ctx context.Context, w *Webhook) error {\n\treq := &api.WebhooksAddRequest{\n\t\tURL: w.URL,\n\t\tDescription: w.Description,\n\t\tEvents: w.Events,\n\t}\n\tresp := &api.WebhooksAddResponse{}\n\terr := c.postContext(ctx, \"webhooks/add\", req, resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\tnewhook, err := c.WebhookInfoContext(ctx, resp.ID)\n\tif err != nil {\n\t\treturn err\n\t}\n\t*w = *newhook\n\treturn nil\n}", "func NewWebhook(db *sqlx.DB) *Webhook {\n\treturn &Webhook{db: db}\n}", "func (z *Client) CreateWebhook(ctx context.Context, hook *Webhook) (*Webhook, error) {\n\tvar data, result struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\tdata.Webhook = hook\n\n\tbody, err := z.post(ctx, \"/webhooks\", data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Webhook, nil\n}", "func (g *V3) CreateWebhook(repo string, webhook *scm.Webhook) error {\n\tif webhook == nil || len(webhook.URL) == 0 || len(webhook.Events) == 0 {\n\t\treturn fmt.Errorf(\"The webhook %v is not correct\", webhook)\n\t}\n\n\t_, err := g.GetWebhook(repo, webhook.URL)\n\tif err != nil {\n\t\tif !cerr.ErrorContentNotFound.Derived(err) {\n\t\t\treturn err\n\t\t}\n\n\t\thook := generateV3ProjectHook(webhook)\n\t\t_, resp, err := g.client.Projects.AddProjectHook(repo, hook)\n\t\tif err != nil {\n\t\t\treturn convertGitlabError(err, resp)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Warningf(\"Webhook already existed: %+v\", webhook)\n\treturn err\n}", "func RegisterWebhook(w *Webhook) error {\n\tif webhooksRegistry == nil {\n\t\twebhooksRegistry = make(map[string]*Webhook)\n\t}\n\n\t_, ok := webhooksRegistry[w.UID()]\n\tif ok {\n\t\treturn fmt.Errorf(\"webhook %s already registred\", w.UID())\n\t}\n\twebhooksRegistry[w.UID()] = w\n\treturn nil\n}", "func (c *Client) CreateWebhook(ctx context.Context, repo bitbucket.Repo, hook bitbucket.Webhook) (bitbucket.Webhook, error) {\n\tmarshalledPayload, err := json.Marshal(hook)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo))\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(marshalledPayload))\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\tvar response bitbucket.Webhook\n\tif err := c.sendRequest(req, &response); err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\treturn response, nil\n}", "func appendWebhookConfiguration(mutatingWebhooks []*admissionv1.MutatingWebhookConfiguration, validatingWebhooks []*admissionv1.ValidatingWebhookConfiguration, configyamlFile []byte, tag string) ([]*admissionv1.MutatingWebhookConfiguration, []*admissionv1.ValidatingWebhookConfiguration, error) {\n\tobjs, err := utilyaml.ToUnstructured(configyamlFile)\n\tif err != nil {\n\t\tklog.Fatalf(\"failed to parse yaml\")\n\t}\n\t// look for resources of kind MutatingWebhookConfiguration\n\tfor i := range objs {\n\t\to := objs[i]\n\t\tif o.GetKind() == mutatingWebhookKind {\n\t\t\t// update the name in metadata\n\t\t\tif o.GetName() == mutatingwebhook {\n\t\t\t\to.SetName(fmt.Sprintf(\"%s-%s\", mutatingwebhook, tag))\n\n\t\t\t\twebhook := &admissionv1.MutatingWebhookConfiguration{}\n\t\t\t\tif err := scheme.Scheme.Convert(&o, webhook, nil); err != nil {\n\t\t\t\t\tklog.Fatalf(\"failed to convert MutatingWebhookConfiguration %s\", o.GetName())\n\t\t\t\t}\n\n\t\t\t\tmutatingWebhooks = append(mutatingWebhooks, webhook)\n\t\t\t}\n\t\t}\n\t\tif o.GetKind() == validatingWebhookKind {\n\t\t\t// update the name in metadata\n\t\t\tif o.GetName() == validatingwebhook {\n\t\t\t\to.SetName(fmt.Sprintf(\"%s-%s\", validatingwebhook, tag))\n\n\t\t\t\twebhook := &admissionv1.ValidatingWebhookConfiguration{}\n\t\t\t\tif err := scheme.Scheme.Convert(&o, webhook, nil); err != nil {\n\t\t\t\t\tklog.Fatalf(\"failed to convert ValidatingWebhookConfiguration %s\", o.GetName())\n\t\t\t\t}\n\n\t\t\t\tvalidatingWebhooks = append(validatingWebhooks, webhook)\n\t\t\t}\n\t\t}\n\t}\n\treturn mutatingWebhooks, validatingWebhooks, err\n}", "func (o *ItemImportRequestOptions) SetWebhook(v string) {\n\to.Webhook = &v\n}", "func (wh *Webhook) Create(accountId string, data map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\tif accountId != \"\" {\n\t\turl := fmt.Sprintf(\"/%s%s/%s%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK)\n\t\treturn wh.Request.Post(url, data, extraHeaders)\n\t}\n\turl := fmt.Sprintf(\"/%s%s\", constants.VERSION_V1, constants.WEBHOOK)\n\treturn wh.Request.Post(url, data, extraHeaders)\n}", "func (c *Client) CreateWebhook(req CreateWebhookReq) (Webhook, error) {\n\tvar res Webhook\n\terr := c.post(c.baseURL+\"/webhooks\", webhookReq{Webhook: req}, &res)\n\n\treturn res, err\n}", "func SendWebhook(wh data.WebhookServices, event string, data interface{}) {\n\theaders := make(map[string]string)\n\theaders[\"X-Webhook-Event\"] = event\n\n\tsubscribers, err := wh.AllSubscriptions(event)\n\tif err != nil {\n\t\tlog.Println(\"unable to get webhook subscribers for \", event)\n\t\treturn\n\t}\n\n\tfor _, sub := range subscribers {\n\t\tgo func(sub model.Webhook, headers map[string]string) {\n\t\t\tif err := post(sub.TargetURL, data, nil, headers); err != nil {\n\t\t\t\tlog.Println(\"error calling URL\", sub.TargetURL, err)\n\t\t\t}\n\t\t}(sub, headers)\n\t}\n}", "func NewWebhook(ctx *pulumi.Context,\n\tname string, args *WebhookArgs, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Name == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Name'\")\n\t}\n\tif args.Url == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Url'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Webhook\n\terr := ctx.RegisterResource(\"datadog:index/webhook:Webhook\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (w *WebhookServiceOp) Create(webhook Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s\", webhooksBasePath)\n\tresource := new(Webhook)\n\terr := w.client.Post(path, webhook, &resource)\n\treturn resource, err\n}", "func SetWebhook(token string, url string, port int) error {\n\tdata, _ := json.Marshal(webhook{WebHookURL: url})\n\tr, _ := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/personal/webhook\", monobankAPIURL), bytes.NewReader(data))\n\tr.Header.Set(\"X-Token\", token)\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := http.Client{}\n\tresp, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn fmt.Errorf(\"Status code: %d, Resp: %s\", resp.StatusCode, string(body))\n\t}\n\treturn nil\n}", "func hookPerformWebPOST(url string, data interface{}) error {\n\t// Generate a buffer for us to store some JSON\n\tb := new(bytes.Buffer)\n\n\t// Take the data we have received and encode it in JSON to POST\n\tjson.NewEncoder(b).Encode(data)\n\n\t// It's always important to log.\n\tlog.WithFields(log.Fields{\n\t\t\"url\": url,\n\t\t\"data\": b,\n\t}).Debug(\"POSTing to webhook\")\n\n\t// POST up our data and then return if we got an error or not.\n\tres, err := http.Post(url, \"application/json; charset=utf-8\", b)\n\n\tlog.WithFields(log.Fields{\n\t\t\"url\": url,\n\t\t\"code\": res.StatusCode,\n\t\t\"status\": res.Status,\n\t}).Debug(\"Response received from webhook\")\n\n\treturn err\n}", "func (app *BandApp) AddHook(hook Hook) {\n\tapp.hooks = append(app.hooks, hook)\n}", "func (a *AppBuilder) Webhooks(objs ...runtime.Object) *AppBuilder {\n\ta.init()\n\tfor _, obj := range objs {\n\t\tif obj == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar err error\n\t\tif setup, ok := obj.(WebhookSetup); ok {\n\t\t\terr = setup.SetupWebhookWithManager(a.Manager)\n\t\t} else {\n\t\t\terr = ctrl.NewWebhookManagedBy(a.Manager).\n\t\t\t\tFor(obj).\n\t\t\t\tComplete()\n\t\t}\n\t\tif err != nil {\n\t\t\ta.Logger.Fatalw(\"webhook setup error for obj\", \"obj\", obj.GetObjectKind(), \"err\", err)\n\t\t}\n\t}\n\treturn a\n}", "func ListenWebhook(a Application) {\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(200)\n\n\t\tif req.Method == http.MethodGet {\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\n\t\tlogrus.Infof(\"webhook data: %s\", string(body))\n\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\tevent := webhookEvent{}\n\n\t\terr = json.Unmarshal(body, &event)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\tif event.Data.StatementItem.Amount > 0 {\n\t\t\treturn\n\t\t}\n\n\t\titem := Item{\n\t\t\tName: event.Data.StatementItem.Description,\n\t\t\tAmount: event.Data.StatementItem.getNormalizedAmount(),\n\t\t\tCategory: event.Data.StatementItem.getCategory(),\n\t\t}\n\n\t\tif item.Name == \"\" {\n\t\t\tif item.Category != \"\" {\n\t\t\t\titem.Name = item.Category\n\t\t\t} else {\n\t\t\t\titem.Name = \"transaction\"\n\t\t\t}\n\t\t}\n\t\tvar account User\n\n\t\tif event.Data.Account == a.Config.MonobankAccount1 {\n\t\t\taccount = User{\n\t\t\t\tID: a.Config.SenderID1,\n\t\t\t\tUsername: a.Config.UserName1,\n\t\t\t}\n\t\t} else if event.Data.Account == a.Config.MonobankAccount2 {\n\t\t\taccount = User{\n\t\t\t\tID: a.Config.SenderID2,\n\t\t\t\tUsername: a.Config.UserName2,\n\t\t\t}\n\t\t} else {\n\t\t\treturn\n\t\t}\n\n\t\ta.IntegrationEvents <- BankData{Item: item, Account: account}\n\t})\n\n\tlogrus.Info(fmt.Sprintf(\"listen webhook on: %d\", a.Config.MonobankPort))\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", a.Config.MonobankPort), nil)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n}", "func (as *AdminServer) Webhooks(w http.ResponseWriter, r *http.Request) {\n\tparams := newTemplateParams(r)\n\tparams.Title = \"Webhooks\"\n\tgetTemplate(w, \"webhooks\").ExecuteTemplate(w, \"base\", params)\n}", "func (c *ApiService) CreateWebhook(ServiceSid string, params *CreateWebhookParams) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.FriendlyName != nil {\n\t\tdata.Set(\"FriendlyName\", *params.FriendlyName)\n\t}\n\tif params != nil && params.EventTypes != nil {\n\t\tfor _, item := range *params.EventTypes {\n\t\t\tdata.Add(\"EventTypes\", item)\n\t\t}\n\t}\n\tif params != nil && params.WebhookUrl != nil {\n\t\tdata.Set(\"WebhookUrl\", *params.WebhookUrl)\n\t}\n\tif params != nil && params.Status != nil {\n\t\tdata.Set(\"Status\", *params.Status)\n\t}\n\tif params != nil && params.Version != nil {\n\t\tdata.Set(\"Version\", *params.Version)\n\t}\n\n\tresp, err := c.requestHandler.Post(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func WebhookHandler(w http.ResponseWriter, r *http.Request, reconciler gitopsconfig.Reconciler) {\n\tlog.Info(\"received webhook call\")\n\tif r.Method != \"POST\" {\n\t\tlog.Info(\"webhook handler only accepts the POST method\", \"sent_method\", r.Method)\n\t\tw.WriteHeader(405)\n\t\treturn\n\t}\n\n\tpayload, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err, \"error reading webhook request body\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\twebHookEvent, err := github.ParseWebHook(github.WebHookType(r), payload)\n\tif err != nil {\n\t\tlog.Error(err, \"error parsing webhook event payload\")\n\t\treturn\n\t}\n\n\tswitch e := webHookEvent.(type) {\n\tcase *github.PushEvent:\n\t\t// A commit push was received, determine if there is are GitOpsConfigs that match the event\n\t\t// The repository url and Git ref must match for the templateSource or parameterSource\n\t\t{\n\t\t\tlist, err := reconciler.GetAll()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err, \"error getting the list of GitOpsConfigs\")\n\t\t\t\tw.WriteHeader(500)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttargetList := gitopsv1alpha1.GitOpsConfigList{\n\t\t\t\tTypeMeta: list.TypeMeta,\n\t\t\t\tListMeta: list.ListMeta,\n\t\t\t\tItems: make([]gitopsv1alpha1.GitOpsConfig, 0, len(list.Items)),\n\t\t\t}\n\n\t\t\tfor _, instance := range list.Items {\n\t\t\t\tif !gitopsconfig.ContainsTrigger(&instance, \"Webhook\") {\n\t\t\t\t\tlog.Info(\"skip instance without webhook trigger\", \"instance_name\", instance.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"comparing instance and event metadata\", \"event_name\", e.Repo.GetFullName(), \"event_ref\", e.GetRef(),\n\t\t\t\t\t\"template_uri\", instance.Spec.TemplateSource.URI, \"template_ref\", instance.Spec.TemplateSource.Ref,\n\t\t\t\t\t\"parameter_uri\", instance.Spec.ParameterSource.URI, \"parameter_ref\", instance.Spec.ParameterSource.Ref)\n\n\t\t\t\tif !repoURLAndRefMatch(&instance, e) {\n\t\t\t\t\tlog.Info(\"skip instance without matching repo url or git ref of the event\", \"instance_name\", instance.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"found matching instance\", \"instance_name\", instance.Name)\n\t\t\t\ttargetList.Items = append(targetList.Items, instance)\n\t\t\t}\n\n\t\t\tif len(targetList.Items) == 0 {\n\t\t\t\tlog.Info(\"no gitopsconfigs match the webhook event\", \"event_repo\", e.Repo.GetFullName(), \"event_ref\", strings.TrimPrefix(e.GetRef(), \"refs/heads/\"))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, instance := range targetList.Items {\n\t\t\t\t//if secured discard those that do not validate\n\t\t\t\tsecret := getWebhookSecret(&instance)\n\t\t\t\tif secret != \"\" {\n\t\t\t\t\t_, err := github.ValidatePayload(r, []byte(secret))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(err, \"webhook payload could not be validated with instance secret --> ignoring\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Webhook triggering job\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t_, err := reconciler.CreateJob(\"create\", &instance)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, \"Webhook unable to create job for instance\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tlog.Info(\"unknown event type\", \"type\", github.WebHookType(r))\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Info(\"webhook handling concluded correctly\")\n}", "func (w Webhook) Create(ctx context.Context, webhook *postmand.Webhook) error {\n\tquery, args := insertQuery(\"webhooks\", webhook)\n\t_, err := w.db.ExecContext(ctx, query, args...)\n\treturn err\n}", "func (s *WebhooksService) ListWebhooks(queryParams *ListWebhooksQueryParams) (*Webhooks, *resty.Response, error) {\n\n\tpath := \"/webhooks/\"\n\n\tqueryParamsString, _ := query.Values(queryParams)\n\n\tresponse, err := s.client.R().\n\t\tSetQueryString(queryParamsString.Encode()).\n\t\tSetResult(&Webhooks{}).\n\t\tSetError(&Error{}).\n\t\tGet(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Webhooks)\n\tif queryParams.Paginate {\n\t\titems := s.webhooksPagination(response.Header().Get(\"Link\"), 0, 0)\n\t\tfor _, webhook := range items.Items {\n\t\t\tresult.AddWebhook(webhook)\n\t\t}\n\t} else {\n\t\tif len(result.Items) < queryParams.Max {\n\t\t\titems := s.webhooksPagination(response.Header().Get(\"Link\"), len(result.Items), queryParams.Max)\n\t\t\tfor _, webhook := range items.Items {\n\t\t\t\tresult.AddWebhook(webhook)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, response, err\n\n}", "func (w *Webhook) AddContext(ctx context.Context) error {\n\treturn globalClient.AddWebHookContext(ctx, w)\n}", "func (s *WebhooksService) CreateWebhook(webhookCreateRequest *WebhookCreateRequest) (*Webhook, *resty.Response, error) {\n\n\tpath := \"/webhooks/\"\n\n\tresponse, err := s.client.R().\n\t\tSetBody(webhookCreateRequest).\n\t\tSetResult(&Webhook{}).\n\t\tSetError(&Error{}).\n\t\tPost(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Webhook)\n\treturn result, response, err\n\n}", "func (r *SpacesService) Webhooks(parent string, message *Message) *SpacesWebhooksCall {\n\tc := &SpacesWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func (v *Kounta) CreateSaleWebHook(token string, company string, webhook WebHook) error {\n\n\tfmt.Println(\"CreateSaleWebHook\", token, company, webhook)\n\n\tb, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.ParseRequestURI(baseURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.Path = fmt.Sprintf(webHookURL+\".json\", company)\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tr, err := http.NewRequest(\"POST\", urlStr, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Header.Add(\"Authorization\", \"Bearer \"+token)\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(b)))\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn fmt.Errorf(\"Failed init sale webhooks %s\", res.Status)\n\t}\n\n\treturn nil\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func add(mgr manager.Manager, r reconcile.Reconciler) error {\n\t// Create a new controller\n\tc, err := controller.New(\"mutatingwebhook-controller\", mgr, controller.Options{Reconciler: r})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch secret\n\terr = c.Watch(&source.Kind{Type: &corev1.Secret{}}, &handler.EnqueueRequestsFromMapFunc{\n\t\tToRequests: handler.ToRequestsFunc(func(obj handler.MapObject) []reconcile.Request {\n\t\t\trequests := []reconcile.Request{}\n\t\t\trequests = append(requests, reconcile.Request{\n\t\t\t\tNamespacedName: types.NamespacedName{\n\t\t\t\t\tName: webhookConfigNamePrefix + obj.Meta.GetNamespace(),\n\t\t\t\t\tNamespace: \"\",\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn requests\n\t\t})}, predicate.Funcs{\n\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\treturn event.Meta.GetName() == serviceAccountSecretName\n\t\t},\n\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\treturn event.MetaNew.GetName() == serviceAccountSecretName\n\t\t},\n\t\t// deletion and generic events don't interest us\n\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(event event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Watch MutatingWebhookConfigurations\n\terr = c.Watch(&source.Kind{Type: &v1beta1.MutatingWebhookConfiguration{}}, &handler.EnqueueRequestForObject{}, predicate.Funcs{\n\t\tCreateFunc: func(event event.CreateEvent) bool {\n\t\t\treturn strings.HasPrefix(event.Meta.GetName(), webhookConfigNamePrefix)\n\t\t},\n\t\tUpdateFunc: func(event event.UpdateEvent) bool {\n\t\t\treturn strings.HasPrefix(event.MetaNew.GetName(), webhookConfigNamePrefix)\n\t\t},\n\t\t// deletion and generic events don't interest us\n\t\tDeleteFunc: func(event event.DeleteEvent) bool {\n\t\t\treturn false\n\t\t},\n\t\tGenericFunc: func(event event.GenericEvent) bool {\n\t\t\treturn false\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (TelegramBotApp *TelegramBotApp) setupWebhook() (tgbotapi.UpdatesChannel, error) {\n\t_, err := TelegramBotApp.bot.SetWebhook(tgbotapi.NewWebhook(TelegramBotApp.conf.WebhookURL + \"/\" + TelegramBotApp.bot.Token))\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Webhook problem: \", err)\n\t\t//return nil, err\n\t}\n\tupdates := TelegramBotApp.bot.ListenForWebhook(\"/\" + TelegramBotApp.bot.Token)\n\tgo http.ListenAndServe(\":\"+TelegramBotApp.conf.Port, nil)\n\n\tfmt.Println(\"[+] Webhook method selected\")\n\n\treturn updates, nil\n\n}", "func (c *EcomClient) CreateWebhook(ctx context.Context, p *CreateWebhookRequest) (*WebhookResponse, error) {\n\trequest, err := json.Marshal(&p)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: client: json marshal\", err)\n\t}\n\n\turl := c.endpoint + \"/webhooks\"\n\tbody := strings.NewReader(string(request))\n\tres, err := c.request(http.MethodPost, url, body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: request\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\tvar e badRequestResponse\n\t\tdec := json.NewDecoder(res.Body)\n\t\tdec.DisallowUnknownFields()\n\t\tif err := dec.Decode(&e); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: client decode\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"status: %d, code: %s, message: %s\", e.Status, e.Code, e.Message)\n\t}\n\n\tvar webhook WebhookResponse\n\tif err = json.NewDecoder(res.Body).Decode(&webhook); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: decode\", err)\n\t}\n\treturn &webhook, nil\n}", "func NewWebhook(WebhookURL string) (whook *Webhook) {\n\twhook = &Webhook{\n\t\twebhookURL: WebhookURL,\n\t\tusingWebhook: false,\n\t}\n\n\tif whook.CheckWebhookExists() {\n\t\twhook.usingWebhook = true\n\t}\n\t\n\treturn whook\n}", "func (s *WebhookServiceOp) Create(ctx context.Context, webhook Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s.json\", webhooksBasePath)\n\twrappedData := WebhookResource{Webhook: &webhook}\n\tresource := new(WebhookResource)\n\terr := s.client.Post(ctx, path, wrappedData, resource)\n\treturn resource.Webhook, err\n}", "func postWebhook(webhookUrl string, webhookType string, p []byte) {\n\n\tvar payloadName string\n\tswitch webhookType {\n\tcase \"slack\":\n\t\tpayloadName = \"payload\"\n\tcase \"discord\":\n\t\tpayloadName = \"payload_json\"\n\t}\n\tresp, _ := http.PostForm(\n\t\twebhookUrl,\n\t\turl.Values{payloadName: {string(p)}},\n\t)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tfmt.Println(string(body))\n}", "func (f *UploadServiceGetAuditLogsForUploadFunc) PushHook(hook func(context.Context, int) ([]types.UploadLog, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (g *Gitlab) CreateWebHook(cfg *api.SCMConfig, repoURL string, webHook *scm.WebHook) error {\n\tif webHook == nil || len(webHook.Url) == 0 || len(webHook.Events) == 0 {\n\t\treturn fmt.Errorf(\"The webhook %v is not correct\", webHook)\n\t}\n\n\tclient, err := newGitlabClient(cfg.Server, cfg.Username, cfg.Token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenableState, disableState := true, false\n\t// Push event is enable for Gitlab webhook in default, so need to remove this default option.\n\thook := gitlab.AddProjectHookOptions{\n\t\tPushEvents: &disableState,\n\t}\n\n\tfor _, e := range webHook.Events {\n\t\tswitch e {\n\t\tcase scm.PullRequestEventType:\n\t\t\thook.MergeRequestsEvents = &enableState\n\t\tcase scm.PullRequestCommentEventType:\n\t\t\thook.NoteEvents = &enableState\n\t\tcase scm.PushEventType:\n\t\t\thook.PushEvents = &enableState\n\t\tcase scm.TagReleaseEventType:\n\t\t\thook.TagPushEvents = &enableState\n\t\tdefault:\n\t\t\tlog.Errorf(\"The event type %s is not supported, will be ignored\", e)\n\t\t\treturn nil\n\t\t}\n\t}\n\thook.URL = &webHook.Url\n\n\tonwer, name := parseURL(repoURL)\n\t_, _, err = client.Projects.AddProjectHook(onwer+\"/\"+name, &hook)\n\treturn err\n}", "func (f *PipelineAddFunc) PushHook(hook func(string, ...interface{})) {\n\tf.hooks = append(f.hooks, hook)\n}", "func (db *MongoDB) Add(w Webhook) (string, error) {\n\tw.ID = bson.NewObjectId()\n\n\terr := w.Validate()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\terr = Session.DB(db.DatabaseName).C(db.WebhooksCollectionName).Insert(w)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn w.ID.Hex(), nil\n}", "func (c *Client) WebhookPost(falcopayload types.FalcoPayload) {\n\terr := c.Post(falcopayload)\n\tif err != nil {\n\t\tc.Stats.Webhook.Add(Error, 1)\n\t\tc.PromStats.Outputs.With(map[string]string{\"destination\": \"webhook\", \"status\": Error}).Inc()\n\t} else {\n\t\tc.Stats.Webhook.Add(OK, 1)\n\t\tc.PromStats.Outputs.With(map[string]string{\"destination\": \"webhook\", \"status\": OK}).Inc()\n\t}\n\n\tc.Stats.Webhook.Add(Total, 1)\n}", "func NewWebhook(url string, filterFnString string, timeout uint64) (*Webhook, error) {\n\n\tvar err error\n\n\tif url == \"\" {\n\t\terr = errors.New(\"url parameter must be defined for webhook events.\")\n\t\treturn nil, err\n\t}\n\n\twh := &Webhook{\n\t\turl: url,\n\t}\n\tif filterFnString != \"\" {\n\t\twh.filter = NewJSEventFunction(filterFnString)\n\t}\n\n\tif timeout != 0 {\n\t\twh.timeout = time.Duration(timeout) * time.Second\n\t} else {\n\t\twh.timeout = time.Duration(kDefaultWebhookTimeout) * time.Second\n\t}\n\n\treturn wh, err\n}", "func AddToManager(ctx *context.ControllerManagerContext, mgr ctrlmgr.Manager) error {\n\thook, err := builder.NewMutatingWebhook(ctx, mgr, webHookName, NewMutator(mgr.GetClient()))\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"failed to create mutation webhook\")\n\t}\n\tmgr.GetWebhookServer().Register(hook.Path, hook)\n\n\treturn nil\n}", "func NewWebhook() *prometheusruleWebhook {\n\tscheme := runtime.NewScheme()\n\treturn &prometheusruleWebhook{\n\t\ts: *scheme,\n\t}\n}", "func (trello *Trello) EnsureHook(callbackURL string) {\n /* Check if we have a hook already */\n var data []webhookInfo\n GenGET(trello, \"/token/\" + trello.Token + \"/webhooks/\", &data)\n found := false\n\n for _, v := range data {\n /* Check if we have a hook for our own URL at same model */\n if v.Model == trello.BoardId {\n if v.URL == callbackURL {\n log.Print(\"Hook found, nothing to do here.\")\n found = true\n break\n }\n }\n }\n\n /* If not, install one */\n if !found {\n /* TODO: save hook reference and uninstall maybe? */\n GenPOSTForm(trello, \"/webhooks/\", nil, url.Values{\n \"name\": { \"trellohub for \" + trello.BoardId },\n \"idModel\": { trello.BoardId },\n \"callbackURL\": { callbackURL } })\n\n log.Print(\"Webhook installed.\")\n } else {\n log.Print(\"Reusing existing webhook.\")\n }\n}", "func (c *MockWebhookClient) CreateWebhook(ctx context.Context, repo bitbucket.Repo, hook bitbucket.Webhook) (result bitbucket.Webhook, err error) {\n\treturn c.MockCreateWebhook(ctx, repo, hook)\n}", "func New(options ...Option) (*Webhook, error) {\n\thook := new(Webhook)\n\tfor _, opt := range options {\n\t\tif err := opt(hook); err != nil {\n\t\t\treturn nil, errors.New(\"Error applying Option\")\n\t\t}\n\t}\n\treturn hook, nil\n}", "func Webhooks(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlog.Infof(ctx, \"GET /webhooks\")\n\tvar webhooksObj model.WebhooksObj\n\tmakeWebhooksObj(&webhooksObj, r.URL.Query())\n\tlog.Infof(ctx, \"webhooksObj is: %+v\", webhooksObj)\n\n\tgaeMail := makeGaeMailForWebhooks(ctx, &webhooksObj)\n\tgaeMail.Send()\n}", "func New(\n\tctx context.Context,\n\tcontrollers []interface{},\n) (webhook *Webhook, err error) {\n\n\t// ServeMux.Handle panics on duplicate paths\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"error creating webhook %v\", r)\n\t\t}\n\t}()\n\n\topts := GetOptions(ctx)\n\tif opts == nil {\n\t\treturn nil, errors.New(\"context must have Options specified\")\n\t}\n\tlogger := logging.FromContext(ctx)\n\n\tif opts.StatsReporter == nil {\n\t\treporter, err := NewStatsReporter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts.StatsReporter = reporter\n\t}\n\n\tdefaultTLSMinVersion := uint16(tls.VersionTLS13)\n\tif opts.TLSMinVersion == 0 {\n\t\topts.TLSMinVersion = TLSMinVersionFromEnv(defaultTLSMinVersion)\n\t} else if opts.TLSMinVersion != tls.VersionTLS12 && opts.TLSMinVersion != tls.VersionTLS13 {\n\t\treturn nil, fmt.Errorf(\"unsupported TLS version: %d\", opts.TLSMinVersion)\n\t}\n\n\tsyncCtx, cancel := context.WithCancel(context.Background())\n\n\twebhook = &Webhook{\n\t\tOptions: *opts,\n\t\tLogger: logger,\n\t\tsynced: cancel,\n\t}\n\n\tif opts.SecretName != \"\" {\n\t\t// Injection is too aggressive for this case because by simply linking this\n\t\t// library we force consumers to have secret access. If we require that one\n\t\t// of the admission controllers' informers *also* require the secret\n\t\t// informer, then we can fetch the shared informer factory here and produce\n\t\t// a new secret informer from it.\n\t\tsecretInformer := kubeinformerfactory.Get(ctx).Core().V1().Secrets()\n\n\t\twebhook.tlsConfig = &tls.Config{\n\t\t\tMinVersion: opts.TLSMinVersion,\n\n\t\t\t// If we return (nil, error) the client sees - 'tls: internal error\"\n\t\t\t// If we return (nil, nil) the client sees - 'tls: no certificates configured'\n\t\t\t//\n\t\t\t// We'll return (nil, nil) when we don't find a certificate\n\t\t\tGetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\t\tsecret, err := secretInformer.Lister().Secrets(system.Namespace()).Get(opts.SecretName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorw(\"failed to fetch secret\", zap.Error(err))\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\twebOpts := GetOptions(ctx)\n\t\t\t\tsKey, sCert := getSecretDataKeyNamesOrDefault(webOpts.ServerPrivateKeyName, webOpts.ServerCertificateName)\n\t\t\t\tserverKey, ok := secret.Data[sKey]\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Warn(\"server key missing\")\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\tserverCert, ok := secret.Data[sCert]\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Warn(\"server cert missing\")\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\tcert, err := tls.X509KeyPair(serverCert, serverKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\treturn &cert, nil\n\t\t\t},\n\t\t}\n\t}\n\n\twebhook.mux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, fmt.Sprint(\"no controller registered for: \", html.EscapeString(r.URL.Path)), http.StatusBadRequest)\n\t})\n\n\tfor _, controller := range controllers {\n\t\tswitch c := controller.(type) {\n\t\tcase AdmissionController:\n\t\t\thandler := admissionHandler(logger, opts.StatsReporter, c, syncCtx.Done())\n\t\t\twebhook.mux.Handle(c.Path(), handler)\n\n\t\tcase ConversionController:\n\t\t\thandler := conversionHandler(logger, opts.StatsReporter, c)\n\t\t\twebhook.mux.Handle(c.Path(), handler)\n\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown webhook controller type: %T\", controller)\n\t\t}\n\t}\n\n\treturn\n}", "func (b *Bot) SetWebhook(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"setWebhook\", request); err == nil {\n\t\tresult = response.(bool)\n\t}\n\treturn\n}", "func GetWebhooksForEvent(event models.EventType) []models.Webhook {\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := `SELECT * FROM (\n\t\tWITH RECURSIVE split(id, url, event, rest) AS (\n\t\t SELECT id, url, '', events || ',' FROM webhooks\n\t\t UNION ALL\n\t\t SELECT id, url,\n\t\t\t\t substr(rest, 0, instr(rest, ',')),\n\t\t\t\t substr(rest, instr(rest, ',')+1)\n\t\t\tFROM split\n\t\t WHERE rest <> '')\n\t\tSELECT id, url, event\n\t\t FROM split\n\t\t WHERE event <> ''\n\t ) AS webhook WHERE event IS \"` + event + `\"`\n\n\trows, err := _db.Query(query)\n\tif err != nil || rows.Err() != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\n\t\tif err := rows.Scan(&id, &url, &event); err != nil {\n\t\t\tlog.Debugln(err)\n\t\t\tlog.Error(\"There is a problem with the database.\")\n\t\t\tbreak\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\treturn webhooks\n}", "func New(mgr manager.Manager, args Args) (*Webhook, error) {\n\tlogger := log.Log.WithName(args.Name).WithValues(\"provider\", args.Provider)\n\n\t// Create handler\n\tbuilder := NewBuilder(mgr, logger)\n\n\tfor val, objs := range args.Validators {\n\t\tbuilder.WithValidator(val, objs...)\n\t}\n\n\tfor mut, objs := range args.Mutators {\n\t\tbuilder.WithMutator(mut, objs...)\n\t}\n\n\tbuilder.WithPredicates(args.Predicates...)\n\n\thandler, err := builder.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create webhook\n\tlogger.Info(\"Creating webhook\")\n\n\treturn &Webhook{\n\t\tPath: args.Path,\n\t\tWebhook: &admission.Webhook{Handler: handler},\n\t}, nil\n}", "func WithWebhookIP(ip string) WebhookOption {\n\treturn func(webhook *Webhook) {\n\t\twebhook.ip = ip\n\t}\n}", "func GetWebhooks() []*Webhook {\n\twebhooks := make([]*Webhook, 0, len(webhooksRegistry))\n\tfor _, wh := range webhooksRegistry {\n\t\twebhooks = append(webhooks, wh)\n\t}\n\treturn webhooks\n}", "func GetWebhooks() ([]models.Webhook, error) { //nolint\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := \"SELECT * FROM webhooks\"\n\n\trows, err := _db.Query(query)\n\tif err != nil {\n\t\treturn webhooks, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\t\tvar events string\n\t\tvar timestampString string\n\t\tvar lastUsedString *string\n\n\t\tif err := rows.Scan(&id, &url, &events, &timestampString, &lastUsedString); err != nil {\n\t\t\tlog.Error(\"There is a problem reading the database.\", err)\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\ttimestamp, err := time.Parse(time.RFC3339, timestampString)\n\t\tif err != nil {\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\tvar lastUsed *time.Time\n\t\tif lastUsedString != nil {\n\t\t\tlastUsedTime, _ := time.Parse(time.RFC3339, *lastUsedString)\n\t\t\tlastUsed = &lastUsedTime\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t\tEvents: strings.Split(events, \",\"),\n\t\t\tTimestamp: timestamp,\n\t\t\tLastUsed: lastUsed,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn webhooks, err\n\t}\n\n\treturn webhooks, nil\n}", "func (b *Bot) SetWebhook(w *Webhook) error {\n\t_, err := b.sendFiles(\"setWebhook\", w.getFiles(), w.getParams())\n\treturn err\n}", "func (b *Bot) RemoveWebhook(dropPending ...bool) error {\n\tdrop := false\n\tif len(dropPending) > 0 {\n\t\tdrop = dropPending[0]\n\t}\n\t_, err := b.Raw(\"deleteWebhook\", map[string]bool{\n\t\t\"drop_pending_updates\": drop,\n\t})\n\treturn err\n}", "func (r *RoomsService) Webhooks(parent string, message *Message) *RoomsWebhooksCall {\n\tc := &RoomsWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func SetupWithWebhooks(mgr manager.Manager) {\n\thookServer := mgr.GetWebhookServer()\n\n\thookServer.Register(\"/validate-core-kubernetes-v1-resource-quota\", &webhook.Admission{Handler: &quota.ResourceQuotaValidator{PivotClient: utils.PivotClient}})\n\n\thookServer.Register(\"/warden-validate-hotplug-kubecube-io-v1-hotplug\", admisson.ValidatingWebhookFor(hotplug.NewHotplugValidator()))\n\n}", "func NewWebhook(timeout time.Duration) filters.Spec {\n\treturn WebhookWithOptions(WebhookOptions{Timeout: timeout, Tracer: opentracing.NoopTracer{}})\n}", "func AddBOSHDeploymentValidator(log *zap.SugaredLogger, config *config.Config, mgr manager.Manager) (webhook.Webhook, error) {\n\tlog.Info(\"Setting up validator for BOSHDeployment\")\n\n\tboshDeploymentValidator := NewValidator(log, config)\n\n\tvalidatingWebhook, err := builder.NewWebhookBuilder().\n\t\tName(admissionWebhookName).\n\t\tPath(admissionWebHookPath).\n\t\tValidating().\n\t\tNamespaceSelector(&metav1.LabelSelector{\n\t\t\tMatchLabels: map[string]string{\n\t\t\t\t\"cf-operator-ns\": config.Namespace,\n\t\t\t},\n\t\t}).\n\t\tForType(&bdv1.BOSHDeployment{}).\n\t\tHandlers(boshDeploymentValidator).\n\t\tWithManager(mgr).\n\t\tFailurePolicy(admissionregistrationv1beta1.Fail).\n\t\tBuild()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"couldn't build a new validating webhook\")\n\t}\n\n\treturn validatingWebhook, nil\n}", "func NewWebhook(token string) *Webhook {\n\treturn &Webhook{\n\t\tToken: token,\n\t}\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func NewWebhook(ops ...ConfigOption) (*Webhook, error) {\n\tconf := toConfig(ops...)\n\ttemplater, err := templates.NewTemplater(conf.templateName, conf.sidecarConfig, conf.sidecarTemplate)\n\tif err != nil {\n\t\topenlogging.Error(fmt.Sprintf(\"new templater failed: error = %v, template = %s\", err.Error(), conf.templateName))\n\t\treturn nil, err\n\t}\n\n\treturn &Webhook{\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", conf.port),\n\t\t\tTLSConfig: &tls.Config{GetCertificate: conf.getCertificate},\n\t\t},\n\t\tconfig: conf,\n\t\ttemplater: templater,\n\t}, nil\n}", "func (f *ExtensionStoreUpdateFunc) PushHook(hook func(context.Context, int32, *string) error) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func AddAPIKeyHook(hookPoint boil.HookPoint, apiKeyHook APIKeyHook) {\n\tswitch hookPoint {\n\tcase boil.BeforeInsertHook:\n\t\tapiKeyBeforeInsertHooks = append(apiKeyBeforeInsertHooks, apiKeyHook)\n\tcase boil.BeforeUpdateHook:\n\t\tapiKeyBeforeUpdateHooks = append(apiKeyBeforeUpdateHooks, apiKeyHook)\n\tcase boil.BeforeDeleteHook:\n\t\tapiKeyBeforeDeleteHooks = append(apiKeyBeforeDeleteHooks, apiKeyHook)\n\tcase boil.BeforeUpsertHook:\n\t\tapiKeyBeforeUpsertHooks = append(apiKeyBeforeUpsertHooks, apiKeyHook)\n\tcase boil.AfterInsertHook:\n\t\tapiKeyAfterInsertHooks = append(apiKeyAfterInsertHooks, apiKeyHook)\n\tcase boil.AfterSelectHook:\n\t\tapiKeyAfterSelectHooks = append(apiKeyAfterSelectHooks, apiKeyHook)\n\tcase boil.AfterUpdateHook:\n\t\tapiKeyAfterUpdateHooks = append(apiKeyAfterUpdateHooks, apiKeyHook)\n\tcase boil.AfterDeleteHook:\n\t\tapiKeyAfterDeleteHooks = append(apiKeyAfterDeleteHooks, apiKeyHook)\n\tcase boil.AfterUpsertHook:\n\t\tapiKeyAfterUpsertHooks = append(apiKeyAfterUpsertHooks, apiKeyHook)\n\t}\n}", "func CreateWebhookListener(config,\n\tremoteConfig *rest.Config,\n\tscheme *runtime.Scheme,\n\ttlsKeyFile, tlsCrtFile string,\n\tcreateService bool) (*WebhookListener, error) {\n\tif klog.V(utils.QuiteLogLel) {\n\t\tfnName := utils.GetFnName()\n\t\tklog.Infof(\"Entering: %v()\", fnName)\n\n\t\tdefer klog.Infof(\"Exiting: %v()\", fnName)\n\t}\n\n\tvar err error\n\n\tdynamicClient := dynamic.NewForConfigOrDie(config)\n\n\tl := &WebhookListener{\n\t\tDynamicClient: dynamicClient,\n\t\tlocalConfig: config,\n\t}\n\n\t// The user-provided key and cert files take precedence over the default provided files if both sets exist.\n\tif _, err := os.Stat(defaultKeyFile); err == nil {\n\t\tl.TLSKeyFile = defaultKeyFile\n\t}\n\n\tif _, err := os.Stat(defaultCrtFile); err == nil {\n\t\tl.TLSCrtFile = defaultCrtFile\n\t}\n\n\tif _, err := os.Stat(tlsKeyFile); err == nil {\n\t\tl.TLSKeyFile = tlsKeyFile\n\t}\n\n\tif _, err := os.Stat(tlsCrtFile); err == nil {\n\t\tl.TLSCrtFile = tlsCrtFile\n\t}\n\n\tl.LocalClient, err = client.New(config, client.Options{})\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to initialize client to update local status. error: \", err)\n\t\treturn nil, err\n\t}\n\n\tl.RemoteClient = l.LocalClient\n\tif remoteConfig != nil {\n\t\tl.RemoteClient, err = client.New(remoteConfig, client.Options{})\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to initialize client to update remote status. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif createService {\n\t\tnamespace, err := getOperatorNamespace()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create the webhook listener service only when the subscription controller runs in hub mode.\n\t\terr = createWebhookListnerService(l.LocalClient, namespace)\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to create a service for Git webhook listener. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn l, err\n}", "func (rec *Recorder) AddHook(handler HookFunc, kind HookKind) {\n\thook := NewHook(handler, kind)\n\trec.hooks = append(rec.hooks, hook)\n}", "func AddWeatherHook(hookPoint boil.HookPoint, weatherHook WeatherHook) {\n\tswitch hookPoint {\n\tcase boil.BeforeInsertHook:\n\t\tweatherBeforeInsertHooks = append(weatherBeforeInsertHooks, weatherHook)\n\tcase boil.BeforeUpdateHook:\n\t\tweatherBeforeUpdateHooks = append(weatherBeforeUpdateHooks, weatherHook)\n\tcase boil.BeforeDeleteHook:\n\t\tweatherBeforeDeleteHooks = append(weatherBeforeDeleteHooks, weatherHook)\n\tcase boil.BeforeUpsertHook:\n\t\tweatherBeforeUpsertHooks = append(weatherBeforeUpsertHooks, weatherHook)\n\tcase boil.AfterInsertHook:\n\t\tweatherAfterInsertHooks = append(weatherAfterInsertHooks, weatherHook)\n\tcase boil.AfterSelectHook:\n\t\tweatherAfterSelectHooks = append(weatherAfterSelectHooks, weatherHook)\n\tcase boil.AfterUpdateHook:\n\t\tweatherAfterUpdateHooks = append(weatherAfterUpdateHooks, weatherHook)\n\tcase boil.AfterDeleteHook:\n\t\tweatherAfterDeleteHooks = append(weatherAfterDeleteHooks, weatherHook)\n\tcase boil.AfterUpsertHook:\n\t\tweatherAfterUpsertHooks = append(weatherAfterUpsertHooks, weatherHook)\n\t}\n}", "func (f *ExtensionStoreCreateFunc) PushHook(hook func(context.Context, int32, int32, string) (int32, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func Add(mgr manager.Manager) error {\n\tlog.Info(\"Setting up mutating webhook for KnativeServing\")\n\thookServer := mgr.GetWebhookServer()\n\thookServer.Register(\"/mutate-v1alpha1-knativeserving\", &webhook.Admission{Handler: &KnativeServingConfigurator{}})\n\treturn nil\n}", "func (f *UploadServiceGetUploadDocumentsForPathFunc) PushHook(hook func(context.Context, int, string) ([]string, int, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func TestWebHook(t *testing.T) {\n\tg := gomega.NewGomegaWithT(t)\n\tg.Expect(createCertificates(t)).NotTo(gomega.HaveOccurred())\n\n\t// create manager\n\tmgr, err := manager.New(cfg, manager.Options{\n\t\tMetricsBindAddress: \"0\",\n\t})\n\tg.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tc = mgr.GetClient()\n\n\t// add webhook to manager\n\tAdd(mgr)\n\n\t// start manager\n\tstopMgr, mgrStopped := StartTestManager(mgr, g)\n\tdefer func() {\n\t\tclose(stopMgr)\n\t\tmgrStopped.Wait()\n\t}()\n\n\tg.Expect(c.Create(context.TODO(), fnConfig)).NotTo(gomega.HaveOccurred())\n\n\ttestInvalidFunc(t)\n\ttestHandleDefaults(t)\n}", "func (h *GitHubWebhook) Register(handler WebhookHandler, eventTypes ...string) {\n\th.mu.Lock()\n\tdefer h.mu.Unlock()\n\tif h.handlers == nil {\n\t\th.handlers = make(map[string][]WebhookHandler)\n\t}\n\tfor _, eventType := range eventTypes {\n\t\th.handlers[eventType] = append(h.handlers[eventType], handler)\n\t}\n}", "func (s *WebhooksServiceOp) List(options ...interface{}) ([]Webhook, error) {\n\twebhookListResponse := ListWebhookResponse{}\n\tbody, reqErr := s.client.DoRequest(http.MethodGet, \"/v3/hooks\", nil)\n\tif reqErr != nil {\n\t\treturn webhookListResponse.Data, reqErr\n\t}\n\tjsonErr := json.Unmarshal(body, &webhookListResponse)\n\tif jsonErr != nil {\n\t\treturn webhookListResponse.Data, jsonErr\n\t}\n\treturn webhookListResponse.Data, nil\n}", "func (f *JobRunFunc) PushHook(hook func(context.Context, database.DB, streaming.Sender) (*search.Alert, error)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (f *WithHooksPostHandleFunc) PushHook(hook func(context.Context, Record)) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func (w *Webman) StartWebhook(endpoint, listenAddr string, fn func(*http.Request) error) error {\n\tw.webhook = &Webhook{\n\t\twebman: w,\n\t\tfn: fn,\n\t}\n\n\tr := mux.NewRouter()\n\tr.HandleFunc(endpoint, w.webhook.handler).Methods(\"POST\")\n\n\tserver := &graceful.Server{\n\t\tTimeout: w.timeout,\n\t\tServer: &http.Server{\n\t\t\tAddr: listenAddr,\n\t\t\tHandler: r,\n\t\t},\n\t}\n\tw.mw.Lock()\n\tw.webhook.server = server\n\tw.mw.Unlock()\n\n\tw.log.Printf(\"webhook server started at: %s:\", listenAddr)\n\treturn w.webhook.server.ListenAndServe()\n}", "func (f *DBStoreUpdateUploadRetentionFunc) PushHook(hook func(context.Context, []int, []int) error) {\n\tf.mutex.Lock()\n\tf.hooks = append(f.hooks, hook)\n\tf.mutex.Unlock()\n}", "func TestCreateAndGetWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tpayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(payload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\t_, err = c.GetWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while getting webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func (c WebhooksConfig) NewWebhooks(ctx context.Context, server io.Server) (web.Webhooks, error) {\n\tvar target web.Sink\n\tswitch c.Target {\n\tcase \"\":\n\t\treturn nil, nil\n\tcase \"direct\":\n\t\ttarget = &web.HTTPClientSink{\n\t\t\tClient: &http.Client{\n\t\t\t\tTimeout: c.Timeout,\n\t\t\t},\n\t\t}\n\tdefault:\n\t\treturn nil, errWebhooksTarget.WithAttributes(\"target\", c.Target)\n\t}\n\tif c.Registry == nil {\n\t\treturn nil, errWebhooksRegistry.New()\n\t}\n\tif c.QueueSize > 0 || c.Workers > 0 {\n\t\ttarget = &web.QueuedSink{\n\t\t\tTarget: target,\n\t\t\tQueue: make(chan *http.Request, c.QueueSize),\n\t\t\tWorkers: c.Workers,\n\t\t}\n\t}\n\tif controllable, ok := target.(web.ControllableSink); ok {\n\t\tgo func() {\n\t\t\tif err := controllable.Run(ctx); err != nil && !errors.IsCanceled(err) {\n\t\t\t\tlog.FromContext(ctx).WithError(err).Error(\"Webhooks target sink failed\")\n\t\t\t}\n\t\t}()\n\t}\n\treturn web.NewWebhooks(ctx, server, c.Registry, target, c.Downlinks), nil\n}", "func ExtensionWebService(r Resource) *restful.WebService {\n\tws := new(restful.WebService)\n\tws.\n\t\tPath(\"/webhooks\").\n\t\tConsumes(restful.MIME_JSON, restful.MIME_JSON).\n\t\tProduces(restful.MIME_JSON, restful.MIME_JSON)\n\n\tws.Route(ws.POST(\"/\").To(r.createWebhook))\n\tws.Route(ws.GET(\"/\").To(r.getAllWebhooks))\n\tws.Route(ws.GET(\"/defaults\").To(r.getDefaults))\n\n\treturn ws\n}", "func (mock *MailgunMock) CreateWebhookCalls() []struct {\n\tKind string\n\tURL string\n} {\n\tvar calls []struct {\n\t\tKind string\n\t\tURL string\n\t}\n\tlockMailgunMockCreateWebhook.RLock()\n\tcalls = mock.calls.CreateWebhook\n\tlockMailgunMockCreateWebhook.RUnlock()\n\treturn calls\n}", "func addKey(Writer http.ResponseWriter, Request *http.Request) {\n\tdefer Request.Body.Close()\n\terr := jwt.ValidateToken(Request.Header[\"Authorization\"][0])\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stdout, \"POST\\t\\\\KeyHook\\t\"+string(http.StatusUnauthorized)+\"\\n\")\n\t\tWriter.WriteHeader(http.StatusUnauthorized)\n\t\tWriter.Write([]byte(\"Invalid Token\"))\n\t\treturn\n\t}\n\n\taddRequest := keyHookRequest{}\n\terr = json.NewDecoder(Request.Body).Decode(&addRequest)\n\tif err != nil {\n\t\tfmt.Fprintf(os.Stderr, err.Error()+\"\\n\")\n\t\tfmt.Fprintf(os.Stdout, \"POST\\t\\\\KeyHook\\t\"+string(http.StatusInternalServerError)+\"\\n\")\n\t\tWriter.WriteHeader(http.StatusInternalServerError)\n\t\tWriter.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\terr = keyhook.AddNewKey(addRequest.ID, addRequest.Website)\n\tif err != nil {\n\t\tfmt.Printf(\"POST\\t\\\\Auth\\t500\\n\")\n\t\tWriter.WriteHeader(http.StatusInternalServerError)\n\t\tWriter.Write([]byte(err.Error()))\n\t\treturn\n\t}\n\n\tfmt.Printf(\"POST\\t\\\\Auth\\t202\\n\")\n\tWriter.WriteHeader(http.StatusAccepted)\n\treturn\n\n}", "func (l *Lifecycle) Append(hook Hook) {\n\t// Save the caller's stack frame to report file/line number.\n\tif f := fxreflect.CallerStack(2, 0); len(f) > 0 {\n\t\thook.callerFrame = f[0]\n\t}\n\tl.hooks = append(l.hooks, hook)\n}", "func (f *PipelineRunFunc) PushHook(hook func() (interface{}, error)) {\n\tf.hooks = append(f.hooks, hook)\n}", "func (c WebhooksConfig) NewWebhooks(ctx context.Context, server io.Server) (web.Webhooks, error) {\n\tvar target web.Sink\n\tswitch c.Target {\n\tcase \"\":\n\t\treturn nil, nil\n\tcase \"direct\":\n\t\tclient, err := server.HTTPClient(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tclient.Timeout = c.Timeout\n\t\ttarget = &web.HTTPClientSink{\n\t\t\tClient: client,\n\t\t}\n\tdefault:\n\t\treturn nil, errWebhooksTarget.WithAttributes(\"target\", c.Target)\n\t}\n\tif c.Registry == nil {\n\t\treturn nil, errWebhooksRegistry.New()\n\t}\n\tif c.QueueSize > 0 || c.Workers > 0 {\n\t\ttarget = &web.QueuedSink{\n\t\t\tTarget: target,\n\t\t\tQueue: make(chan *http.Request, c.QueueSize),\n\t\t\tWorkers: c.Workers,\n\t\t}\n\t}\n\tif controllable, ok := target.(web.ControllableSink); ok {\n\t\tgo func() {\n\t\t\tif err := controllable.Run(ctx); err != nil && !errors.IsCanceled(err) {\n\t\t\t\tlog.FromContext(ctx).WithError(err).Error(\"Webhooks target sink failed\")\n\t\t\t}\n\t\t}()\n\t}\n\treturn web.NewWebhooks(ctx, server, c.Registry, target, c.Downlinks)\n}", "func (g *GitHub) CreateHook(service *api.Service) error {\n\twebhooktype := service.Repository.Webhook\n\tif webhooktype == \"\" {\n\t\treturn fmt.Errorf(\"no need webhook registry\")\n\t}\n\n\tif webhooktype == api.GITHUB {\n\t\turl := getHookURL(webhooktype, service.ServiceID)\n\t\tif url == \"\" {\n\t\t\tlog.Infof(\"url is empty\", log.Fields{\"user_id\": service.UserID})\n\t\t\treturn nil\n\t\t}\n\n\t\tds := store.NewStore()\n\t\tdefer ds.Close()\n\n\t\ttok, err := ds.FindtokenByUserID(service.UserID, api.GITHUB)\n\t\tif err != nil {\n\t\t\tlog.ErrorWithFields(\"find token failed\", log.Fields{\"user_id\": service.UserID, \"error\": err})\n\t\t\treturn err\n\t\t}\n\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: tok.Vsctoken.AccessToken},\n\t\t)\n\t\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\t\tclient := github.NewClient(tc)\n\n\t\tvar hook github.Hook\n\t\thook.Name = github.String(\"web\")\n\t\thook.Events = []string{\"push\", \"pull_request\"}\n\t\thook.Config = map[string]interface{}{}\n\t\thook.Config[\"url\"] = url\n\t\thook.Config[\"content_type\"] = \"json\"\n\t\tonwer, name := parseURL(service.Repository.URL)\n\t\t_, _, err = client.Repositories.CreateHook(onwer, name, &hook)\n\t\treturn err\n\t}\n\tlog.WarnWithFields(\"not support vcs repository\", log.Fields{\"vcs repository\": webhooktype})\n\treturn fmt.Errorf(\"not support vcs repository in create webhook\")\n}" ]
[ "0.7258891", "0.70565635", "0.64024055", "0.6374247", "0.62231016", "0.61942786", "0.6190991", "0.6102132", "0.6034921", "0.58705044", "0.5861128", "0.5833314", "0.58317864", "0.58306634", "0.57757217", "0.57751566", "0.5752552", "0.57346755", "0.57092667", "0.5688974", "0.5677393", "0.5667996", "0.56304216", "0.5617168", "0.56171626", "0.558937", "0.557201", "0.5568299", "0.5567745", "0.5562658", "0.55426776", "0.55364966", "0.55358094", "0.5527721", "0.5489764", "0.5476294", "0.5457597", "0.54547364", "0.54462796", "0.54355365", "0.54310167", "0.5430998", "0.54276717", "0.5425583", "0.5423119", "0.5418659", "0.5410935", "0.5402451", "0.53968424", "0.5393785", "0.5358475", "0.5318888", "0.531604", "0.53116137", "0.53018665", "0.5292541", "0.5287529", "0.5285533", "0.52629256", "0.5255249", "0.5239681", "0.5237759", "0.5236567", "0.5206152", "0.5203443", "0.5201716", "0.5201511", "0.5200715", "0.5198321", "0.5190899", "0.51840407", "0.5183973", "0.518276", "0.5176471", "0.5175856", "0.5166453", "0.51584435", "0.51541984", "0.5149908", "0.51211524", "0.51096195", "0.5106781", "0.51048553", "0.5102853", "0.50944537", "0.50886106", "0.5082265", "0.5080372", "0.5079542", "0.5071156", "0.5067326", "0.5066139", "0.5055032", "0.50502557", "0.50441957", "0.5038466", "0.50336194", "0.5032216", "0.503025", "0.5028054" ]
0.6897466
2
CreateWebhook Creates a webhook. / Creates a webhook.
func (s *WebhooksService) CreateWebhook(webhookCreateRequest *WebhookCreateRequest) (*Webhook, *resty.Response, error) { path := "/webhooks/" response, err := s.client.R(). SetBody(webhookCreateRequest). SetResult(&Webhook{}). SetError(&Error{}). Post(path) if err != nil { return nil, nil, err } result := response.Result().(*Webhook) return result, response, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) CreateWebhook(req CreateWebhookReq) (Webhook, error) {\n\tvar res Webhook\n\terr := c.post(c.baseURL+\"/webhooks\", webhookReq{Webhook: req}, &res)\n\n\treturn res, err\n}", "func (z *Client) CreateWebhook(ctx context.Context, hook *Webhook) (*Webhook, error) {\n\tvar data, result struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\tdata.Webhook = hook\n\n\tbody, err := z.post(ctx, \"/webhooks\", data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.Webhook, nil\n}", "func (c *EcomClient) CreateWebhook(ctx context.Context, p *CreateWebhookRequest) (*WebhookResponse, error) {\n\trequest, err := json.Marshal(&p)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: client: json marshal\", err)\n\t}\n\n\turl := c.endpoint + \"/webhooks\"\n\tbody := strings.NewReader(string(request))\n\tres, err := c.request(http.MethodPost, url, body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: request\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\tvar e badRequestResponse\n\t\tdec := json.NewDecoder(res.Body)\n\t\tdec.DisallowUnknownFields()\n\t\tif err := dec.Decode(&e); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"%w: client decode\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"status: %d, code: %s, message: %s\", e.Status, e.Code, e.Message)\n\t}\n\n\tvar webhook WebhookResponse\n\tif err = json.NewDecoder(res.Body).Decode(&webhook); err != nil {\n\t\treturn nil, fmt.Errorf(\"%w: decode\", err)\n\t}\n\treturn &webhook, nil\n}", "func (w *WebhookServiceOp) Create(webhook Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s\", webhooksBasePath)\n\tresource := new(Webhook)\n\terr := w.client.Post(path, webhook, &resource)\n\treturn resource, err\n}", "func (s *WebhookServiceOp) Create(ctx context.Context, webhook Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s.json\", webhooksBasePath)\n\twrappedData := WebhookResource{Webhook: &webhook}\n\tresource := new(WebhookResource)\n\terr := s.client.Post(ctx, path, wrappedData, resource)\n\treturn resource.Webhook, err\n}", "func (s *WebhooksServiceOp) Create(webhook Webhook, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tjsonBody, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn webhookResponse.Data, err\n\t}\n\treqBody := bytes.NewReader(jsonBody)\n\tbody, reqErr := s.client.DoRequest(http.MethodPost, \"/v3/hooks\", reqBody)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\n\treturn webhookResponse.Data, nil\n}", "func (t *TauAPI) CreateWebhook(webhook Webhook) (ID int64, error error) {\n\tjsonPostMsg, _ := json.Marshal(webhook)\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"POST\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t\tPostMsg: jsonPostMsg,\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tif string(jsonData) == \"[\\\"Limit reached\\\"]\" {\n\t\treturn 0, fmt.Errorf(\"Limit of webhooks reached (5)\")\n\t}\n\tvar d struct {\n\t\tID int64 `json:\"id\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn 0, fmt.Errorf(\"CreateWebhook -> unmarshal jsonData %v\", err)\n\t}\n\treturn d.ID, nil\n}", "func CreateWebhook(user string, repo string, accesstoken string, webhookUrl string, secret string) (int, error) {\n\tdata := user + \":\" + accesstoken\n\tsEnc := base64.StdEncoding.EncodeToString([]byte(data))\n\tname := \"web\"\n\tactive := true\n\thook := github.Hook{\n\t\tName: &name,\n\t\tActive: &active,\n\t\tConfig: make(map[string]interface{}),\n\t\tEvents: []string{\"push\"},\n\t}\n\n\thook.Config[\"url\"] = webhookUrl\n\thook.Config[\"content_type\"] = \"json\"\n\thook.Config[\"secret\"] = secret\n\thook.Config[\"insecure_ssl\"] = \"1\"\n\n\tlogrus.Infof(\"hook to create:%v\", hook)\n\tb := new(bytes.Buffer)\n\tjson.NewEncoder(b).Encode(hook)\n\thc := http.Client{}\n\tAPIURL := fmt.Sprintf(\"https://api.github.com/repos/%v/%v/hooks\", user, repo)\n\treq, err := http.NewRequest(\"POST\", APIURL, b)\n\n\treq.Header.Add(\"Authorization\", \"Basic \"+sEnc)\n\n\tresp, err := hc.Do(req)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\trespData, err := ioutil.ReadAll(resp.Body)\n\tlogrus.Infof(\"respData:%v\", string(respData))\n\tif resp.StatusCode > 399 {\n\t\treturn -1, errors.New(string(respData))\n\t}\n\terr = json.Unmarshal(respData, &hook)\n\tif err != nil {\n\t\treturn -1, err\n\t}\n\treturn hook.GetID(), err\n}", "func (c *Client) CreateWebhook(ctx context.Context, repo bitbucket.Repo, hook bitbucket.Webhook) (bitbucket.Webhook, error) {\n\tmarshalledPayload, err := json.Marshal(hook)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo))\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewBuffer(marshalledPayload))\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\tvar response bitbucket.Webhook\n\tif err := c.sendRequest(req, &response); err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\treturn response, nil\n}", "func (c *ApiService) CreateWebhook(ServiceSid string, params *CreateWebhookParams) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.FriendlyName != nil {\n\t\tdata.Set(\"FriendlyName\", *params.FriendlyName)\n\t}\n\tif params != nil && params.EventTypes != nil {\n\t\tfor _, item := range *params.EventTypes {\n\t\t\tdata.Add(\"EventTypes\", item)\n\t\t}\n\t}\n\tif params != nil && params.WebhookUrl != nil {\n\t\tdata.Set(\"WebhookUrl\", *params.WebhookUrl)\n\t}\n\tif params != nil && params.Status != nil {\n\t\tdata.Set(\"Status\", *params.Status)\n\t}\n\tif params != nil && params.Version != nil {\n\t\tdata.Set(\"Version\", *params.Version)\n\t}\n\n\tresp, err := c.requestHandler.Post(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (g *V3) CreateWebhook(repo string, webhook *scm.Webhook) error {\n\tif webhook == nil || len(webhook.URL) == 0 || len(webhook.Events) == 0 {\n\t\treturn fmt.Errorf(\"The webhook %v is not correct\", webhook)\n\t}\n\n\t_, err := g.GetWebhook(repo, webhook.URL)\n\tif err != nil {\n\t\tif !cerr.ErrorContentNotFound.Derived(err) {\n\t\t\treturn err\n\t\t}\n\n\t\thook := generateV3ProjectHook(webhook)\n\t\t_, resp, err := g.client.Projects.AddProjectHook(repo, hook)\n\t\tif err != nil {\n\t\t\treturn convertGitlabError(err, resp)\n\t\t}\n\t\treturn nil\n\t}\n\n\tlog.Warningf(\"Webhook already existed: %+v\", webhook)\n\treturn err\n}", "func (w Webhook) Create(ctx context.Context, webhook *postmand.Webhook) error {\n\tquery, args := insertQuery(\"webhooks\", webhook)\n\t_, err := w.db.ExecContext(ctx, query, args...)\n\treturn err\n}", "func (c *MockWebhookClient) CreateWebhook(ctx context.Context, repo bitbucket.Repo, hook bitbucket.Webhook) (result bitbucket.Webhook, err error) {\n\treturn c.MockCreateWebhook(ctx, repo, hook)\n}", "func (wh *Webhook) Create(accountId string, data map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\tif accountId != \"\" {\n\t\turl := fmt.Sprintf(\"/%s%s/%s%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK)\n\t\treturn wh.Request.Post(url, data, extraHeaders)\n\t}\n\turl := fmt.Sprintf(\"/%s%s\", constants.VERSION_V1, constants.WEBHOOK)\n\treturn wh.Request.Post(url, data, extraHeaders)\n}", "func TestCreateAndGetWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tpayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(payload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\t_, err = c.GetWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while getting webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func NewWebhook(ctx *pulumi.Context,\n\tname string, args *WebhookArgs, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Name == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Name'\")\n\t}\n\tif args.Url == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Url'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Webhook\n\terr := ctx.RegisterResource(\"datadog:index/webhook:Webhook\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func NewWebhook(db *sqlx.DB) *Webhook {\n\treturn &Webhook{db: db}\n}", "func (m *Client) CreateWebhook(arg0 context.Context, arg1 *zendesk.Webhook) (*zendesk.Webhook, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"CreateWebhook\", arg0, arg1)\n\tret0, _ := ret[0].(*zendesk.Webhook)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func (v *Kounta) CreateSaleWebHook(token string, company string, webhook WebHook) error {\n\n\tfmt.Println(\"CreateSaleWebHook\", token, company, webhook)\n\n\tb, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.ParseRequestURI(baseURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.Path = fmt.Sprintf(webHookURL+\".json\", company)\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tr, err := http.NewRequest(\"POST\", urlStr, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Header.Add(\"Authorization\", \"Bearer \"+token)\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tr.Header.Add(\"Content-Length\", strconv.Itoa(len(b)))\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn fmt.Errorf(\"Failed init sale webhooks %s\", res.Status)\n\t}\n\n\treturn nil\n}", "func (g *Gitlab) CreateWebHook(cfg *api.SCMConfig, repoURL string, webHook *scm.WebHook) error {\n\tif webHook == nil || len(webHook.Url) == 0 || len(webHook.Events) == 0 {\n\t\treturn fmt.Errorf(\"The webhook %v is not correct\", webHook)\n\t}\n\n\tclient, err := newGitlabClient(cfg.Server, cfg.Username, cfg.Token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tenableState, disableState := true, false\n\t// Push event is enable for Gitlab webhook in default, so need to remove this default option.\n\thook := gitlab.AddProjectHookOptions{\n\t\tPushEvents: &disableState,\n\t}\n\n\tfor _, e := range webHook.Events {\n\t\tswitch e {\n\t\tcase scm.PullRequestEventType:\n\t\t\thook.MergeRequestsEvents = &enableState\n\t\tcase scm.PullRequestCommentEventType:\n\t\t\thook.NoteEvents = &enableState\n\t\tcase scm.PushEventType:\n\t\t\thook.PushEvents = &enableState\n\t\tcase scm.TagReleaseEventType:\n\t\t\thook.TagPushEvents = &enableState\n\t\tdefault:\n\t\t\tlog.Errorf(\"The event type %s is not supported, will be ignored\", e)\n\t\t\treturn nil\n\t\t}\n\t}\n\thook.URL = &webHook.Url\n\n\tonwer, name := parseURL(repoURL)\n\t_, _, err = client.Projects.AddProjectHook(onwer+\"/\"+name, &hook)\n\treturn err\n}", "func NewWebhook(WebhookURL string) (whook *Webhook) {\n\twhook = &Webhook{\n\t\twebhookURL: WebhookURL,\n\t\tusingWebhook: false,\n\t}\n\n\tif whook.CheckWebhookExists() {\n\t\twhook.usingWebhook = true\n\t}\n\t\n\treturn whook\n}", "func NewWebhook(ops ...ConfigOption) (*Webhook, error) {\n\tconf := toConfig(ops...)\n\ttemplater, err := templates.NewTemplater(conf.templateName, conf.sidecarConfig, conf.sidecarTemplate)\n\tif err != nil {\n\t\topenlogging.Error(fmt.Sprintf(\"new templater failed: error = %v, template = %s\", err.Error(), conf.templateName))\n\t\treturn nil, err\n\t}\n\n\treturn &Webhook{\n\t\tserver: &http.Server{\n\t\t\tAddr: fmt.Sprintf(\":%d\", conf.port),\n\t\t\tTLSConfig: &tls.Config{GetCertificate: conf.getCertificate},\n\t\t},\n\t\tconfig: conf,\n\t\ttemplater: templater,\n\t}, nil\n}", "func (g *GitHub) CreateHook(service *api.Service) error {\n\twebhooktype := service.Repository.Webhook\n\tif webhooktype == \"\" {\n\t\treturn fmt.Errorf(\"no need webhook registry\")\n\t}\n\n\tif webhooktype == api.GITHUB {\n\t\turl := getHookURL(webhooktype, service.ServiceID)\n\t\tif url == \"\" {\n\t\t\tlog.Infof(\"url is empty\", log.Fields{\"user_id\": service.UserID})\n\t\t\treturn nil\n\t\t}\n\n\t\tds := store.NewStore()\n\t\tdefer ds.Close()\n\n\t\ttok, err := ds.FindtokenByUserID(service.UserID, api.GITHUB)\n\t\tif err != nil {\n\t\t\tlog.ErrorWithFields(\"find token failed\", log.Fields{\"user_id\": service.UserID, \"error\": err})\n\t\t\treturn err\n\t\t}\n\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: tok.Vsctoken.AccessToken},\n\t\t)\n\t\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\t\tclient := github.NewClient(tc)\n\n\t\tvar hook github.Hook\n\t\thook.Name = github.String(\"web\")\n\t\thook.Events = []string{\"push\", \"pull_request\"}\n\t\thook.Config = map[string]interface{}{}\n\t\thook.Config[\"url\"] = url\n\t\thook.Config[\"content_type\"] = \"json\"\n\t\tonwer, name := parseURL(service.Repository.URL)\n\t\t_, _, err = client.Repositories.CreateHook(onwer, name, &hook)\n\t\treturn err\n\t}\n\tlog.WarnWithFields(\"not support vcs repository\", log.Fields{\"vcs repository\": webhooktype})\n\treturn fmt.Errorf(\"not support vcs repository in create webhook\")\n}", "func (a *ManagementApiService) CreateNotificationWebhook(ctx _context.Context, applicationId int32) apiCreateNotificationWebhookRequest {\n\treturn apiCreateNotificationWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t}\n}", "func NewWebhook(token string) *Webhook {\n\treturn &Webhook{\n\t\tToken: token,\n\t}\n}", "func NewWebhook(url string, filterFnString string, timeout uint64) (*Webhook, error) {\n\n\tvar err error\n\n\tif url == \"\" {\n\t\terr = errors.New(\"url parameter must be defined for webhook events.\")\n\t\treturn nil, err\n\t}\n\n\twh := &Webhook{\n\t\turl: url,\n\t}\n\tif filterFnString != \"\" {\n\t\twh.filter = NewJSEventFunction(filterFnString)\n\t}\n\n\tif timeout != 0 {\n\t\twh.timeout = time.Duration(timeout) * time.Second\n\t} else {\n\t\twh.timeout = time.Duration(kDefaultWebhookTimeout) * time.Second\n\t}\n\n\treturn wh, err\n}", "func CreateWebhookListener(config,\n\tremoteConfig *rest.Config,\n\tscheme *runtime.Scheme,\n\ttlsKeyFile, tlsCrtFile string,\n\tcreateService bool) (*WebhookListener, error) {\n\tif klog.V(utils.QuiteLogLel) {\n\t\tfnName := utils.GetFnName()\n\t\tklog.Infof(\"Entering: %v()\", fnName)\n\n\t\tdefer klog.Infof(\"Exiting: %v()\", fnName)\n\t}\n\n\tvar err error\n\n\tdynamicClient := dynamic.NewForConfigOrDie(config)\n\n\tl := &WebhookListener{\n\t\tDynamicClient: dynamicClient,\n\t\tlocalConfig: config,\n\t}\n\n\t// The user-provided key and cert files take precedence over the default provided files if both sets exist.\n\tif _, err := os.Stat(defaultKeyFile); err == nil {\n\t\tl.TLSKeyFile = defaultKeyFile\n\t}\n\n\tif _, err := os.Stat(defaultCrtFile); err == nil {\n\t\tl.TLSCrtFile = defaultCrtFile\n\t}\n\n\tif _, err := os.Stat(tlsKeyFile); err == nil {\n\t\tl.TLSKeyFile = tlsKeyFile\n\t}\n\n\tif _, err := os.Stat(tlsCrtFile); err == nil {\n\t\tl.TLSCrtFile = tlsCrtFile\n\t}\n\n\tl.LocalClient, err = client.New(config, client.Options{})\n\n\tif err != nil {\n\t\tklog.Error(\"Failed to initialize client to update local status. error: \", err)\n\t\treturn nil, err\n\t}\n\n\tl.RemoteClient = l.LocalClient\n\tif remoteConfig != nil {\n\t\tl.RemoteClient, err = client.New(remoteConfig, client.Options{})\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to initialize client to update remote status. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif createService {\n\t\tnamespace, err := getOperatorNamespace()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Create the webhook listener service only when the subscription controller runs in hub mode.\n\t\terr = createWebhookListnerService(l.LocalClient, namespace)\n\n\t\tif err != nil {\n\t\t\tklog.Error(\"Failed to create a service for Git webhook listener. error: \", err)\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn l, err\n}", "func APIProjectWebhookCreateHandler(er *Errorly) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := er.Store.Get(r, sessionName)\n\t\tdefer er.SaveSession(session, r, rw)\n\n\t\tvars := mux.Vars(r)\n\n\t\t// Authenticate the user\n\t\tauth, user := er.AuthenticateSession(session)\n\t\tif !auth {\n\t\t\tpassResponse(rw, \"You must be logged in to do this\", false, http.StatusForbidden)\n\n\t\t\treturn\n\t\t}\n\n\t\tproject, viewable, elevated, ok := verifyProjectVisibility(er, rw, vars, user, auth, true)\n\t\tif !ok {\n\t\t\t// If ok is False, an error has already been provided to the ResponseWriter so we should just return\n\t\t\treturn\n\t\t}\n\n\t\tif !viewable {\n\t\t\t// No permission to view project. We will treat like the project\n\t\t\t// does not exist.\n\t\t\tpassResponse(rw, \"Could not find this project\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tif !elevated {\n\t\t\t// No permission to execute on project. We will simply tell them\n\t\t\t// they cannot do this.\n\t\t\tpassResponse(rw, \"Guests to a project cannot do this\", false, http.StatusForbidden)\n\n\t\t\treturn\n\t\t}\n\n\t\twebhookURL, err := url.Parse(r.FormValue(\"url\"))\n\t\tif err != nil {\n\t\t\tpassResponse(rw, \"Webhook url is not valid\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\twebhookSecret := r.FormValue(\"secret\")\n\n\t\tuseJSON, err := strconv.ParseBool(r.FormValue(\"use_json\"))\n\t\tif err != nil {\n\t\t\tpassResponse(rw, \"Passed use_json value is not valid\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\twebhookDiscord, err := strconv.ParseBool(r.FormValue(\"webhook_discord\"))\n\t\tif err != nil {\n\t\t\tpassResponse(rw, \"Passed webhook_discord value is not valid\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tvar webhookType structs.WebhookType\n\t\tif webhookDiscord {\n\t\t\twebhookType = structs.RegularPayload\n\t\t} else {\n\t\t\twebhookType = structs.DiscordWebhook\n\t\t}\n\n\t\twebhook := &structs.Webhook{\n\t\t\tID: er.IDGen.GenerateID(),\n\t\t\tProjectID: project.ID,\n\n\t\t\tCreatedAt: time.Now().UTC(),\n\t\t\tCreatedByID: user.ID,\n\n\t\t\tSecret: webhookSecret,\n\t\t\tURL: webhookURL.String(),\n\t\t\tType: webhookType,\n\t\t\tJSONContent: useJSON,\n\t\t\tActive: true,\n\n\t\t\tFailures: 0,\n\t\t}\n\n\t\t_, err = er.Postgres.Model(webhook).\n\t\t\tInsert()\n\t\tif err != nil {\n\t\t\tpassResponse(rw, err.Error(), false, http.StatusInternalServerError)\n\t\t}\n\n\t\tpassResponse(rw, webhook, true, http.StatusOK)\n\t}\n}", "func New(mgr manager.Manager, args Args) (*Webhook, error) {\n\tlogger := log.Log.WithName(args.Name).WithValues(\"provider\", args.Provider)\n\n\t// Create handler\n\tbuilder := NewBuilder(mgr, logger)\n\n\tfor val, objs := range args.Validators {\n\t\tbuilder.WithValidator(val, objs...)\n\t}\n\n\tfor mut, objs := range args.Mutators {\n\t\tbuilder.WithMutator(mut, objs...)\n\t}\n\n\tbuilder.WithPredicates(args.Predicates...)\n\n\thandler, err := builder.Build()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create webhook\n\tlogger.Info(\"Creating webhook\")\n\n\treturn &Webhook{\n\t\tPath: args.Path,\n\t\tWebhook: &admission.Webhook{Handler: handler},\n\t}, nil\n}", "func TestCreateAndUpdateWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tcreationPayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(creationPayload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\tupdatePayload := []WebhookField{\n\t\tWebhookField{\n\t\t\tOperation: \"replace\",\n\t\t\tPath: \"/event_types\",\n\t\t\tValue: []interface{}{\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"name\": \"PAYMENT.SALE.REFUNDED\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = c.UpdateWebhook(createdWebhook.ID, updatePayload)\n\tif err != nil {\n\t\tt.Errorf(\"Couldn't update webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func (mr *ClientMockRecorder) CreateWebhook(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"CreateWebhook\", reflect.TypeOf((*Client)(nil).CreateWebhook), arg0, arg1)\n}", "func NewWebhook(timeout time.Duration) filters.Spec {\n\treturn WebhookWithOptions(WebhookOptions{Timeout: timeout, Tracer: opentracing.NoopTracer{}})\n}", "func New(\n\tctx context.Context,\n\tcontrollers []interface{},\n) (webhook *Webhook, err error) {\n\n\t// ServeMux.Handle panics on duplicate paths\n\tdefer func() {\n\t\tif r := recover(); r != nil {\n\t\t\terr = fmt.Errorf(\"error creating webhook %v\", r)\n\t\t}\n\t}()\n\n\topts := GetOptions(ctx)\n\tif opts == nil {\n\t\treturn nil, errors.New(\"context must have Options specified\")\n\t}\n\tlogger := logging.FromContext(ctx)\n\n\tif opts.StatsReporter == nil {\n\t\treporter, err := NewStatsReporter()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts.StatsReporter = reporter\n\t}\n\n\tdefaultTLSMinVersion := uint16(tls.VersionTLS13)\n\tif opts.TLSMinVersion == 0 {\n\t\topts.TLSMinVersion = TLSMinVersionFromEnv(defaultTLSMinVersion)\n\t} else if opts.TLSMinVersion != tls.VersionTLS12 && opts.TLSMinVersion != tls.VersionTLS13 {\n\t\treturn nil, fmt.Errorf(\"unsupported TLS version: %d\", opts.TLSMinVersion)\n\t}\n\n\tsyncCtx, cancel := context.WithCancel(context.Background())\n\n\twebhook = &Webhook{\n\t\tOptions: *opts,\n\t\tLogger: logger,\n\t\tsynced: cancel,\n\t}\n\n\tif opts.SecretName != \"\" {\n\t\t// Injection is too aggressive for this case because by simply linking this\n\t\t// library we force consumers to have secret access. If we require that one\n\t\t// of the admission controllers' informers *also* require the secret\n\t\t// informer, then we can fetch the shared informer factory here and produce\n\t\t// a new secret informer from it.\n\t\tsecretInformer := kubeinformerfactory.Get(ctx).Core().V1().Secrets()\n\n\t\twebhook.tlsConfig = &tls.Config{\n\t\t\tMinVersion: opts.TLSMinVersion,\n\n\t\t\t// If we return (nil, error) the client sees - 'tls: internal error\"\n\t\t\t// If we return (nil, nil) the client sees - 'tls: no certificates configured'\n\t\t\t//\n\t\t\t// We'll return (nil, nil) when we don't find a certificate\n\t\t\tGetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {\n\t\t\t\tsecret, err := secretInformer.Lister().Secrets(system.Namespace()).Get(opts.SecretName)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogger.Errorw(\"failed to fetch secret\", zap.Error(err))\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\twebOpts := GetOptions(ctx)\n\t\t\t\tsKey, sCert := getSecretDataKeyNamesOrDefault(webOpts.ServerPrivateKeyName, webOpts.ServerCertificateName)\n\t\t\t\tserverKey, ok := secret.Data[sKey]\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Warn(\"server key missing\")\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\tserverCert, ok := secret.Data[sCert]\n\t\t\t\tif !ok {\n\t\t\t\t\tlogger.Warn(\"server cert missing\")\n\t\t\t\t\treturn nil, nil\n\t\t\t\t}\n\t\t\t\tcert, err := tls.X509KeyPair(serverCert, serverKey)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\treturn &cert, nil\n\t\t\t},\n\t\t}\n\t}\n\n\twebhook.mux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n\t\thttp.Error(w, fmt.Sprint(\"no controller registered for: \", html.EscapeString(r.URL.Path)), http.StatusBadRequest)\n\t})\n\n\tfor _, controller := range controllers {\n\t\tswitch c := controller.(type) {\n\t\tcase AdmissionController:\n\t\t\thandler := admissionHandler(logger, opts.StatsReporter, c, syncCtx.Done())\n\t\t\twebhook.mux.Handle(c.Path(), handler)\n\n\t\tcase ConversionController:\n\t\t\thandler := conversionHandler(logger, opts.StatsReporter, c)\n\t\t\twebhook.mux.Handle(c.Path(), handler)\n\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown webhook controller type: %T\", controller)\n\t\t}\n\t}\n\n\treturn\n}", "func (a *Client) PostWebhooks(params *PostWebhooksParams, authInfo runtime.ClientAuthInfoWriter) (*PostWebhooksCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPostWebhooksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"PostWebhooks\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/webhooks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PostWebhooksReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*PostWebhooksCreated)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for PostWebhooks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func postWebhook(webhookUrl string, webhookType string, p []byte) {\n\n\tvar payloadName string\n\tswitch webhookType {\n\tcase \"slack\":\n\t\tpayloadName = \"payload\"\n\tcase \"discord\":\n\t\tpayloadName = \"payload_json\"\n\t}\n\tresp, _ := http.PostForm(\n\t\twebhookUrl,\n\t\turl.Values{payloadName: {string(p)}},\n\t)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tfmt.Println(string(body))\n}", "func AddWebhook(ctx context.Context, w *Webhook) error {\n\treturn db.Bun().RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {\n\t\t_, err := tx.NewInsert().Model(w).Exec(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, t := range w.Triggers {\n\t\t\tt.WebhookID = w.ID\n\t\t}\n\n\t\tif len(w.Triggers) != 0 {\n\t\t\t_, err = tx.NewInsert().Model(&w.Triggers).Exec(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func CreateHook(ctx *context.APIContext) {\n\t// swagger:operation POST /user/hooks user userCreateHook\n\t// ---\n\t// summary: Create a hook\n\t// consumes:\n\t// - application/json\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: body\n\t// in: body\n\t// required: true\n\t// schema:\n\t// \"$ref\": \"#/definitions/CreateHookOption\"\n\t// responses:\n\t// \"201\":\n\t// \"$ref\": \"#/responses/Hook\"\n\n\tutils.AddOwnerHook(\n\t\tctx,\n\t\tctx.Doer,\n\t\tweb.GetForm(ctx).(*api.CreateHookOption),\n\t)\n}", "func NewWebhook(client kubernetes.Interface, resources *WebhookResources, controllerNamespace string, noInitContainer bool) (*Webhook, error) {\n\tvar (\n\t\tscheme = runtime.NewScheme()\n\t\tcodecs = serializer.NewCodecFactory(scheme)\n\t)\n\n\treturn &Webhook{\n\t\tdeserializer: codecs.UniversalDeserializer(),\n\t\tcontrollerNamespace: controllerNamespace,\n\t\tresources: resources,\n\t\tnoInitContainer: noInitContainer,\n\t}, nil\n}", "func CreateHook(db DB, gameID string, eventType int, url string) (*Hook, error) {\n\thook := GetHookByDetails(db, gameID, eventType, url)\n\n\tif hook != nil {\n\t\treturn hook, nil\n\t}\n\n\tpublicID := uuid.NewV4().String()\n\thook = &Hook{\n\t\tGameID: gameID,\n\t\tPublicID: publicID,\n\t\tEventType: eventType,\n\t\tURL: url,\n\t}\n\terr := db.Insert(hook)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn hook, nil\n}", "func NewCreateWebhookCreated() *CreateWebhookCreated {\n\treturn &CreateWebhookCreated{}\n}", "func (c *Client) AddWebhook(w *Webhook) error {\n\treturn c.AddWebHookContext(context.TODO(), w)\n}", "func createWebhookService(\n\townerReference metav1.OwnerReference,\n\tserviceName string,\n\tnamespace string,\n) error {\n\n\tvar createService = false\n\t_, err := observer.GetService(namespace, serviceName)\n\tif err == nil {\n\t\t// service already present, no need to do anything\n\t\tcreateService = false\n\t} else {\n\t\tif errors.IsNotFound(err) {\n\t\t\tcreateService = true\n\t\t} else {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif !createService {\n\t\treturn nil\n\t}\n\n\t// create service resource that refers to KubeDirector pod\n\tkdName, _ := k8sutil.GetOperatorName()\n\tserviceLabels := map[string]string{\"name\": kdName}\n\tservice := &v1.Service{\n\t\tTypeMeta: metav1.TypeMeta{\n\t\t\tKind: \"Service\",\n\t\t\tAPIVersion: \"v1\",\n\t\t},\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: namespace,\n\t\t\tName: serviceName,\n\t\t\tLabels: map[string]string{\"webhook\": kdName},\n\t\t\tOwnerReferences: []metav1.OwnerReference{ownerReference},\n\t\t},\n\t\tSpec: v1.ServiceSpec{\n\t\t\tSelector: serviceLabels,\n\t\t\tPorts: []v1.ServicePort{\n\t\t\t\t{\n\t\t\t\t\tProtocol: \"TCP\",\n\t\t\t\t\tPort: 443,\n\t\t\t\t\tTargetPort: intstr.FromInt(validationPort),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\treturn shared.Create(context.TODO(), service)\n}", "func New() (*WebhookHandler, error) {\n\tconf, err := NewConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewWithConfig(conf)\n}", "func (m *HookManager) Create(r *Hook) error {\n\treturn m.post(m.uri(\"hooks\"), r)\n}", "func (client *WebhooksClient) createCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookCreateParameters WebhookCreateParameters, options *WebhooksClientBeginCreateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif webhookName == \"\" {\n\t\treturn nil, errors.New(\"parameter webhookName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{webhookName}\", url.PathEscape(webhookName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPut, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, webhookCreateParameters)\n}", "func SetupWebhooks(mgr ctrl.Manager) error {\n\t/*\n\t\tTotally undocumented and hard-to-find feature is that the builder automatically registers the URL path for the webhook.\n\t\tWhat's more, not even the tests in upstream controller-runtime reveal what this path is _actually_ going to look like.\n\t\tSo here's how the path is built (dots replaced with dash, lower-cased, single-form):\n\t\t /validate-<group>-<version>-<kind>\n\t\t /mutate-<group>-<version>-<kind>\n\t\tExample:\n\t\t /validate-clustercode-github-io-v1alpha1-blueprint\n\t\tThis path has to be given in the `//+kubebuilder:webhook:...` magic comment, see example:\n\t\t +kubebuilder:webhook:verbs=create;update;delete,path=/validate-clustercode-github-io-v1alpha1-blueprint,mutating=false,failurePolicy=fail,groups=clustercode.github.io,resources=blueprints,versions=v1alpha1,name=blueprints.clustercode.github.io,sideEffects=None,admissionReviewVersions=v1\n\t\tPay special attention to the plural forms and correct versions!\n\t*/\n\tfor _, setup := range []func(ctrl.Manager) error{\n\t\tblueprintwebhook.SetupWebhook,\n\t} {\n\t\tif err := setup(mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func NewWebhook() *prometheusruleWebhook {\n\tscheme := runtime.NewScheme()\n\treturn &prometheusruleWebhook{\n\t\ts: *scheme,\n\t}\n}", "func (r *ScalewayWebhook) ValidateCreate(ctx context.Context, obj runtime.Object) (field.ErrorList, error) {\n\treturn r.ScalewayManager.ValidateCreate(ctx, obj)\n}", "func New(config *Config) *Webhook {\n\treturn &Webhook{\n\t\tprovider: webhooks.Gogs,\n\t\tsecret: config.Secret,\n\t\teventFuncs: map[Event]webhooks.ProcessPayloadFunc{},\n\t}\n}", "func InsertWebhook(url string, events []models.EventType) (int, error) {\n\tlog.Traceln(\"Adding new webhook\")\n\n\teventsString := strings.Join(events, \",\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tstmt, err := tx.Prepare(\"INSERT INTO webhooks(url, events) values(?, ?)\")\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tdefer stmt.Close()\n\n\tinsertResult, err := stmt.Exec(url, eventsString)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn 0, err\n\t}\n\n\tnewID, err := insertResult.LastInsertId()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\treturn int(newID), err\n}", "func New(options ...Option) (*Webhook, error) {\n\thook := new(Webhook)\n\tfor _, opt := range options {\n\t\tif err := opt(hook); err != nil {\n\t\t\treturn nil, errors.New(\"Error applying Option\")\n\t\t}\n\t}\n\treturn hook, nil\n}", "func NewWebhook() *NamespaceWebhook {\n\tscheme := runtime.NewScheme()\n\terr := admissionv1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding admissionsv1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\terr = corev1.AddToScheme(scheme)\n\tif err != nil {\n\t\tlog.Error(err, \"Fail adding corev1 scheme to NamespaceWebhook\")\n\t\tos.Exit(1)\n\t}\n\n\treturn &NamespaceWebhook{\n\t\ts: *scheme,\n\t}\n}", "func NewWebhook(url string, file interface{}) *SetWebhookParameters {\n\treturn &SetWebhookParameters{\n\t\tURL: url,\n\t\tCertificate: file,\n\t}\n}", "func NewCreateWebhookForbidden() *CreateWebhookForbidden {\n\treturn &CreateWebhookForbidden{}\n}", "func (c *Client) WebhookPost(falcopayload types.FalcoPayload) {\n\terr := c.Post(falcopayload)\n\tif err != nil {\n\t\tc.Stats.Webhook.Add(Error, 1)\n\t\tc.PromStats.Outputs.With(map[string]string{\"destination\": \"webhook\", \"status\": Error}).Inc()\n\t} else {\n\t\tc.Stats.Webhook.Add(OK, 1)\n\t\tc.PromStats.Outputs.With(map[string]string{\"destination\": \"webhook\", \"status\": OK}).Inc()\n\t}\n\n\tc.Stats.Webhook.Add(Total, 1)\n}", "func New(clientSecret string) Webhook {\n\treturn &webhook{\n\t\tsecret: clientSecret,\n\t\tevents: make(map[Event]Handler),\n\t}\n}", "func NewWebhookAPI(webhookChan chan dockworker.Job) WebhookAPI {\n\treturn WebhookAPI{\n\t\twebhookChan: webhookChan,\n\t}\n}", "func NewPostWebhookCreated() *PostWebhookCreated {\n\treturn &PostWebhookCreated{}\n}", "func New(secret string, config WebhookConfig) *Webhook {\n\tif config.L == nil {\n\t\tconfig.L = log.New(ioutil.Discard, \"\", 0)\n\t}\n\tif config.PushCallback == nil {\n\t\tconfig.PushCallback = emptyCallback\n\t}\n\tif config.ReleaseCallback == nil {\n\t\tconfig.ReleaseCallback = emptyCallback\n\t}\n\treturn &Webhook{\n\t\tl: config.L,\n\t\tsecret: secret,\n\t\tpushCallback: config.PushCallback,\n\t\treleaseCallback: config.ReleaseCallback,\n\t}\n}", "func webhookCreateVersion(serviceID string, version *api.Version) error {\n\t// Find service info from DB.\n\tds := store.NewStore()\n\tdefer ds.Close()\n\tservice, err := ds.FindServiceByID(serviceID)\n\tif err != nil {\n\t\tmessage := fmt.Sprintf(\"Unable to find service %v\", version.ServiceID)\n\t\tlog.ErrorWithFields(message, log.Fields{\"user_id\": service.UserID, \"error\": err})\n\t\treturn fmt.Errorf(\"%s\", message)\n\t}\n\n\tif \"\" == version.URL {\n\t\tversion.URL = service.Repository.URL\n\t}\n\tversion.Operator = api.WebhookOperator\n\n\t// To create a version, we must first make sure repository is healthy.\n\tif service.Repository.Status != api.RepositoryHealthy {\n\t\tmessage := fmt.Sprintf(\"Repository of service %s is not healthy, current status %s\", service.Name, service.Repository.Status)\n\t\tlog.ErrorWithFields(message, log.Fields{\"user_id\": service.UserID})\n\t\treturn fmt.Errorf(\"%s\", message)\n\t}\n\n\t// Request looks good, now fill up initial version status.\n\tversion.CreateTime = time.Now()\n\tversion.Status = api.VersionPending\n\n\t// Create a new version in database. Note the version is NOT the final version:\n\t// there can be error when running tests or building docker image. The version\n\t// ID is only a record that a version build has occurred. If the version build\n\t// succeeds, it'll be added to the service and is considered as a final version;\n\t// otherwise, it is just a version recorded in database.\n\t_, err = ds.NewVersionDocument(version)\n\tif err != nil {\n\t\tmessage := \"Unable to create version document in database\"\n\t\tlog.ErrorWithFields(message, log.Fields{\"user_id\": service.UserID, \"error\": err})\n\t\treturn fmt.Errorf(\"%s\", message)\n\t}\n\n\t// Start building the version asynchronously, and make sure event is successfully\n\t// created before return.\n\terr = event.SendCreateVersionEvent(service, version)\n\tif err != nil {\n\t\tmessage := \"Unable to create build version job\"\n\t\tlog.ErrorWithFields(message, log.Fields{\"user_id\": service.UserID, \"service\": service, \"version\": version, \"error\": err})\n\t\treturn fmt.Errorf(\"%s\", message)\n\t}\n\n\treturn nil\n}", "func NewPostWebhook(branchesToIgnore string, committersToIgnore string, enabled bool, id int32, title string, url string) *PostWebhook {\n\tthis := PostWebhook{}\n\tthis.BranchesToIgnore = branchesToIgnore\n\tthis.CommittersToIgnore = committersToIgnore\n\tthis.Enabled = enabled\n\tthis.Id = id\n\tthis.Title = title\n\tthis.Url = url\n\treturn &this\n}", "func NewWebhookHandler(e *echo.Echo, u webhook.WebhooksUsecase) {\n\thandler := &WebhookHandler{\n\t\tWebhoolUsecase: u,\n\t}\n\te.POST(\"/webhoooks\", handler.CreateWebhooks)\n\te.DELETE(\"/webhoooks/:id\", handler.DeleteWebhooks)\n}", "func NewWebHook(\n\tsessionWorks repository.Session,\n\tconnectionsSupervisor Connections,\n\tauthorizer Authorizer,\n\twebhookURL string,\n\tmsgRepo repository.Message,\n\tclient httpInfra.Client,\n\tinterruptChan chan os.Signal,\n) *WebHook {\n\treturn &WebHook{\n\t\tsessionRepo: sessionWorks,\n\t\tconnectionsSupervisor: connectionsSupervisor,\n\t\tauth: authorizer,\n\t\twebhookURL: webhookURL,\n\t\tmsgRepo: msgRepo,\n\t\tclient: client,\n\t\tinterruptChan: interruptChan,\n\t}\n}", "func (c *Client) CreateParseWebhook(hostname string, url string, spamCheck bool, sendRaw bool) (*ParseWebhook, RequestError) {\n\tif hostname == \"\" {\n\t\treturn nil, RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: ErrHostnameRequired,\n\t\t}\n\t}\n\n\tif url == \"\" {\n\t\treturn nil, RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: ErrURLRequired,\n\t\t}\n\t}\n\n\trespBody, statusCode, err := c.Post(\"POST\", \"/user/webhooks/parse/settings\", ParseWebhook{\n\t\tHostname: hostname,\n\t\tURL: url,\n\t\tSpamCheck: spamCheck,\n\t\tSendRaw: sendRaw,\n\t})\n\tif err != nil {\n\t\treturn nil, RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: fmt.Errorf(\"failed creating inbound parse: %w\", err),\n\t\t}\n\t}\n\n\tif statusCode >= http.StatusMultipleChoices {\n\t\treturn nil, RequestError{\n\t\t\tStatusCode: statusCode,\n\t\t\tErr: fmt.Errorf(\"%w, status: %d, response: %s\", ErrFailedCreatingParseWebhook, statusCode, respBody),\n\t\t}\n\t}\n\n\treturn parseParseWebhook(respBody)\n}", "func New(req *http.Request) (hook *Hook, err error) {\n\thook = new(Hook)\n\tif !strings.EqualFold(req.Method, \"POST\") {\n\t\treturn nil, errors.New(\"unknown method\")\n\t}\n\n\tif hook.Signature = req.Header.Get(\"X-ChatWorkWebhookSignature\"); len(hook.Signature) == 0 {\n\t\treturn nil, errors.New(\"no signature\")\n\t}\n\n\thook.RawPayload, err = ioutil.ReadAll(req.Body)\n\treturn\n}", "func hookPerformWebPOST(url string, data interface{}) error {\n\t// Generate a buffer for us to store some JSON\n\tb := new(bytes.Buffer)\n\n\t// Take the data we have received and encode it in JSON to POST\n\tjson.NewEncoder(b).Encode(data)\n\n\t// It's always important to log.\n\tlog.WithFields(log.Fields{\n\t\t\"url\": url,\n\t\t\"data\": b,\n\t}).Debug(\"POSTing to webhook\")\n\n\t// POST up our data and then return if we got an error or not.\n\tres, err := http.Post(url, \"application/json; charset=utf-8\", b)\n\n\tlog.WithFields(log.Fields{\n\t\t\"url\": url,\n\t\t\"code\": res.StatusCode,\n\t\t\"status\": res.Status,\n\t}).Debug(\"Response received from webhook\")\n\n\treturn err\n}", "func NewWebHook(accessToken string) *WebHook {\n\tbaseAPI := \"https://oapi.dingtalk.com/robot/send\"\n\treturn &WebHook{accessToken: accessToken, apiUrl: baseAPI}\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func (bot *Bot) createServer() (err error) {\n\tserverOpts := &http.ServerOptions{\n\t\tAddress: bot.opts.Webhook.ListenAddress,\n\t}\n\n\tif bot.opts.Webhook.ListenCertificate != nil {\n\t\ttlsConfig := &tls.Config{}\n\t\ttlsConfig.Certificates = append(\n\t\t\ttlsConfig.Certificates,\n\t\t\t*bot.opts.Webhook.ListenCertificate,\n\t\t)\n\t\tserverOpts.Conn = &stdhttp.Server{\n\t\t\tTLSConfig: tlsConfig,\n\t\t}\n\t}\n\n\tbot.webhook, err = http.NewServer(serverOpts)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"createServer: %w\", err)\n\t}\n\n\tepToken := &http.Endpoint{\n\t\tMethod: http.RequestMethodPost,\n\t\tPath: \"/\" + bot.opts.Token,\n\t\tRequestType: http.RequestTypeJSON,\n\t\tResponseType: http.ResponseTypeNone,\n\t\tCall: bot.handleWebhook,\n\t}\n\n\terr = bot.webhook.RegisterEndpoint(epToken)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"createServer: %w\", err)\n\t}\n\n\treturn nil\n}", "func NewWebhooksJsonWebhook() *WebhooksJsonWebhook {\n\tthis := WebhooksJsonWebhook{}\n\treturn &this\n}", "func NewCreateWebhookBadRequest() *CreateWebhookBadRequest {\n\treturn &CreateWebhookBadRequest{}\n}", "func (bot *Bot) DeleteWebhook() (err error) {\n\t_, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\tres := &response{}\n\terr = json.Unmarshal(resBody, res)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\treturn nil\n}", "func AddWebhook() (bool, error) {\n\tfmt.Println()\n\tlog.Infof(\"WEBHOOK SETUP\")\n\tlog.Printf(\"For automatic webhook setup for push and PR git events you need administrator rights for your repository\")\n\n\tconst (\n\t\toptionYes = \"Yes\"\n\t\toptionNo = \"No\"\n\t)\n\n\tprompt := promptui.Select{\n\t\tLabel: \"Would you like us to register a webhook for you?\",\n\t\tItems: []string{optionYes, optionNo},\n\t\tTemplates: &promptui.SelectTemplates{\n\t\t\tLabel: fmt.Sprintf(\"%s {{.}} \", promptui.IconInitial),\n\t\t\tSelected: \"Auto register webhook: {{ . | green }}\",\n\t\t},\n\t}\n\n\t_, answer, err := prompt.Run()\n\tif err != nil {\n\t\treturn false, fmt.Errorf(\"scan user input: %s\", err)\n\t}\n\n\tvar registerWebhook bool\n\tif answer == optionYes {\n\t\tregisterWebhook = true\n\t}\n\n\treturn registerWebhook, nil\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func DeleteWebhook(id int) error {\n\tlog.Traceln(\"Deleting webhook\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(\"DELETE FROM webhooks WHERE id = ?\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowsDeleted, _ := result.RowsAffected(); rowsDeleted == 0 {\n\t\t_ = tx.Rollback()\n\t\treturn errors.New(fmt.Sprint(id) + \" not found\")\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (e *EventAPI) Create(eventType *EventType) error {\n\tconst errMsg = \"unable to create event type\"\n\n\tresponse, err := e.client.httpPOST(e.backOffConf.create(), e.eventBaseURL(), eventType, errMsg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer response.Body.Close()\n\n\tif response.StatusCode != http.StatusCreated {\n\t\tbuffer, err := io.ReadAll(response.Body)\n\t\tif err != nil {\n\t\t\treturn errors.Wrapf(err, \"%s: unable to read response body\", errMsg)\n\t\t}\n\t\treturn decodeResponseToError(buffer, errMsg)\n\t}\n\n\treturn nil\n}", "func CreateBotProxyWebHook(token string) (*viber.PostWebhooksViberOK, error) {\n\tclient := getBotProxyClient()\n\tparams := viber.NewPostWebhooksViberParams().WithBody(&botproxymodels.PostWebhooksViberParamsBody{})\n\tparams.Body.Token = &token\n\n\treturn client.Viber.PostWebhooksViber(params)\n}", "func testPostWebhook(p bytes.Buffer) {\n\tresp, _ := http.PostForm(\n\t\t\"\",\n\t\turl.Values{\"payload_json\": {p.String()}},\n\t)\n\n\tbody, _ := ioutil.ReadAll(resp.Body)\n\tdefer resp.Body.Close()\n\tfmt.Println(string(body))\n}", "func (t *TauAPI) DeleteWebhook(ID int64) error {\n\t_, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"DELETE\",\n\t\tPath: \"webhooks/webhooks/\" + strconv.FormatInt(ID, 10),\n\t\tNeedsAuth: true,\n\t})\n\treturn err\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.delete(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), nil)\n}", "func (ws *webhookSpec) CreateFilter(args []interface{}) (filters.Filter, error) {\n\tif l := len(args); l == 0 || l > 2 {\n\t\treturn nil, filters.ErrInvalidFilterParameters\n\t}\n\n\tvar ok bool\n\ts, ok := args[0].(string)\n\tif !ok {\n\t\treturn nil, filters.ErrInvalidFilterParameters\n\t}\n\n\tforwardResponseHeaderKeys := make([]string, 0)\n\n\tif len(args) > 1 {\n\t\t// Capture headers that should be forwarded from webhook responses.\n\t\theaderKeysOption, ok := args[1].(string)\n\t\tif !ok {\n\t\t\treturn nil, filters.ErrInvalidFilterParameters\n\t\t}\n\n\t\theaderKeys := strings.Split(headerKeysOption, \",\")\n\n\t\tfor _, header := range headerKeys {\n\t\t\tvalid := httpguts.ValidHeaderFieldName(header)\n\t\t\tif !valid {\n\t\t\t\treturn nil, fmt.Errorf(\"header %s is invalid\", header)\n\t\t\t}\n\t\t\tforwardResponseHeaderKeys = append(forwardResponseHeaderKeys, http.CanonicalHeaderKey(header))\n\t\t}\n\t}\n\n\tvar ac *authClient\n\tvar err error\n\tif ac, ok = webhookAuthClient[s]; !ok {\n\t\tac, err = newAuthClient(s, webhookSpanName, ws.options.Timeout, ws.options.MaxIdleConns, ws.options.Tracer)\n\t\tif err != nil {\n\t\t\treturn nil, filters.ErrInvalidFilterParameters\n\t\t}\n\t\twebhookAuthClient[s] = ac\n\t}\n\n\treturn &webhookFilter{authClient: ac, forwardResponseHeaderKeys: forwardResponseHeaderKeys}, nil\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.DeleteWebhookContext(context.TODO(), id)\n}", "func NewWebhookTarget(ctx context.Context, id string, args WebhookArgs, loggerOnce logger.LogOnce, transport *http.Transport) (*WebhookTarget, error) {\n\tctx, cancel := context.WithCancel(ctx)\n\n\ttarget := &WebhookTarget{\n\t\tid: event.TargetID{ID: id, Name: \"webhook\"},\n\t\targs: args,\n\t\tloggerOnce: loggerOnce,\n\t\ttransport: transport,\n\t\tcancel: cancel,\n\t\tcancelCh: ctx.Done(),\n\t}\n\n\treturn target, nil\n}", "func (b *Bot) Webhook() (*Webhook, error) {\n\tdata, err := b.Raw(\"getWebhookInfo\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tResult Webhook\n\t}\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, wrapError(err)\n\t}\n\treturn &resp.Result, nil\n}", "func (a *API) RegisterWebhook(webhook *Webhook) (string, error) {\n\tvar resp registerWebhookResponse\n\terr := a.Call(\"register_webhook\", webhook, &resp)\n\n\treturn resp.ID, err\n}", "func RegisterWebhook(w *Webhook) error {\n\tif webhooksRegistry == nil {\n\t\twebhooksRegistry = make(map[string]*Webhook)\n\t}\n\n\t_, ok := webhooksRegistry[w.UID()]\n\tif ok {\n\t\treturn fmt.Errorf(\"webhook %s already registred\", w.UID())\n\t}\n\twebhooksRegistry[w.UID()] = w\n\treturn nil\n}", "func (bot *Bot) startWebhook() (err error) {\n\terr = bot.createServer()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\tbot.err = make(chan error)\n\n\tgo func() {\n\t\tbot.err <- bot.webhook.Start()\n\t}()\n\n\terr = bot.DeleteWebhook()\n\tif err != nil {\n\t\tlog.Println(\"startWebhook:\", err.Error())\n\t}\n\n\terr = bot.setWebhook()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"startWebhook: %w\", err)\n\t}\n\n\treturn <-bot.err\n}", "func NewCreateGitWebhookUsingPOSTParams() *CreateGitWebhookUsingPOSTParams {\n\treturn &CreateGitWebhookUsingPOSTParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (b *Bot) DeleteWebhook(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"deleteWebhook\", request); err == nil {\n\t\tresult = response.(bool)\n\t}\n\treturn\n}", "func NewCreateWebhookUnauthorized() *CreateWebhookUnauthorized {\n\treturn &CreateWebhookUnauthorized{}\n}", "func Webhook(message string) {\n\tendpoint := os.Getenv(\"SLACK_WEBHOOK\")\n\n\tif len(endpoint) == 0 { // If the webhook endpoint is not set, ignore\n\t\treturn\n\t}\n\n\trequest := gorequest.New()\n\tresp, body, err := request.Post(os.Getenv(\"SLACK_WEBHOOK\")).\n\t\tSend(`{\"text\":\"` + message + `\"}`).\n\t\tEnd()\n\tif err != nil { // Die if there was an error\n\t\tlog.Panic(err)\n\t}\n\n\t// Leave these log statements here in case Slack starts being dumb\n\tlog.Println(resp)\n\tlog.Println(body)\n}", "func DeleteWebhook(ctx context.Context, id WebhookID) error {\n\t_, err := db.Bun().NewDelete().Model((*Webhook)(nil)).Where(\"id = ?\", id).Exec(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func webhookHandler(w http.ResponseWriter, r *http.Request) {\n\t// parse request body\n\tbody, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tfmt.Println(string(body))\n\t// decoder := json.NewDecoder(r.Body)\n\t// Get student public URL\n\t// run Webdriver IO test against the URL and get its result\n\t// Store result and SHA\n\t// publish status to Github\n\tfmt.Println(\"Hello\")\n}", "func NewWebhookSpec(spec *job.WebhookSpec) *WebhookSpec {\n\treturn &WebhookSpec{\n\t\tCreatedAt: spec.CreatedAt,\n\t\tUpdatedAt: spec.UpdatedAt,\n\t}\n}", "func NewCmdWebhooks() *cobra.Command {\n\tvar cmd = &cobra.Command{\n\t\tUse: \"webhooks\",\n\t\tShort: \"Webhooks Management\",\n\t}\n\tcmd.AddCommand(NewCmdWebhooksCreate())\n\tcmd.AddCommand(NewCmdWebhooksList())\n\tcmd.AddCommand(NewCmdWebhooksGet())\n\tcmd.AddCommand(NewCmdWebhooksUpdate())\n\tcmd.AddCommand(NewCmdWebhooksDelete())\n\treturn cmd\n}", "func PostWebhooks(diagnostic structs.DiagnosticSpec, status string, promotestatus string, isCron bool, result structs.ResultSpec) error {\n\t// No configured webhook destinations\n\tif diagnostic.WebhookURLs == \"\" {\n\t\treturn nil\n\t}\n\n\t// Assemble the webhook payload\n\tpayload := WebhookPayload{\n\t\tJob: diagnostic.JobSpace + \"/\" + diagnostic.Job,\n\t\tTarget: diagnostic.App + \"-\" + diagnostic.Space,\n\t\tStatus: status,\n\t\tIsPreview: diagnostic.IsPreview,\n\t\tIsCron: isCron,\n\t\tLogURL: os.Getenv(\"LOG_URL\") + \"/logs/\" + diagnostic.RunID,\n\t\tKibanaURL: os.Getenv(\"KIBANA_URL\") + \"/app/kibana#/doc/logs/logs/run/?id=\" + diagnostic.RunID,\n\t\tArtifactsURL: os.Getenv(\"ARTIFACTS_URL\") + \"/v1/artifacts/\" + diagnostic.RunID + \"/\",\n\t\tRerunURL: os.Getenv(\"RERUN_URL\") + \"?space=\" + diagnostic.Space + \"&app=\" + diagnostic.App + \"&action=\" + diagnostic.Action + \"&result=\" + diagnostic.Result + \"&releaseid=\" + diagnostic.ReleaseID + \"&buildid=\" + diagnostic.BuildID,\n\t\tCommitAuthor: diagnostic.CommitAuthor,\n\t\tStartTime: result.Payload.StartTime,\n\t\tStopTime: result.Payload.StopTime,\n\t\tRunDurationMs: result.Payload.BuildTimeMillis,\n\t\tPromotionResults: PromotionResults{},\n\t}\n\n\tif diagnostic.GithubVersion != \"\" {\n\t\tpayload.GithubVersion = diagnostic.GithubVersion\n\t}\n\n\tif status != \"success\" {\n\t\tpayload.PromotionResults.Message = \"No promotion triggered - tests not successful\"\n\t} else if diagnostic.PipelineName == \"manual\" {\n\t\tpayload.PromotionResults.Message = \"No promotion triggered - set to manual\"\n\t\tpayload.PromotionResults.Pipeline = diagnostic.PipelineName\n\t} else {\n\t\tpayload.PromotionResults.Message = \"Promotion was triggered with result \" + promotestatus\n\t\tpayload.PromotionResults.Status = promotestatus\n\t\tpayload.PromotionResults.From = diagnostic.TransitionFrom\n\t\tpayload.PromotionResults.To = diagnostic.TransitionTo\n\t\tpayload.PromotionResults.Pipeline = diagnostic.PipelineName\n\t}\n\n\t// Send message to each hook URL\n\tfor _, hookURL := range strings.Split(diagnostic.WebhookURLs, \",\") {\n\t\tpayloadBytes, err := json.Marshal(payload)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif !strings.HasPrefix(hookURL, \"http://\") && !strings.HasPrefix(hookURL, \"https://\") {\n\t\t\thookURL = \"https://\" + hookURL\n\t\t}\n\n\t\treq, err := http.NewRequest(\"POST\", hookURL, bytes.NewBuffer(payloadBytes))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Add(\"Content-type\", \"application/json\")\n\n\t\tclient := http.Client{}\n\t\t_, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\t// If we ever want to save the result and do something with it\n\t\t// defer resp.Body.Close()\n\t\t// bodybytes, err := ioutil.ReadAll(resp.Body)\n\t\t// if err != nil {\n\t\t// \tfmt.Println(err)\n\t\t// \treturn err\n\t\t// }\n\t\t// fmt.Println(string(bodybytes))\n\t\t// fmt.Println(resp.status)\n\t}\n\treturn nil\n}", "func (a *Client) PostV1ServicesTypeIncomingWebhook(params *PostV1ServicesTypeIncomingWebhookParams, authInfo runtime.ClientAuthInfoWriter) (*PostV1ServicesTypeIncomingWebhookCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPostV1ServicesTypeIncomingWebhookParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"PostV1ServicesTypeIncomingWebhook\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/v1/services/?type=incoming-webhook\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PostV1ServicesTypeIncomingWebhookReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn result.(*PostV1ServicesTypeIncomingWebhookCreated), nil\n\n}", "func NewWebhookEngine(mode string) WebhookEngine {\n\tgin.SetMode(mode)\n\treturn WebhookEngine{}\n}", "func CreateTrigger(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Received a POST against an ID. Working.\")\n\n\tvars := mux.Vars(r)\n\tid := vars[\"id\"]\n\n\t// We use the same error every time, as this makes it harder to try and hack from the outside with\n\t// brute force attempt to get the message. Timing attacks are still an issue however.\n\tfof := fmt.Sprintf(\"{\\\"error\\\":\\\"Invalid endpoint/token.\\\",\\\"details\\\":\\\"Could not find requested endpoint.\\\"}\")\n\n\tif !checkToken(id) {\n\t\tlog.Println(\"Invalid endpoint: \", id)\n\t\thttp.Error(w, fof, 401)\n\t\treturn\n\t}\n\n\tendpoint, err := FindEndpoint(id)\n\n\tif err != nil {\n\t\tlog.Println(\"Problem finding endpoint in database: \", err)\n\t\thttp.Error(w, fof, 401)\n\t\treturn\n\t}\n\n\t// Load the JSON.\n\tpayload, err := simplejson.NewFromReader(r.Body)\n\n\tif err != nil {\n\t\tlog.Println(\"Failed to parse request JSON: \")\n\t\thttp.Error(w, fmt.Sprintf(\"{\\\"error\\\":\\\"Request body invalid.\\\",\\\"details\\\":\\\"%v\\\"}\", err), 400)\n\t\treturn\n\t}\n\n\ttoken := payload.Get(\"token\").MustString()\n\tmessage := payload.Get(\"message\").MustString()\n\taction := payload.Get(\"action\").MustString()\n\n\tif !checkToken(token) {\n\t\tlog.Println(\"Invalid token: \", token)\n\t\thttp.Error(w, fof, 401)\n\t\treturn\n\t}\n\n\tif !validateRequest(token, endpoint) {\n\t\tlog.Println(\"Token was not valid against the endpoint: \", token)\n\t\thttp.Error(w, fof, 401)\n\t}\n\n\t// Now check against the JSON\n\tlog.Println(\"Valid alert: \", token, message, action)\n\n\tif token != endpoint.Token {\n\t\tlog.Println(\"Endpoint token did not match DB stored token: \", token, vars[\"token\"])\n\t\thttp.Error(w, fof, 404)\n\t\treturn\n\t}\n\n\tnotif, err := CreateNotification(endpoint, message, false)\n\n\tif err != nil {\n\t\tlog.Println(\"Failed to create notification: \", err)\n\t\thttp.Error(w, fmt.Sprintf(\"{\\\"error\\\":\\\"Creating the notification failed.\\\",\\\"details\\\":\\\"%v\\\"}\", err), 400)\n\t\treturn\n\t}\n\n\t// Identify the service we'll use to deliver the message\n\tif endpoint.DeviceType == \"IOS\" {\n\t\t// This should be a GO Func.\n\t\tgo func(endpoint *Endpoint, notif *Notification) {\n\t\t\tlog.Println(\"Sending Notification to Apple: \", notif.Id)\n\t\t\tSendIOSNotification(endpoint, notif)\n\t\t}(endpoint, notif)\n\t\t// } else if endpoint.DeviceType == \"ANDROID\" {\n\t\t// serviceId = \"Not implemented!\"\n\t\t// } else if endpoint.DeviceType == \"WINDOWS\" {\n\t\t// serviceId = \"Not implemented!\"\n\t} else {\n\t\tlog.Println(\"Failed to find a device service match: '\", endpoint.DeviceType, \"'\")\n\t\thttp.Error(w, \"{\\\"error\\\":\\\"Could not identify device type.\\\",\\\"details\\\":\\\"Device type did not match a configured type.\\\"}\", 400)\n\t\treturn\n\t}\n\n\t// 201 and return the notifcation ID so it can be queried later\n\tw.WriteHeader(http.StatusCreated)\n\tfmt.Fprintf(w, \"{ \\\"status\\\":\\\"%v\\\" \\\"id\\\": \\\"%v.\\\" }\", notif.Status, notif.Id)\n}", "func GetWebhook(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WebhookState, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tvar resource Webhook\n\terr := ctx.ReadResource(\"datadog:index/webhook:Webhook\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}" ]
[ "0.8481151", "0.833772", "0.827526", "0.81374407", "0.8028327", "0.7994685", "0.7972451", "0.7958692", "0.7945194", "0.7892641", "0.7741412", "0.768944", "0.7640314", "0.7614412", "0.755055", "0.7351725", "0.732087", "0.71639544", "0.70969343", "0.6960401", "0.68619627", "0.68399346", "0.6833097", "0.6821098", "0.67750347", "0.677449", "0.6747554", "0.66998935", "0.6679423", "0.66296345", "0.66257113", "0.6599909", "0.65991455", "0.6569958", "0.6515024", "0.65129834", "0.6504751", "0.64485884", "0.644265", "0.64254767", "0.6415951", "0.64016134", "0.63494176", "0.63042843", "0.6212217", "0.6208112", "0.61987317", "0.618623", "0.6168078", "0.6166393", "0.6130979", "0.61203575", "0.6115684", "0.6112645", "0.6092343", "0.6082058", "0.60724247", "0.6070418", "0.60673714", "0.60504013", "0.603602", "0.60074407", "0.59982365", "0.59922224", "0.59777826", "0.59744143", "0.5957679", "0.5954478", "0.59298235", "0.5915735", "0.5907471", "0.5881821", "0.5862377", "0.5851899", "0.5848503", "0.58428776", "0.584168", "0.5832741", "0.5822599", "0.576577", "0.5744146", "0.5707281", "0.5693072", "0.5684186", "0.56747717", "0.5672342", "0.56688726", "0.56688106", "0.56656706", "0.5664735", "0.5664027", "0.5648097", "0.56242496", "0.5623663", "0.5605699", "0.5597481", "0.55969316", "0.5584554", "0.55813056", "0.5569788" ]
0.8336215
2
DeleteWebhook Deletes a webhook, by ID. / Deletes a webhook, by ID. Specify the webhook ID in the webhookID parameter in the URI.
func (s *WebhooksService) DeleteWebhook(webhookID string) (*resty.Response, error) { path := "/webhooks/{webhookId}" path = strings.Replace(path, "{"+"webhookId"+"}", fmt.Sprintf("%v", webhookID), -1) response, err := s.client.R(). SetError(&Error{}). Delete(path) if err != nil { return nil, err } return response, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.delete(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), nil)\n}", "func DeleteWebhook(id int) error {\n\tlog.Traceln(\"Deleting webhook\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(\"DELETE FROM webhooks WHERE id = ?\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowsDeleted, _ := result.RowsAffected(); rowsDeleted == 0 {\n\t\t_ = tx.Rollback()\n\t\treturn errors.New(fmt.Sprint(id) + \" not found\")\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *TauAPI) DeleteWebhook(ID int64) error {\n\t_, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"DELETE\",\n\t\tPath: \"webhooks/webhooks/\" + strconv.FormatInt(ID, 10),\n\t\tNeedsAuth: true,\n\t})\n\treturn err\n}", "func DeleteWebhook(ctx context.Context, id WebhookID) error {\n\t_, err := db.Bun().NewDelete().Model((*Webhook)(nil)).Where(\"id = ?\", id).Exec(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.DeleteWebhookContext(context.TODO(), id)\n}", "func (c *EcomClient) DeleteWebhook(ctx context.Context, webhookID string) error {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 404 {\n\t\treturn ErrWebhookNotFound\n\t}\n\n\treturn nil\n}", "func (c *Client) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) error {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.sendRequest(req, nil)\n}", "func (z *Client) DeleteWebhook(ctx context.Context, webhookID string) error {\n\terr := z.delete(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *ApiService) DeleteWebhook(ServiceSid string, Sid string) error {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks/{Sid}\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\tpath = strings.Replace(path, \"{\"+\"Sid\"+\"}\", Sid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Delete(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func (c *MockWebhookClient) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) (err error) {\n\treturn c.MockDeleteWebhook(ctx, repo, id)\n}", "func (bot *Bot) DeleteWebhook() (err error) {\n\t_, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\tres := &response{}\n\terr = json.Unmarshal(resBody, res)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\treturn nil\n}", "func (w *WebhookServiceOp) Delete(webhookID int64, options interface{}) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhookID)\n\tresource := new(Webhook)\n\terr := w.client.Delete(path, options, &resource)\n\treturn resource, err\n}", "func (b *Bot) DeleteWebhook(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"deleteWebhook\", request); err == nil {\n\t\tresult = response.(bool)\n\t}\n\treturn\n}", "func (wh *Webhook) Delete(webhookId string, accountId string, queryParams map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\turl := fmt.Sprintf(\"/%s%s/%s%s/%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK, url.PathEscape(webhookId))\n\treturn wh.Request.Delete(url, queryParams, extraHeaders)\n}", "func (s *WebhookServiceOp) Delete(ctx context.Context, ID int) error {\n\treturn s.client.Delete(ctx, fmt.Sprintf(\"%s/%d.json\", webhooksBasePath, ID))\n}", "func (w Webhook) Delete(ctx context.Context, id postmand.ID) error {\n\tquery := `\n\t\tDELETE FROM webhooks WHERE id = $1\n\t`\n\t_, err := w.db.ExecContext(ctx, query, id)\n\treturn err\n}", "func (client *Client) DeleteWebHook() *VoidResponse {\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointDeleteWebHook, client.accessToken)\n\trequest := gorequest.New().Get(endpoint).Set(UserAgentHeader, UserAgent+\"/\"+Version)\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}", "func (c *Client) DeleteWebhookContext(ctx context.Context, id int) error {\n\treq := &api.WebhooksDeleteRequest{ID: id}\n\tresp := &api.WebhooksDeleteResponse{}\n\treturn c.postContext(ctx, \"webhooks/delete\", req, resp)\n}", "func (g *V3) DeleteWebhook(repo string, webhookURL string) error {\n\thook, err := g.GetWebhook(repo, webhookURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif resp, err := g.client.Projects.DeleteProjectHook(repo, hook.ID); err != nil {\n\t\tlog.Errorf(\"delete project hook %s for repo error: %v\", hook.ID, repo, err)\n\t\treturn convertGitlabError(err, resp)\n\t}\n\n\treturn nil\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithWebhookID(webhookID string) *DeleteV1WebhooksWebhookIDParams {\n\to.SetWebhookID(webhookID)\n\treturn o\n}", "func (o *DeleteV1WebhooksWebhookIDParams) SetWebhookID(webhookID string) {\n\to.WebhookID = webhookID\n}", "func (b *Bot) DeleteWebhook() bool {\n\turl := fmt.Sprintf(\"https://api.telegram.com/bot%s/deleteWebhook\", b.Token)\n\t_, err := http.Get(url)\n\tif err != nil {\n\t\treturn false\n\t}\n\treturn true\n}", "func APIProjectWebhookDeleteHandler(er *Errorly) http.HandlerFunc {\n\treturn func(rw http.ResponseWriter, r *http.Request) {\n\t\tsession, _ := er.Store.Get(r, sessionName)\n\t\tdefer er.SaveSession(session, r, rw)\n\n\t\tvars := mux.Vars(r)\n\n\t\twebhookID := vars[\"webhook_id\"]\n\n\t\t// Authenticate the user\n\t\tauth, user := er.AuthenticateSession(session)\n\t\tif !auth {\n\t\t\tpassResponse(rw, \"You must be logged in to do this\", false, http.StatusForbidden)\n\n\t\t\treturn\n\t\t}\n\n\t\tproject, viewable, elevated, ok := verifyProjectVisibility(er, rw, vars, user, auth, true)\n\t\tif !ok {\n\t\t\t// If ok is False, an error has already been provided to the ResponseWriter so we should just return\n\t\t\treturn\n\t\t}\n\n\t\tif !viewable {\n\t\t\t// No permission to view project. We will treat like the project\n\t\t\t// does not exist.\n\t\t\tpassResponse(rw, \"Could not find this project\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tif !elevated {\n\t\t\t// No permission to execute on project. We will simply tell them\n\t\t\t// they cannot do this.\n\t\t\tpassResponse(rw, \"Guests to a project cannot do this\", false, http.StatusForbidden)\n\n\t\t\treturn\n\t\t}\n\n\t\twebhook := &structs.Webhook{}\n\n\t\tres, err := er.Postgres.Model(webhook).\n\t\t\tWhere(\"id = ?\", webhookID).\n\t\t\tWhere(\"project_id = ?\", project.ID).\n\t\t\tDelete()\n\t\tif err != nil {\n\t\t\tif errors.Is(err, pg.ErrNoRows) {\n\t\t\t\tpassResponse(rw, \"Invalid webhook passed\", false, http.StatusBadRequest)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\t// Unexpected error\n\t\t\tpassResponse(rw, err.Error(), false, http.StatusInternalServerError)\n\n\t\t\treturn\n\t\t}\n\n\t\tif res.RowsAffected() == 0 {\n\t\t\tpassResponse(rw, \"Invalid webhook passed\", false, http.StatusBadRequest)\n\n\t\t\treturn\n\t\t}\n\n\t\tpassResponse(rw, \"OK\", true, http.StatusOK)\n\t}\n}", "func (s *WebhooksServiceOp) Delete(id int64, options ...interface{}) error {\n\t_, reqErr := s.client.DoRequest(http.MethodDelete, fmt.Sprintf(\"/v3/hooks/%d\", id), nil)\n\tif reqErr != nil {\n\t\treturn reqErr\n\t}\n\treturn nil\n}", "func (a *Client) DeleteWebhooksID(params *DeleteWebhooksIDParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteWebhooksIDNoContent, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewDeleteWebhooksIDParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"DeleteWebhooksID\",\n\t\tMethod: \"DELETE\",\n\t\tPathPattern: \"/webhooks/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &DeleteWebhooksIDReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*DeleteWebhooksIDNoContent)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for DeleteWebhooksID: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (v *Kounta) DeleteSaleWebHook(token string, company string, id int) error {\n\n\tfmt.Println(\"UpdateSaleWebHook\", token, company, id)\n\n\tu, err := url.ParseRequestURI(baseURL)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tu.Path = fmt.Sprintf(webHookURL+\"/\"+strconv.Itoa(id)+\".json\", company)\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tr, err := http.NewRequest(\"DELETE\", urlStr, nil) //, bytes.NewBuffer(b))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tr.Header.Add(\"Authorization\", \"Bearer \"+token)\n\tr.Header.Add(\"Content-Type\", \"application/json\")\n\tr.Header.Add(\"Content-Length\", \"0\") // strconv.Itoa(len(b)))\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif res.StatusCode >= 400 {\n\t\treturn fmt.Errorf(\"Failed init sale webhooks %s\", res.Status)\n\t}\n\n\treturn nil\n}", "func (t *TauAPI) DeleteWebhooks() (error error) {\n\twebhooks, err := t.GetWebhooks()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, w := range webhooks {\n\t\terr := t.DeleteWebhook(w.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithHTTPClient(client *http.Client) *DeleteV1WebhooksWebhookIDParams {\n\to.SetHTTPClient(client)\n\treturn o\n}", "func (a *ManagementApiService) DeleteNotificationWebhook(ctx _context.Context, applicationId int32, notificationWebhookId int32) apiDeleteNotificationWebhookRequest {\n\treturn apiDeleteNotificationWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t\tnotificationWebhookId: notificationWebhookId,\n\t}\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithTimeout(timeout time.Duration) *DeleteV1WebhooksWebhookIDParams {\n\to.SetTimeout(timeout)\n\treturn o\n}", "func (m *Client) DeleteWebhook(arg0 context.Context, arg1 string) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"DeleteWebhook\", arg0, arg1)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithContext(ctx context.Context) *DeleteV1WebhooksWebhookIDParams {\n\to.SetContext(ctx)\n\treturn o\n}", "func (a *API) UnregisterWebhook(id string) error {\n\treturn a.Call(\"unregister_webhook\", unregisterWebhookRequest{\n\t\tID: id,\n\t}, &emptyResponse{})\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func (w *Webhook) Delete() error {\n\treturn w.DeleteContext(context.TODO())\n}", "func DeleteHook(ctx *context.APIContext) {\n\t// swagger:operation DELETE /user/hooks/{id} user userDeleteHook\n\t// ---\n\t// summary: Delete a hook\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: id\n\t// in: path\n\t// description: id of the hook to delete\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// responses:\n\t// \"204\":\n\t// \"$ref\": \"#/responses/empty\"\n\n\tutils.DeleteOwnerHook(\n\t\tctx,\n\t\tctx.Doer,\n\t\tctx.ParamsInt64(\"id\"),\n\t)\n}", "func (u *UsersService) DeleteHook(userID, hookID string) (*simpleresty.Response, error) {\n\turlStr := u.client.http.RequestURL(\"/users/%s/hooks/%s\", userID, hookID)\n\tresponse, err := u.client.http.Delete(urlStr, nil, nil)\n\n\treturn response, err\n}", "func NewDeleteV1WebhooksWebhookIDParams() *DeleteV1WebhooksWebhookIDParams {\n\treturn &DeleteV1WebhooksWebhookIDParams{\n\t\ttimeout: cr.DefaultTimeout,\n\t}\n}", "func (g *GitHub) DeleteHook(service *api.Service) error {\n\twebhooktype := service.Repository.Webhook\n\tif webhooktype == \"\" {\n\t\treturn fmt.Errorf(\"no need webhook registry\")\n\t}\n\n\tif webhooktype == api.GITHUB {\n\t\turl := getHookURL(webhooktype, service.ServiceID)\n\t\tif url == \"\" {\n\t\t\tlog.Infof(\"url is empty\", log.Fields{\"user_id\": service.UserID})\n\t\t\treturn nil\n\t\t}\n\n\t\tds := store.NewStore()\n\t\tdefer ds.Close()\n\n\t\ttok, err := ds.FindtokenByUserID(service.UserID, api.GITHUB)\n\t\tif err != nil {\n\t\t\tlog.ErrorWithFields(\"find token failed\", log.Fields{\"user_id\": service.UserID, \"error\": err})\n\t\t\treturn err\n\t\t}\n\n\t\tts := oauth2.StaticTokenSource(\n\t\t\t&oauth2.Token{AccessToken: tok.Vsctoken.AccessToken},\n\t\t)\n\t\ttc := oauth2.NewClient(oauth2.NoContext, ts)\n\t\tclient := github.NewClient(tc)\n\n\t\towner, name := parseURL(service.Repository.URL)\n\t\thooks, _, err := client.Repositories.ListHooks(owner, name, nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tvar hook *github.Hook\n\t\thasFoundHook := false\n\t\tfor _, hook = range hooks {\n\t\t\thookurl, ok := hook.Config[\"url\"].(string)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif strings.HasPrefix(hookurl, url) {\n\t\t\t\thasFoundHook = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif hasFoundHook {\n\t\t\t_, err = client.Repositories.DeleteHook(owner, name, *hook.ID)\n\t\t\treturn err\n\t\t}\n\t\treturn nil\n\t}\n\tlog.WarnWithFields(\"not support vcs repository\", log.Fields{\"vcs repository\": webhooktype})\n\treturn fmt.Errorf(\"not support vcs repository in delete webhook\")\n}", "func (mr *ClientMockRecorder) DeleteWebhook(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"DeleteWebhook\", reflect.TypeOf((*Client)(nil).DeleteWebhook), arg0, arg1)\n}", "func DeleteBotProxyWebHook(id string) (*webhook.DeleteWebhooksWebhookIDOK, error) {\n\tclient := getBotProxyClient()\n\tparams := webhook.NewDeleteWebhooksWebhookIDParams()\n\tparams.WebhookID = id\n\n\treturn client.Webhook.DeleteWebhooksWebhookID(params)\n}", "func (b *Bot) RemoveWebhook(dropPending ...bool) error {\n\tdrop := false\n\tif len(dropPending) > 0 {\n\t\tdrop = dropPending[0]\n\t}\n\t_, err := b.Raw(\"deleteWebhook\", map[string]bool{\n\t\t\"drop_pending_updates\": drop,\n\t})\n\treturn err\n}", "func NewDeleteV1WebhooksWebhookIDParamsWithTimeout(timeout time.Duration) *DeleteV1WebhooksWebhookIDParams {\n\treturn &DeleteV1WebhooksWebhookIDParams{\n\t\ttimeout: timeout,\n\t}\n}", "func (_m *ISession) WebhookDelete(webhookID string, options ...discordgo.RequestOption) error {\n\t_va := make([]interface{}, len(options))\n\tfor _i := range options {\n\t\t_va[_i] = options[_i]\n\t}\n\tvar _ca []interface{}\n\t_ca = append(_ca, webhookID)\n\t_ca = append(_ca, _va...)\n\tret := _m.Called(_ca...)\n\n\tvar r0 error\n\tif rf, ok := ret.Get(0).(func(string, ...discordgo.RequestOption) error); ok {\n\t\tr0 = rf(webhookID, options...)\n\t} else {\n\t\tr0 = ret.Error(0)\n\t}\n\n\treturn r0\n}", "func NewDeleteV1WebhooksWebhookIDParamsWithHTTPClient(client *http.Client) *DeleteV1WebhooksWebhookIDParams {\n\treturn &DeleteV1WebhooksWebhookIDParams{\n\t\tHTTPClient: client,\n\t}\n}", "func (g *Gitlab) DeleteWebHook(cfg *api.SCMConfig, repoURL string, webHookUrl string) error {\n\tclient, err := newGitlabClient(cfg.Server, cfg.Username, cfg.Token)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\towner, name := parseURL(repoURL)\n\thooks, _, err := client.Projects.ListProjectHooks(owner+\"/\"+name, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, hook := range hooks {\n\t\tif strings.HasPrefix(hook.URL, webHookUrl) {\n\t\t\t_, err = client.Projects.DeleteProjectHook(owner+\"/\"+name, hook.ID)\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn nil\n}", "func DeleteTweet(w http.ResponseWriter, r *http.Request) {\n\tID := r.URL.Query().Get(\"id\")\n\tif len(ID) < 1 {\n\t\thttp.Error(w, \"Debe enviar el parametro ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\terr := bd.DeleteTweet(ID, IDUsuario)\n\tif err != nil {\n\t\thttp.Error(w, \"Error eliminando el tweet \"+err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-type\", \"application/json\")\n\tw.WriteHeader(http.StatusCreated)\n}", "func (m *HookManager) Delete(id string) error {\n\treturn m.delete(m.uri(\"hooks\", id))\n}", "func (s *WebhooksService) GetWebhook(webhookID string) (*Webhook, *resty.Response, error) {\n\n\tpath := \"/webhooks/{webhookId}\"\n\tpath = strings.Replace(path, \"{\"+\"webhookId\"+\"}\", fmt.Sprintf(\"%v\", webhookID), -1)\n\n\tresponse, err := s.client.R().\n\t\tSetResult(&Webhook{}).\n\t\tSetError(&Error{}).\n\t\tGet(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Webhook)\n\treturn result, response, err\n\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithDefaults() *DeleteV1WebhooksWebhookIDParams {\n\to.SetDefaults()\n\treturn o\n}", "func (z *Client) GetWebhook(ctx context.Context, webhookID string) (*Webhook, error) {\n\tvar result struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\n\tbody, err := z.get(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Webhook, nil\n}", "func (a *WebhooksApiService) TeamsUsernameHooksUidDelete(ctx context.Context, username string, uid string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Delete\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\t\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/teams/{username}/hooks/{uid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uid\"+\"}\", fmt.Sprintf(\"%v\", uid), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarHttpResponse, err\n\t}\n\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarHttpResponse, newErr\n\t}\n\n\treturn localVarHttpResponse, nil\n}", "func GetWebhook(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WebhookState, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tvar resource Webhook\n\terr := ctx.ReadResource(\"datadog:index/webhook:Webhook\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (c *EcomClient) GetWebhook(ctx context.Context, webhookID string) (*WebhookResponse, error) {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 400 {\n\t\treturn nil, ErrBadRequest\n\t}\n\tif res.StatusCode == 404 {\n\t\treturn nil, ErrWebhookNotFound\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t}\n\treturn &w, nil\n}", "func (api *API) DeletePayFwd(id string) (err error) {\n\tu, err := api.buildURL(\"/payments/\"+id, nil)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = deleteResponse(u)\n\treturn\n}", "func DeleteTagWebhooks(ctx context.Context, client kubernetes.Interface, tag string) error {\n\twebhooks, err := GetWebhooksWithTag(ctx, client, tag)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar result error\n\tfor _, wh := range webhooks {\n\t\tresult = multierror.Append(result, client.AdmissionregistrationV1().MutatingWebhookConfigurations().Delete(ctx, wh.Name, metav1.DeleteOptions{})).ErrorOrNil()\n\t}\n\treturn result\n}", "func (h *Handler) DeleteTweet(c echo.Context) (err error) {\n\ttweetID := c.Param(\"tweet\")\n\n\tif !bson.IsObjectIdHex(tweetID) {\n\t\treturn &echo.HTTPError{Code: http.StatusBadRequest, Message: \"Malformed tweet ID.\"}\n\t}\n\n\tdb := h.DB.Clone()\n\tdefer db.Close()\n\n\terr = db.DB(\"se_avengers\").C(\"tweets\").RemoveId(bson.ObjectIdHex(tweetID))\n\tif err != nil {\n\t\tif err == mgo.ErrNotFound {\n\t\t\treturn &echo.HTTPError{Code: http.StatusNotFound, Message: \"Tweet does not exist.\"}\n\t\t}\n\t\treturn\n\t}\n\n\treturn c.NoContent(http.StatusNoContent)\n}", "func Delete(c *golangsdk.ServiceClient, id string) (r DeleteResult) {\n\turl := resourceURL(c, id)\n\t//fmt.Printf(\"Delete listener url: %s.\\n\", url)\n\t_, r.Err = c.Delete(url, &golangsdk.RequestOpts{\n\t\tOkCodes: []int{204},\n\t})\n\treturn\n}", "func DeactivateIstioInjectionWebhook(ctx context.Context, client kubernetes.Interface) error {\n\twhs, err := GetWebhooksWithRevision(ctx, client, DefaultRevisionName)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif len(whs) == 0 {\n\t\t// no revision with default, no action required.\n\t\treturn nil\n\t}\n\tif len(whs) > 1 {\n\t\treturn fmt.Errorf(\"expected a single webhook for default revision\")\n\t}\n\twebhook := whs[0]\n\tfor i := range webhook.Webhooks {\n\t\twh := webhook.Webhooks[i]\n\t\t// this is an abomination, but if this isn't a per-revision webhook, we want to make it ineffectual\n\t\t// without deleting it. Add a nonsense match.\n\t\twh.NamespaceSelector = util.NeverMatch\n\t\twh.ObjectSelector = util.NeverMatch\n\t\twebhook.Webhooks[i] = wh\n\t}\n\tadmit := client.AdmissionregistrationV1().MutatingWebhookConfigurations()\n\t_, err = admit.Update(ctx, &webhook, metav1.UpdateOptions{})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (gc *GreetingController) DeleteGreeting(w http.ResponseWriter, r *http.Request) {\n\tid := pat.Param(r, \"id\")\n\tif !bson.IsObjectIdHex(id) {\n\t\tMainLogger.Println(\"Invalid id\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tidh := bson.ObjectIdHex(id)\n\terr := gc.Session.DB(\"starterdb\").C(\"greetings\").RemoveId(idh)\n\tif err != nil {\n\t\tMainLogger.Println(\"Unknown id\")\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n}", "func GetWebhook(ctx context.Context, webhookID int) (*Webhook, error) {\n\twebhook := Webhook{}\n\terr := db.Bun().NewSelect().\n\t\tModel(&webhook).\n\t\tRelation(\"Triggers\").\n\t\tWhere(\"id = ?\", webhookID).\n\t\tScan(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &webhook, nil\n}", "func (c *Client) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (bitbucket.Webhook, error) {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\t// The documentation says this is a paged API but it is not\n\tvar payload bitbucket.Webhook\n\tif err := c.sendRequest(req, &payload); err != nil {\n\t\treturn bitbucket.Webhook{}, fmt.Errorf(\"GetWebhook(%+v, %d): %w\", repo, id, err)\n\t}\n\n\treturn payload, nil\n}", "func Delete(c blogpb.BlogServiceClient, blogID string) {\n\tres, err := c.DeleteBlog(context.Background(), &blogpb.DeleteBlogRequest{BlogId: blogID})\n\tif err != nil {\n\t\tfmt.Println(\"Something happenned whle deleting\", err)\n\t}\n\tfmt.Println(\"Successfully deleted\", res)\n}", "func (client *WebhooksClient) deleteCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, options *WebhooksClientBeginDeleteOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif webhookName == \"\" {\n\t\treturn nil, errors.New(\"parameter webhookName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{webhookName}\", url.PathEscape(webhookName))\n\treq, err := runtime.NewRequest(ctx, http.MethodDelete, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treturn req, nil\n}", "func (a *ManagementApiService) GetWebhook(ctx _context.Context, webhookId int32) apiGetWebhookRequest {\n\treturn apiGetWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\twebhookId: webhookId,\n\t}\n}", "func WebAPIOfferDelete(w http.ResponseWriter, r *http.Request) {\n\tviewData := BaseViewData(w, r)\n\n\tresponse := webAPIOfferDeleteResponse{\n\t\tSuccessful: false,\n\t}\n\tif viewData.Session == nil {\n\t\tresponse.Error = \"Not Logged In\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\tif !viewData.ValidCsrf(r) {\n\t\tresponse.Error = \"Not Authorized\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\targs := URIArgs(r)\n\n\tif len(args) != 1 {\n\t\tresponse.Error = \"Invalid Request\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\tidStr := args[0]\n\tid, err := strconv.Atoi(idStr)\n\tif err != nil {\n\t\tresponse.Error = \"Invalid ID\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\toffer, err := models.GetOfferByID(Base.Db, id)\n\tif err != nil {\n\t\tresponse.Error = \"Not Found\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\tif offer.Seller.ID == viewData.Session.User.ID ||\n\t\toffer.Buyer.ID == viewData.Session.User.ID {\n\t\tif ok := offer.Delete(Base.Db); ok {\n\n\t\t\tif offer.Seller.ID == viewData.Session.User.ID {\n\t\t\t\toffer.Seller = viewData.Session.User\n\t\t\t\tlisting, err := models.GetListingByID(Base.Db, offer.Listing.ID)\n\t\t\t\tif err == nil && listing != nil {\n\t\t\t\t\toffer.Listing = *listing\n\t\t\t\t\tBase.WebsockChannel <- wsock.UserJSONNotification(&offer.Buyer,\n\t\t\t\t\t\t\"NOTIF_OFFER_REJECTED\", offer, true)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toffer.Buyer = viewData.Session.User\n\t\t\t\tlisting, err := models.GetListingByID(Base.Db, offer.Listing.ID)\n\t\t\t\tif err == nil && listing != nil {\n\t\t\t\t\toffer.Listing = *listing\n\t\t\t\t\tBase.WebsockChannel <- wsock.UserJSONNotification(&offer.Seller,\n\t\t\t\t\t\t\"NOTIF_OFFER_REVOKED\", offer, true)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tresponse.Successful = true\n\t\t\tRenderJSON(w, response)\n\t\t\treturn\n\t\t}\n\t\tresponse.Error = \"Unexpected Error\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\tresponse.Error = \"Not Authorized\"\n\tRenderJSON(w, response)\n}", "func Delete(c messagebird.Client, id string) error {\n\treturn c.Request(nil, http.MethodDelete, path+\"/\"+id, nil)\n}", "func DeleteTrigger(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"Received a DELETE. Working. \")\n}", "func (t *TauAPI) CreateWebhook(webhook Webhook) (ID int64, error error) {\n\tjsonPostMsg, _ := json.Marshal(webhook)\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"POST\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t\tPostMsg: jsonPostMsg,\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tif string(jsonData) == \"[\\\"Limit reached\\\"]\" {\n\t\treturn 0, fmt.Errorf(\"Limit of webhooks reached (5)\")\n\t}\n\tvar d struct {\n\t\tID int64 `json:\"id\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn 0, fmt.Errorf(\"CreateWebhook -> unmarshal jsonData %v\", err)\n\t}\n\treturn d.ID, nil\n}", "func (c *Client) DeleteFirewall(ctx context.Context, id int) error {\n\te, err := c.Firewalls.Endpoint()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treq := c.R(ctx)\n\n\te = fmt.Sprintf(\"%s/%d\", e, id)\n\t_, err = coupleAPIErrors(req.Delete(e))\n\treturn err\n}", "func (w *Webhook) DeleteContext(ctx context.Context) error {\n\treturn globalClient.DeleteWebhookContext(ctx, w.ID)\n}", "func (mh *MonkeyHandler) DeleteMonkey(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\n\tif err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid monkey ID\")\n\t\treturn\n\t}\n\n\tret, err := mh.MonkeyService.DeleteMonkey(id)\n\tif err != nil {\n\t\terrorRespond(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tcnt, err := ret.RowsAffected()\n\tif cnt == 0 {\n\t\terrorRespond(w, http.StatusInternalServerError, \"NOTHING TO DELETE: The Monkey with the specified ID does not exists!\")\n\t\treturn\n\t}\n\n\tjsonRespond(w, http.StatusOK, map[string]string{\"Result\": \"SUCESS: Monkey successfully deleted!\"})\n\n}", "func NewWebhook(db *sqlx.DB) *Webhook {\n\treturn &Webhook{db: db}\n}", "func (wd *Word) DeleteWord(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\n\tclaims, ok := ctx.Value(auth.Key).(auth.Claims)\n\tif !ok {\n\t\treturn errors.New(\"claims missing from context\")\n\t}\n\n\twordID := chi.URLParam(r, \"_id\")\n\n\tif err := word.DeleteWord(ctx, wd.DB, claims, wordID); err != nil {\n\t\tswitch err {\n\t\tcase apierror.ErrNotFound:\n\t\t\treturn web.NewRequestError(err, http.StatusNotFound)\n\t\tcase apierror.ErrInvalidID:\n\t\t\treturn web.NewRequestError(err, http.StatusBadRequest)\n\t\tcase apierror.ErrForbidden:\n\t\t\treturn web.NewRequestError(err, http.StatusForbidden)\n\t\tdefault:\n\t\t\treturn errors.Wrapf(err, \"deleting word %q\", wordID)\n\t\t}\n\t}\n\n\treturn web.Respond(ctx, w, nil, http.StatusNoContent)\n}", "func (hh *HealthCheckHandler) Delete(w http.ResponseWriter, r *http.Request) {\n\tuuid := utils.ExtractUUID(r.URL.String())\n\thh.db.Delete(uuid)\n}", "func DeleteAPI(apiID string) error {\n\tendpoint, err := utils.ConstructURL(publisherAPIEndpoint, apiID)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := creatHTTPDELETEAPIRequest(endpoint)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = client.Invoke(APIDeleteContext, req, nil, http.StatusOK)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func DeleteTweet(ID string, userID string) error {\n\tctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)\n\tdefer cancel()\n\n\tdb := MongoConnection.Database(\"gotwitor\")\n\tcollection := db.Collection(\"tweet\")\n\n\tobjID, _ := primitive.ObjectIDFromHex(ID)\n\n\tcondition := bson.M{\n\t\t\"_id\": objID,\n\t\t\"userid\": userID,\n\t}\n\t_, err := collection.DeleteOne(ctx, condition)\n\n\treturn err\n}", "func (dh *DogHandler) DeleteDog(w http.ResponseWriter, r *http.Request) {\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\n\tif err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid dog ID\")\n\t\treturn\n\t}\n\n\tret, err := dh.DogService.DeleteDog(id)\n\tif err != nil {\n\t\terrorRespond(w, http.StatusInternalServerError, err.Error())\n\t\treturn\n\t}\n\n\tcnt, err := ret.RowsAffected()\n\tif cnt == 0 {\n\t\terrorRespond(w, http.StatusInternalServerError, \"NOTHING TO DELETE: The Dog with the specified ID does not exists!\")\n\t\treturn\n\t}\n\n\tjsonRespond(w, http.StatusOK, map[string]string{\"Result\": \"SUCESS: Dog successfully deleted!\"})\n\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WriteToRequest(r runtime.ClientRequest, reg strfmt.Registry) error {\n\n\tif err := r.SetTimeout(o.timeout); err != nil {\n\t\treturn err\n\t}\n\tvar res []error\n\n\t// path param webhook_id\n\tif err := r.SetPathParam(\"webhook_id\", o.WebhookID); err != nil {\n\t\treturn err\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (w *Webman) ShutdownWebhook() {\n\tw.mw.RLock()\n\tdefer w.mw.RUnlock()\n\tif w.webhook != nil {\n\t\tw.webhook.server.Stop(w.timeout)\n\t\t<-w.webhook.server.StopChan()\n\t}\n}", "func (w *WebhookServiceOp) Get(webhookID int64, options interface{}) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhookID)\n\tresource := new(Webhook)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func deleteEndpoint(endpointId string) (string, error) {\n\tvar ret string\n\n\turi := fmt.Sprintf(\"%s/%s\", endpointURI, id)\n\turl, err := client.GetURL(uri)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\treq, err := client.BuildReq(nil, url, http.MethodDelete, true)\n\trawResp, err := client.HTTPClient().Do(req)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\tif _, err := client.ParseReq(rawResp); err != nil {\n\t\treturn ret, err\n\t}\n\n\t// Confirm the node was deleted.\n\tif rawResp.StatusCode != 204 {\n\t\treturn ret, errors.New(\"Endpoint was not able to be deleted\")\n\t}\n\tret = \"Endpoint deleted\\n\"\n\n\treturn ret, nil\n}", "func (c *Client) DeleteParseWebhook(hostname string) (bool, RequestError) {\n\tif hostname == \"\" {\n\t\treturn false, RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: ErrHostnameRequired,\n\t\t}\n\t}\n\n\tresponseBody, statusCode, err := c.Get(\"DELETE\", \"/user/webhooks/parse/settings/\"+hostname)\n\tif err != nil {\n\t\treturn false, RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: err,\n\t\t}\n\t}\n\n\tif statusCode >= http.StatusMultipleChoices && statusCode != http.StatusNotFound { // ignore not found\n\t\treturn false, RequestError{\n\t\t\tStatusCode: statusCode,\n\t\t\tErr: fmt.Errorf(\"%w, status: %d, response: %s\", ErrFailedDeletingParseWebhook, statusCode, responseBody),\n\t\t}\n\t}\n\n\treturn true, RequestError{StatusCode: http.StatusOK, Err: nil}\n}", "func (c *MockWebhookClient) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (result bitbucket.Webhook, err error) {\n\treturn c.MockGetWebhook(ctx, repo, id)\n}", "func deleteWebsite(w http.ResponseWriter, r *http.Request, database storage.Database) {\n\tif err := r.ParseForm(); err != nil {\n\t\tlog.Printf(\"unable to parse form: %v\", err)\n\t\thttp.Error(w, \"invalid form parameter\", http.StatusBadRequest)\n\t\treturn\n\t}\n\twebsiteID := r.FormValue(\"website_id\")\n\tif websiteID == \"\" {\n\t\tlog.Printf(\"website_id is empty\")\n\t\thttp.Error(w, \"website_id is required\", http.StatusBadRequest)\n\t\treturn\n\t}\n\tif err := database.Delete(websiteID); err != nil {\n\t\tlog.Printf(\"unable to delete a website with id: %s from database: %v\", websiteID, err)\n\t\thttp.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlog.Printf(\"success delete website with id: %s\", websiteID)\n\tw.WriteHeader(http.StatusOK)\n}", "func DeleteHero(w http.ResponseWriter, r *http.Request) {\n\t// swagger:operation DELETE /hero/{id} heroes DeleteHero\n\t//\n\t// Deletes a hero\n\t//\n\t// ---\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - in: path\n\t// name: id\n\t// description: id of hero\n\t// required: true\n\t// type: integer\n\t// responses:\n\t// '200':\n\t// description: Returns the deleted hero\n\t// schema:\n\t// \"$ref\": \"#/definitions/Hero\"\n\n\tw.Header().Add(\"Content-Type\", \"application/json\")\n\n\tparams := mux.Vars(r)\n\tid, err := strconv.Atoi(params[\"id\"])\n\n\tif err != nil {\n\t\thttp.Error(w, \"Invalid ID\", http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tif err = models.RemoveHero(id); err != nil {\n\t\thttp.Error(w, \"Failed to remove hero\", http.StatusNotFound)\n\t\treturn\n\t}\n\n\tw.WriteHeader(http.StatusOK)\n}", "func (o *DeleteBlueprintRequestUsingDELETE1Params) WithRequestID(requestID strfmt.UUID) *DeleteBlueprintRequestUsingDELETE1Params {\n\to.SetRequestID(requestID)\n\treturn o\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func deleteurl(w http.ResponseWriter, r *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\tparams := mux.Vars(r)\n\tinputOrderID := params[\"Id\"]\n\tvar url Myurl\n\tdb.Where(\"id = ? \", inputOrderID).Delete(&url)\n}", "func (o *ItemImportRequestOptions) SetWebhook(v string) {\n\to.Webhook = &v\n}", "func delete(resource string, id string) ([]byte, error) {\n\thttpParams := &HTTPParams{\n\t\tResource: resource + \"/\" + id,\n\t\tVerb: \"DELETE\",\n\t}\n\treturn processRequest(httpParams)\n}", "func (handler WebserviceHandler) DeleteFaq(res http.ResponseWriter, req *http.Request) {\n\thandler.Logger.Info(\"Received \" + req.Method + \" request at path: \" + req.URL.Path)\n\n\t// Setting headers for CORS\n\tres.Header().Set(\"Access-Control-Allow-Origin\", \"*\")\n\tres.Header().Set(\"Access-Control-Allow-Headers\", \"Authorization\")\n\tif req.Method == http.MethodOptions {\n\t\treturn\n\t}\n\n\t// Retrieving the ID from the url\n\tvar id string\n\tvar err error\n\n\t// Checking request, verifying if ID is in query params\n\thandler.Logger.Debug(\"Starting to check the ID\")\n\tid = req.URL.Query().Get(\"id\")\n\tok := checkID(handler, res, req)\n\tif !ok {\n\t\treturn\n\t}\n\thandler.Logger.Debug(\"Request correct, ID inserted as query params\")\n\n\thandler.Logger.Info(\"ID: \" + id)\n\n\t// Deleting the new Data\n\thandler.Logger.Debug(\"Starting to delete faq\")\n\terr = handler.KnowledgeBaseInteractor.DeleteFaq(id)\n\tif err != nil {\n\t\tres.WriteHeader(http.StatusInternalServerError)\n\t\treturn\n\t}\n\thandler.Logger.Debug(\"Faq deleted\")\n\n\t// Preparing response\n\tres.WriteHeader(200)\n\thandler.Logger.Info(\"Returning response\")\n\treturn\n}", "func Delete(w http.ResponseWriter, r *http.Request){\n\n\t//pegando a url atraves da requisiçãp (.Get = pegar )\n\tidDoProduto := r.URL.Query().Get(\"id\") // pegando o id da url\n\n\tmodels.DeletaProduto(idDoProduto)\n\thttp.Redirect(w, r, \"/\", 301)\n}", "func (c *EcomClient) UpdateWebhook(ctx context.Context, webhookID string, req *UpdateWebhookRequest) (*WebhookResponse, error) {\n\trequest, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"json marshal: %w\", err)\n\t}\n\n\tbody := strings.NewReader(string(request))\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodPatch, url, body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\tvar e badRequestResponse\n\t\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Status: %d, Code: %s, Message: %s\", e.Status, e.Code, e.Message)\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"json decode url %s\", url)\n\t}\n\treturn &w, nil\n}", "func NewWebhookHandler(e *echo.Echo, u webhook.WebhooksUsecase) {\n\thandler := &WebhookHandler{\n\t\tWebhoolUsecase: u,\n\t}\n\te.POST(\"/webhoooks\", handler.CreateWebhooks)\n\te.DELETE(\"/webhoooks/:id\", handler.DeleteWebhooks)\n}", "func ExecProjectWebhookDeleteMutation(client graphql.Client, id string) error {\n\tvariables := make(graphql.Variables)\n\tvariables[\"id\"] = id\n\tvar sb strings.Builder\n\tsb.WriteString(\"mutation GoProjectWebhookDeleteMutation($id: String!) {\\n\")\n\tsb.WriteString(\"\\twork {\\n\")\n\tsb.WriteString(\"\\t\\tdeleteProjectWebhook(_id: $id)\\n\")\n\tsb.WriteString(\"\\t}\\n\")\n\tsb.WriteString(\"}\\n\")\n\tvar res interface{}\n\tif err := client.Mutate(sb.String(), variables, &res); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func Delete(c *gophercloud.ServiceClient, idOrURL string) (r DeleteResult) {\n\tvar url string\n\tif strings.Contains(idOrURL, \"/\") {\n\t\turl = idOrURL\n\t} else {\n\t\turl = deleteURL(c, idOrURL)\n\t}\n\tresp, err := c.Delete(url, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}", "func deleteAPIPostHandler(w http.ResponseWriter, r *http.Request, params map[string]string) {\n\tuserName := sessionHandler.GetUserName(r)\n\tif userName != \"\" {\n\t\tid := params[\"id\"]\n\t\t// Delete post\n\t\tpostID, err := strconv.ParseInt(id, 10, 64)\n\t\tif err != nil || postID < 1 {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\terr = methods.DeletePost(postID)\n\t\tif err != nil {\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t\treturn\n\t\t}\n\t\tw.WriteHeader(http.StatusOK)\n\t\tw.Write([]byte(\"Post deleted!\"))\n\t\treturn\n\t}\n\thttp.Error(w, \"Not logged in!\", http.StatusInternalServerError)\n}", "func (e EventHandler) DeleteEventbyID(ctx context.Context, params api.DeleteEventbyIDParams) middleware.Responder {\n\t// validateErr := u.userService.Validate(params.HTTPRequest.Header.Get(\"X-API-Key\"), params.ID)\n\t// if validateErr != nil {\n\t// \terr := models.Error{\n\t// \t\tMessage: validateErr.Error(),\n\t// \t}\n\t// \treturn api.NewRegisterUserUnauthorized().WithPayload(&err)\n\t// }\n\tstatus, err := e.eventService.DeleteEventByID(params.ID)\n\tif err != nil {\n\t\tpostErr := fmt.Errorf(\"Deletion of the event failed: %w\", err)\n\t\tlogrus.Warnf(postErr.Error())\n\t\tErrstatus := models.Response{}\n\t\tErrstatus.Code = 500\n\t\tErrstatus.Status = \"Failed\"\n\t\tErrstatus.Message = postErr.Error()\n\t\treturn api.NewDeleteEventbyIDInternalServerError().WithPayload(&Errstatus)\n\t}\n\tmodelStatus := models.Response{}\n\tif status {\n\t\tlogrus.Infoln(\"The event has been deleted in the DB:\", status)\n\t\tmodelStatus.Code = 200\n\t\tmodelStatus.Status = \"Success\"\n\t\tmodelStatus.Message = \"The event has been deleted from the DB\"\n\t}\n\n\treturn api.NewDeleteEventbyIDOK().WithPayload(&modelStatus)\n}", "func (*server) DeleteBlog(ctx context.Context, req *blogpb.DeleteBlogRequest) (*blogpb.DeleteBlogResponse, error) {\n\tfmt.Println(\"Deleting blog\")\n\t// receive a requset\n\tblogID := req.GetBlogId()\n\t// convert ID to primitive object id\n\tbID, pErr := primitive.ObjectIDFromHex(blogID)\n\tif pErr != nil {\n\t\treturn nil, status.Errorf(codes.Internal, fmt.Sprintf(\"Cannot convert object ID: %v\\n\", pErr))\n\t}\n\t// Delete the blog in mongoDB\n\tfilter := bson.M{\n\t\t\"_id\": bID,\n\t}\n\tresult, dErr := collection.DeleteOne(context.Background(), filter)\n\tif dErr != nil {\n\t\treturn nil, status.Errorf(codes.Internal, fmt.Sprintf(\"Delete opperation failed %v\\n\", dErr))\n\t}\n\tif result.DeletedCount == 0 {\n\t\treturn nil, status.Errorf(codes.Internal, fmt.Sprintf(\"Blog was not deleted: %v\\n\", blogID))\n\t}\n\t// send back a response\n\treturn &blogpb.DeleteBlogResponse{\n\t\tBlogId: blogID,\n\t}, nil\n\n}" ]
[ "0.83634174", "0.8352434", "0.82925785", "0.821205", "0.8188866", "0.80112755", "0.7990058", "0.77990377", "0.7760329", "0.7618506", "0.75669944", "0.736306", "0.73021424", "0.718133", "0.70486265", "0.70045626", "0.69901586", "0.6765741", "0.67372346", "0.6629408", "0.661696", "0.65983564", "0.65850586", "0.65585005", "0.64995617", "0.64924645", "0.64022714", "0.6391118", "0.6337414", "0.62919724", "0.6240474", "0.6223483", "0.6215558", "0.61926377", "0.6112463", "0.6057701", "0.6044607", "0.5984791", "0.59384364", "0.59330976", "0.58866245", "0.5787287", "0.57276565", "0.5718647", "0.5685073", "0.5680274", "0.5669533", "0.56607616", "0.5613201", "0.55558294", "0.55269283", "0.54963005", "0.5490826", "0.54122955", "0.53732526", "0.53665555", "0.53413343", "0.5263494", "0.5245998", "0.52341336", "0.52265555", "0.52218837", "0.52199227", "0.52164507", "0.52075785", "0.51604384", "0.51424193", "0.5141974", "0.5127075", "0.5113661", "0.51039886", "0.5089727", "0.5080713", "0.50573146", "0.5046564", "0.5010354", "0.50044733", "0.5003289", "0.49955598", "0.49936008", "0.49927506", "0.499056", "0.4983842", "0.49788198", "0.49747032", "0.49735138", "0.49610606", "0.4960487", "0.49545124", "0.49506333", "0.49394774", "0.4932307", "0.49177375", "0.4916442", "0.49147806", "0.4911015", "0.49080938", "0.4902708", "0.48968664", "0.4875091" ]
0.815381
5
GetWebhook Shows details for a webhook, by ID. / Shows details for a webhook, by ID. Specify the webhook ID in the webhookID parameter in the URI.
func (s *WebhooksService) GetWebhook(webhookID string) (*Webhook, *resty.Response, error) { path := "/webhooks/{webhookId}" path = strings.Replace(path, "{"+"webhookId"+"}", fmt.Sprintf("%v", webhookID), -1) response, err := s.client.R(). SetResult(&Webhook{}). SetError(&Error{}). Get(path) if err != nil { return nil, nil, err } result := response.Result().(*Webhook) return result, response, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func GetWebhook(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WebhookState, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tvar resource Webhook\n\terr := ctx.ReadResource(\"datadog:index/webhook:Webhook\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (z *Client) GetWebhook(ctx context.Context, webhookID string) (*Webhook, error) {\n\tvar result struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\n\tbody, err := z.get(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Webhook, nil\n}", "func (c *EcomClient) GetWebhook(ctx context.Context, webhookID string) (*WebhookResponse, error) {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 400 {\n\t\treturn nil, ErrBadRequest\n\t}\n\tif res.StatusCode == 404 {\n\t\treturn nil, ErrWebhookNotFound\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t}\n\treturn &w, nil\n}", "func GetWebhook(ctx context.Context, webhookID int) (*Webhook, error) {\n\twebhook := Webhook{}\n\terr := db.Bun().NewSelect().\n\t\tModel(&webhook).\n\t\tRelation(\"Triggers\").\n\t\tWhere(\"id = ?\", webhookID).\n\t\tScan(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &webhook, nil\n}", "func (a *ManagementApiService) GetWebhook(ctx _context.Context, webhookId int32) apiGetWebhookRequest {\n\treturn apiGetWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\twebhookId: webhookId,\n\t}\n}", "func (w *WebhookServiceOp) Get(webhookID int64, options interface{}) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhookID)\n\tresource := new(Webhook)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func (c *Client) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (bitbucket.Webhook, error) {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\t// The documentation says this is a paged API but it is not\n\tvar payload bitbucket.Webhook\n\tif err := c.sendRequest(req, &payload); err != nil {\n\t\treturn bitbucket.Webhook{}, fmt.Errorf(\"GetWebhook(%+v, %d): %w\", repo, id, err)\n\t}\n\n\treturn payload, nil\n}", "func (c *MockWebhookClient) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (result bitbucket.Webhook, err error) {\n\treturn c.MockGetWebhook(ctx, repo, id)\n}", "func (s *WebhooksServiceOp) Get(id int64, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tbody, reqErr := s.client.DoRequest(http.MethodGet, fmt.Sprintf(\"/v3/hooks/%d\", id), nil)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\treturn webhookResponse.Data, nil\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func (w Webhook) Get(ctx context.Context, getOptions postmand.RepositoryGetOptions) (*postmand.Webhook, error) {\n\twebhook := postmand.Webhook{}\n\tquery, args := getQuery(\"webhooks\", getOptions)\n\terr := w.db.GetContext(ctx, &webhook, query, args...)\n\tif err == sql.ErrNoRows {\n\t\treturn &webhook, postmand.ErrWebhookNotFound\n\t}\n\treturn &webhook, err\n}", "func (a *WorkflowsApiService) WorkflowWorkflowIDWebhooksGet(ctx _context.Context, workflowID int32) ApiWorkflowWorkflowIDWebhooksGetRequest {\n\treturn ApiWorkflowWorkflowIDWebhooksGetRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tworkflowID: workflowID,\n\t}\n}", "func (g *V3) GetWebhook(repo string, webhookURL string) (*v3.ProjectHook, error) {\n\thooks, resp, err := g.client.Projects.ListProjectHooks(repo, nil)\n\tif err != nil {\n\t\treturn nil, convertGitlabError(err, resp)\n\t}\n\n\tfor _, hook := range hooks {\n\t\tif hook.URL == webhookURL {\n\t\t\treturn hook, nil\n\t\t}\n\t}\n\n\treturn nil, cerr.ErrorContentNotFound.Error(fmt.Sprintf(\"webhook url %s\", webhookURL))\n}", "func (b *Bot) Webhook() (*Webhook, error) {\n\tdata, err := b.Raw(\"getWebhookInfo\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tResult Webhook\n\t}\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, wrapError(err)\n\t}\n\treturn &resp.Result, nil\n}", "func GetHook(ctx *context.APIContext) {\n\t// swagger:operation GET /user/hooks/{id} user userGetHook\n\t// ---\n\t// summary: Get a hook\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: id\n\t// in: path\n\t// description: id of the hook to get\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Hook\"\n\n\thook, err := utils.GetOwnerHook(ctx, ctx.Doer.ID, ctx.ParamsInt64(\"id\"))\n\tif err != nil {\n\t\treturn\n\t}\n\n\tapiHook, err := webhook_service.ToHook(ctx.Doer.HomeLink(), hook)\n\tif err != nil {\n\t\tctx.InternalServerError(err)\n\t\treturn\n\t}\n\tctx.JSON(http.StatusOK, apiHook)\n}", "func (a *ManagementApiService) GetWebhooks(ctx _context.Context) apiGetWebhooksRequest {\n\treturn apiGetWebhooksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (a *Client) GetWebhooks(params *GetWebhooksParams, authInfo runtime.ClientAuthInfoWriter) (*GetWebhooksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetWebhooksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetWebhooks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/webhooks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetWebhooksReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetWebhooksOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetWebhooks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o *ItemImportRequestOptions) GetWebhook() string {\n\tif o == nil || o.Webhook == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Webhook\n}", "func (a *ManagementApiService) GetNotificationWebhook(ctx _context.Context, applicationId int32, notificationWebhookId int32) apiGetNotificationWebhookRequest {\n\treturn apiGetNotificationWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t\tnotificationWebhookId: notificationWebhookId,\n\t}\n}", "func (a *Client) GetWebhooksID(params *GetWebhooksIDParams, authInfo runtime.ClientAuthInfoWriter) (*GetWebhooksIDOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetWebhooksIDParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetWebhooksID\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/webhooks/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetWebhooksIDReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetWebhooksIDOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetWebhooksID: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (o *DeleteV1WebhooksWebhookIDParams) SetWebhookID(webhookID string) {\n\to.WebhookID = webhookID\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.delete(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), nil)\n}", "func (t *TauAPI) DeleteWebhook(ID int64) error {\n\t_, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"DELETE\",\n\t\tPath: \"webhooks/webhooks/\" + strconv.FormatInt(ID, 10),\n\t\tNeedsAuth: true,\n\t})\n\treturn err\n}", "func (db *MongoDB) Get(key string) (Webhook, bool) {\n\twebhook := Webhook{}\n\tok := true\n\n\tif bson.IsObjectIdHex(key) == false {\n\t\treturn webhook, false\n\t}\n\n\tid := bson.ObjectIdHex(key)\n\n\terr := Session.DB(db.DatabaseName).C(db.WebhooksCollectionName).\n\t\tFind(bson.M{\"_id\": id}).One(&webhook)\n\tif err != nil {\n\t\tok = false\n\t}\n\n\treturn webhook, ok\n}", "func (m *Client) GetWebhook(arg0 context.Context, arg1 string) (*zendesk.Webhook, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"GetWebhook\", arg0, arg1)\n\tret0, _ := ret[0].(*zendesk.Webhook)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func DeleteWebhook(id int) error {\n\tlog.Traceln(\"Deleting webhook\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(\"DELETE FROM webhooks WHERE id = ?\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowsDeleted, _ := result.RowsAffected(); rowsDeleted == 0 {\n\t\t_ = tx.Rollback()\n\t\treturn errors.New(fmt.Sprint(id) + \" not found\")\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (s *WebhooksService) DeleteWebhook(webhookID string) (*resty.Response, error) {\n\n\tpath := \"/webhooks/{webhookId}\"\n\tpath = strings.Replace(path, \"{\"+\"webhookId\"+\"}\", fmt.Sprintf(\"%v\", webhookID), -1)\n\n\tresponse, err := s.client.R().\n\t\tSetError(&Error{}).\n\t\tDelete(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, err\n\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.DeleteWebhookContext(context.TODO(), id)\n}", "func (mr *ClientMockRecorder) GetWebhook(arg0, arg1 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"GetWebhook\", reflect.TypeOf((*Client)(nil).GetWebhook), arg0, arg1)\n}", "func GetWebhooks(ctx context.Context) (Webhooks, error) {\n\twebhooks := Webhooks{}\n\terr := db.Bun().NewSelect().\n\t\tModel(&webhooks).\n\t\tRelation(\"Triggers\").\n\t\tScan(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn webhooks, nil\n}", "func GetWebhooks() ([]models.Webhook, error) { //nolint\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := \"SELECT * FROM webhooks\"\n\n\trows, err := _db.Query(query)\n\tif err != nil {\n\t\treturn webhooks, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\t\tvar events string\n\t\tvar timestampString string\n\t\tvar lastUsedString *string\n\n\t\tif err := rows.Scan(&id, &url, &events, &timestampString, &lastUsedString); err != nil {\n\t\t\tlog.Error(\"There is a problem reading the database.\", err)\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\ttimestamp, err := time.Parse(time.RFC3339, timestampString)\n\t\tif err != nil {\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\tvar lastUsed *time.Time\n\t\tif lastUsedString != nil {\n\t\t\tlastUsedTime, _ := time.Parse(time.RFC3339, *lastUsedString)\n\t\t\tlastUsed = &lastUsedTime\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t\tEvents: strings.Split(events, \",\"),\n\t\t\tTimestamp: timestamp,\n\t\t\tLastUsed: lastUsed,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn webhooks, err\n\t}\n\n\treturn webhooks, nil\n}", "func (c *EcomClient) GetWebhooks(ctx context.Context) ([]*WebhookResponse, error) {\n\turi := c.endpoint + \"/webhooks\"\n\tres, err := c.request(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tvar container WebhookContainer\n\tif err := json.NewDecoder(res.Body).Decode(&container); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode failed: %w\", err)\n\t}\n\treturn container.Data, nil\n}", "func (list ListResponse) GetWebHooks() (*ListOfWebHooks, error) {\n\tif err := list.CanMakeRequest(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoint := fmt.Sprintf(webhooks_path, list.ID)\n\tresponse := new(ListOfWebHooks)\n\n\treturn response, list.api.Request(\"GET\", endpoint, nil, nil, response)\n}", "func NewWebhook(db *sqlx.DB) *Webhook {\n\treturn &Webhook{db: db}\n}", "func (t *TauAPI) GetWebhooks() (webhooks []Webhook, error error) {\n\tvar w = []Webhook{}\n\tvar d struct {\n\t\tCount int64 `json:\"count\"`\n\t\tWebhooks []Webhook `json:\"results\"`\n\t\tDetail string `json:\"detail\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t})\n\tif err != nil {\n\t\treturn w, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn w, err\n\t}\n\tif d.Detail == \"Invalid token.\" { //todo: really use http status code instead.\n\t\treturn w, fmt.Errorf(\"Tauros API: %s\", d.Detail)\n\t}\n\treturn d.Webhooks, nil\n}", "func DeleteWebhook(ctx context.Context, id WebhookID) error {\n\t_, err := db.Bun().NewDelete().Model((*Webhook)(nil)).Where(\"id = ?\", id).Exec(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (s *prometheusruleWebhook) GetURI() string {\n\treturn \"/\" + WebhookName\n}", "func NewGetWebhookNotFound() *GetWebhookNotFound {\n\treturn &GetWebhookNotFound{}\n}", "func (a *ManagementApiService) GetWebhookLogs(ctx _context.Context) apiGetWebhookLogsRequest {\n\treturn apiGetWebhookLogsRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (v *Kounta) GetWebHooks(token string, company string) (WebHooks, error) {\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tu, _ := url.ParseRequestURI(baseURL)\n\tu.Path = fmt.Sprintf(webHookURL+\".json\", company)\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tr, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Header = http.Header(make(map[string][]string))\n\tr.Header.Set(\"Accept\", \"application/json\")\n\tr.Header.Set(\"Authorization\", \"Bearer \"+token)\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawResBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode == 200 {\n\t\tvar resp WebHooks\n\n\t\tfmt.Println(string(rawResBody))\n\n\t\terr = json.Unmarshal(rawResBody, &resp)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp, nil\n\t}\n\treturn nil, fmt.Errorf(\"Failed to get Kounta Web Hooks %s\", res.Status)\n\n}", "func Webhooks(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlog.Infof(ctx, \"GET /webhooks\")\n\tvar webhooksObj model.WebhooksObj\n\tmakeWebhooksObj(&webhooksObj, r.URL.Query())\n\tlog.Infof(ctx, \"webhooksObj is: %+v\", webhooksObj)\n\n\tgaeMail := makeGaeMailForWebhooks(ctx, &webhooksObj)\n\tgaeMail.Send()\n}", "func (c *EcomClient) DeleteWebhook(ctx context.Context, webhookID string) error {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 404 {\n\t\treturn ErrWebhookNotFound\n\t}\n\n\treturn nil\n}", "func NewWebhook(ctx *pulumi.Context,\n\tname string, args *WebhookArgs, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Name == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Name'\")\n\t}\n\tif args.Url == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Url'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Webhook\n\terr := ctx.RegisterResource(\"datadog:index/webhook:Webhook\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (u *UsersService) GetHook(userID, hookID string, opts ...interface{}) (*UserHook, *simpleresty.Response, error) {\n\thook := new(UserHook)\n\turlStr, urlStrErr := u.client.http.RequestURLWithQueryParams(\n\t\tfmt.Sprintf(\"/users/%s/hooks/%s\", userID, hookID), opts...)\n\tif urlStrErr != nil {\n\t\treturn nil, nil, urlStrErr\n\t}\n\n\tresponse, err := u.client.http.Get(urlStr, hook, nil)\n\n\treturn hook, response, err\n}", "func (r *Webhooks) Gets(ro *WebhooksOptions) (interface{}, error) {\n\turlStr := r.c.requestUrl(\"/repositories/%s/%s/hooks/\", ro.Owner, ro.RepoSlug)\n\treturn r.c.executePaginated(\"GET\", urlStr, \"\", nil)\n}", "func (c *Client) WebhookInfo(id int) (*Webhook, error) {\n\treturn c.WebhookInfoContext(context.TODO(), id)\n}", "func (c *Client) Webhooks() (Webhooks, error) {\n\tvar res Webhooks\n\terr := c.get(c.baseURL+\"/webhooks\", &res)\n\n\treturn res, err\n}", "func (b *Bot) GetWebhookInfo() (result axon.O, err error) {\n\tvar response interface{}\n\tif response, err = b.doGet(\"getWebhookInfo\"); err == nil {\n\t\tresult = response.(map[string]interface{})\n\t}\n\treturn\n}", "func Get(ctx context.Context, id string, params *razorpay.GetParams) (*razorpay.Refund, error) {\n\treturn getDefaultClient().Get(ctx, id, params)\n}", "func (a *WebhooksApiService) TeamsUsernameHooksGet(ctx context.Context, username string) (PaginatedWebhookSubscriptions, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue PaginatedWebhookSubscriptions\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/teams/{username}/hooks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v PaginatedWebhookSubscriptions\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 403 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (bot *Bot) GetWebhookInfo() (webhookInfo *WebhookInfo, err error) {\n\t_, resBody, err := bot.client.Get(methodGetWebhookInfo, nil, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetWebhookInfo: %w\", err)\n\t}\n\n\twebhookInfo = &WebhookInfo{}\n\tres := &response{\n\t\tResult: webhookInfo,\n\t}\n\terr = res.unpack(resBody)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"GetWebhookInfo: %w\", err)\n\t}\n\n\treturn webhookInfo, nil\n}", "func (m *GetWebhook) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEvents(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModifiedAt(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateURL(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func NewGetWebhookOK() *GetWebhookOK {\n\treturn &GetWebhookOK{}\n}", "func (t *TauAPI) CreateWebhook(webhook Webhook) (ID int64, error error) {\n\tjsonPostMsg, _ := json.Marshal(webhook)\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"POST\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t\tPostMsg: jsonPostMsg,\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tif string(jsonData) == \"[\\\"Limit reached\\\"]\" {\n\t\treturn 0, fmt.Errorf(\"Limit of webhooks reached (5)\")\n\t}\n\tvar d struct {\n\t\tID int64 `json:\"id\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn 0, fmt.Errorf(\"CreateWebhook -> unmarshal jsonData %v\", err)\n\t}\n\treturn d.ID, nil\n}", "func (w *WebhookServiceOp) Delete(webhookID int64, options interface{}) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhookID)\n\tresource := new(Webhook)\n\terr := w.client.Delete(path, options, &resource)\n\treturn resource, err\n}", "func (c *Client) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) error {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.sendRequest(req, nil)\n}", "func GetWebhooks() []*Webhook {\n\twebhooks := make([]*Webhook, 0, len(webhooksRegistry))\n\tfor _, wh := range webhooksRegistry {\n\t\twebhooks = append(webhooks, wh)\n\t}\n\treturn webhooks\n}", "func (c *Client) Get(ctx context.Context, id string, params *razorpay.GetParams) (*razorpay.Refund, error) {\n\tif params == nil {\n\t\tparams = &razorpay.GetParams{}\n\t}\n\n\trefund := &razorpay.Refund{}\n\terr := c.Call(ctx, http.MethodGet, \"/refunds/\"+id, params, refund)\n\treturn refund, err\n}", "func TestCreateAndGetWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tpayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(payload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\t_, err = c.GetWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while getting webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func (r Resource) getGitHubWebhook(gitrepourl string, namespace string) (webhook, error) {\n\tlogging.Log.Debugf(\"Get GitHub webhook in namespace %s with repositoryURL %s.\", namespace, gitrepourl)\n\n\tsources, err := r.readGitHubWebhooks(namespace)\n\tif err != nil {\n\t\treturn webhook{}, err\n\t}\n\tfor _, source := range sources {\n\t\tif source.GitRepositoryURL == gitrepourl {\n\t\t\treturn source, nil\n\t\t}\n\t}\n\treturn webhook{}, fmt.Errorf(\"could not find webhook with GitRepositoryURL: %s\", gitrepourl)\n}", "func (a *WorkflowsApiService) WorkflowWorkflowIDWebhooksGetExecute(r ApiWorkflowWorkflowIDWebhooksGetRequest) (ListResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ListResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"WorkflowsApiService.WorkflowWorkflowIDWebhooksGet\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/workflow/{workflowID}/webhooks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"workflowID\"+\"}\", _neturl.PathEscape(parameterToString(r.workflowID, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.pageNumber != nil {\n\t\tlocalVarQueryParams.Add(\"pageNumber\", parameterToString(*r.pageNumber, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (a *ManagementApiService) GetNotificationWebhooks(ctx _context.Context, applicationId int32) apiGetNotificationWebhooksRequest {\n\treturn apiGetNotificationWebhooksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t}\n}", "func (c *ApiService) FetchWebhook(ServiceSid string, Sid string) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks/{Sid}\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\tpath = strings.Replace(path, \"{\"+\"Sid\"+\"}\", Sid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (z *Client) DeleteWebhook(ctx context.Context, webhookID string) error {\n\terr := z.delete(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (o *InvestmentsHistoricalUpdateWebhook) GetWebhookType() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.WebhookType\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func (c *MockWebhookClient) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) (err error) {\n\treturn c.MockDeleteWebhook(ctx, repo, id)\n}", "func (a *WebhooksApiService) TeamsUsernameHooksUidGet(ctx context.Context, username string, uid string) (WebhookSubscription, *http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Get\")\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue WebhookSubscription\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/teams/{username}/hooks/{uid}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"username\"+\"}\", fmt.Sprintf(\"%v\", username), -1)\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"uid\"+\"}\", fmt.Sprintf(\"%v\", uid), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHttpContentTypes := []string{\"application/json\"}\n\n\t// set Content-Type header\n\tlocalVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes)\n\tif localVarHttpContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHttpContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHttpHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts)\n\tif localVarHttpHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHttpHeaderAccept\n\t}\n\tif ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok {\n\t\t\tvar key string\n\t\t\tif auth.Prefix != \"\" {\n\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t} else {\n\t\t\t\tkey = auth.Key\n\t\t\t}\n\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t\n\t\t}\n\t}\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tlocalVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body)\n\tlocalVarHttpResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t}\n\n\tif localVarHttpResponse.StatusCode < 300 {\n\t\t// If we succeed, return the data, otherwise pass on to decode error.\n\t\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\tif err == nil { \n\t\t\treturn localVarReturnValue, localVarHttpResponse, err\n\t\t}\n\t}\n\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tnewErr := GenericSwaggerError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHttpResponse.Status,\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 200 {\n\t\t\tvar v WebhookSubscription\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\tif localVarHttpResponse.StatusCode == 404 {\n\t\t\tvar v ModelError\n\t\t\terr = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get(\"Content-Type\"));\n\t\t\t\tif err != nil {\n\t\t\t\t\tnewErr.error = err.Error()\n\t\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t\t\t}\n\t\t\t\tnewErr.model = v\n\t\t\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t\t}\n\t\t\n\t\treturn localVarReturnValue, localVarHttpResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHttpResponse, nil\n}", "func (c *EcomClient) UpdateWebhook(ctx context.Context, webhookID string, req *UpdateWebhookRequest) (*WebhookResponse, error) {\n\trequest, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"json marshal: %w\", err)\n\t}\n\n\tbody := strings.NewReader(string(request))\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodPatch, url, body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\tvar e badRequestResponse\n\t\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Status: %d, Code: %s, Message: %s\", e.Status, e.Code, e.Message)\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"json decode url %s\", url)\n\t}\n\treturn &w, nil\n}", "func (o *HttpPushWebhookTest) GetWebhookUrl() string {\n\tif o == nil || o.WebhookUrl == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.WebhookUrl\n}", "func NewWebhook() *prometheusruleWebhook {\n\tscheme := runtime.NewScheme()\n\treturn &prometheusruleWebhook{\n\t\ts: *scheme,\n\t}\n}", "func (c *Context) HandleWebhook(w http.ResponseWriter, r *http.Request) {\n\trequestID := l.GenerateContextID()\n\tlogger := &l.Logger{Context: map[string]interface{}{\n\t\t\"request_id\": requestID,\n\t}}\n\tlog := logger.StartLog()\n\tdefer log.Write()\n\n\tlog[\"request_url\"] = r.URL.String()\n\tlog[\"request_path\"] = r.URL.Path\n\tlog[\"request_header\"] = r.Header\n\n\twebhookID := GetRequestWebhookID(r)\n\tif len(webhookID) == 0 {\n\t\tlog[\"error\"] = \"couldn't identify webhook ID from URL\"\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog[\"webhook_id\"] = webhookID\n\twebhookSecret, err := c.WebhookSecret.SecretForWebhookID(webhookID)\n\tif err != nil {\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"fetching webhook secret\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpayload, err := github.ValidatePayload(r, []byte(webhookSecret.Secret))\n\tif err != nil {\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"validating webhook request\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tevent, err := github.ParseWebHook(github.WebHookType(r), payload)\n\tif err != nil {\n\t\tlog[\"request_body\"] = string(payload)\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"parsing webhook request\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch event := event.(type) {\n\tcase *github.PushEvent:\n\t\tlog[\"push_event\"] = event\n\tcase *github.PullRequestEvent:\n\t\tlog[\"pull_event\"] = event\n\n\t\t// Handle the event asynchronously.\n\t\tgo c.HandlePullEvent(webhookSecret, event, requestID, logger)\n\tdefault:\n\t\tlog[\"body\"] = string(payload)\n\t\tlog[\"other_event\"] = true\n\t}\n}", "func (s *WebhooksService) ListWebhooks(queryParams *ListWebhooksQueryParams) (*Webhooks, *resty.Response, error) {\n\n\tpath := \"/webhooks/\"\n\n\tqueryParamsString, _ := query.Values(queryParams)\n\n\tresponse, err := s.client.R().\n\t\tSetQueryString(queryParamsString.Encode()).\n\t\tSetResult(&Webhooks{}).\n\t\tSetError(&Error{}).\n\t\tGet(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Webhooks)\n\tif queryParams.Paginate {\n\t\titems := s.webhooksPagination(response.Header().Get(\"Link\"), 0, 0)\n\t\tfor _, webhook := range items.Items {\n\t\t\tresult.AddWebhook(webhook)\n\t\t}\n\t} else {\n\t\tif len(result.Items) < queryParams.Max {\n\t\t\titems := s.webhooksPagination(response.Header().Get(\"Link\"), len(result.Items), queryParams.Max)\n\t\t\tfor _, webhook := range items.Items {\n\t\t\t\tresult.AddWebhook(webhook)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn result, response, err\n\n}", "func NewWebhook(timeout time.Duration) filters.Spec {\n\treturn WebhookWithOptions(WebhookOptions{Timeout: timeout, Tracer: opentracing.NoopTracer{}})\n}", "func (c *ApiService) DeleteWebhook(ServiceSid string, Sid string) error {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks/{Sid}\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\tpath = strings.Replace(path, \"{\"+\"Sid\"+\"}\", Sid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Delete(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func getDiscordWebHookUrl(hookId string, hookToken string) string {\n\treturn strings.Join([]string{DiscordWebHookUrl, hookId, hookToken}, \"/\")\n}", "func (o *ItemImportRequestOptions) SetWebhook(v string) {\n\to.Webhook = &v\n}", "func (bot *Bot) DeleteWebhook() (err error) {\n\t_, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\tres := &response{}\n\terr = json.Unmarshal(resBody, res)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\treturn nil\n}", "func (wh *Webhook) Delete(webhookId string, accountId string, queryParams map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\turl := fmt.Sprintf(\"/%s%s/%s%s/%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK, url.PathEscape(webhookId))\n\treturn wh.Request.Delete(url, queryParams, extraHeaders)\n}", "func (o *ProjectWebhook) GetID() string {\n\treturn o.ID\n}", "func FindProjectWebhook(client graphql.Client, id string) (*ProjectWebhook, error) {\n\tvariables := make(graphql.Variables)\n\tvariables[\"id\"] = id\n\tvar sb strings.Builder\n\tsb.WriteString(\"query GoProjectWebhookQuery($id: ID) {\\n\")\n\tsb.WriteString(\"\\twork {\\n\")\n\tsb.WriteString(\"\\t\\tProjectWebhook(_id: $id) {\\n\")\n\tsb.WriteString(getProjectWebhookQueryFields())\n\tsb.WriteString(\"\\t\\t}\\n\")\n\tsb.WriteString(\"\\t}\\n\")\n\tsb.WriteString(\"}\\n\")\n\tvar res QueryOneProjectWebhookData\n\tif err := client.Query(sb.String(), variables, &res); err != nil {\n\t\treturn nil, err\n\t}\n\tif res.Data != nil {\n\t\treturn res.Data.Object, nil\n\t}\n\treturn nil, nil\n}", "func NewGetWebhookBadRequest() *GetWebhookBadRequest {\n\treturn &GetWebhookBadRequest{}\n}", "func New() (*WebhookHandler, error) {\n\tconf, err := NewConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn NewWithConfig(conf)\n}", "func NewWebhook(url string, filterFnString string, timeout uint64) (*Webhook, error) {\n\n\tvar err error\n\n\tif url == \"\" {\n\t\terr = errors.New(\"url parameter must be defined for webhook events.\")\n\t\treturn nil, err\n\t}\n\n\twh := &Webhook{\n\t\turl: url,\n\t}\n\tif filterFnString != \"\" {\n\t\twh.filter = NewJSEventFunction(filterFnString)\n\t}\n\n\tif timeout != 0 {\n\t\twh.timeout = time.Duration(timeout) * time.Second\n\t} else {\n\t\twh.timeout = time.Duration(kDefaultWebhookTimeout) * time.Second\n\t}\n\n\treturn wh, err\n}", "func (o *ProjectWebhook) GetRefID() string {\n\treturn o.RefID\n}", "func (a *API) UnregisterWebhook(id string) error {\n\treturn a.Call(\"unregister_webhook\", unregisterWebhookRequest{\n\t\tID: id,\n\t}, &emptyResponse{})\n}", "func GetWebVersion(request *api.Request, campaignID int64) *GetWebVersionRequest {\n\trequest.Add(\"campaign_id\", strconv.FormatInt(campaignID, 10))\n\n\treturn &GetWebVersionRequest{\n\t\trequest: request,\n\t}\n}", "func (r apiGetWebhookRequest) Execute() (Webhook, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue Webhook\n\t)\n\n\tlocalBasePath, err := r.apiService.client.cfg.ServerURLWithContext(r.ctx, \"ManagementApiService.GetWebhook\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/v1/webhooks/{webhookId}\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"webhookId\"+\"}\", _neturl.QueryEscape(parameterToString(r.webhookId, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\tif r.ctx != nil {\n\t\t// API Key Authentication\n\t\tif auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok {\n\t\t\tif auth, ok := auth[\"Authorization\"]; ok {\n\t\t\t\tvar key string\n\t\t\t\tif auth.Prefix != \"\" {\n\t\t\t\t\tkey = auth.Prefix + \" \" + auth.Key\n\t\t\t\t} else {\n\t\t\t\t\tkey = auth.Key\n\t\t\t\t}\n\t\t\t\tlocalVarHeaderParams[\"Authorization\"] = key\n\t\t\t}\n\t\t}\n\t}\n\treq, err := r.apiService.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := r.apiService.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\tif localVarHTTPResponse.StatusCode == 200 {\n\t\t\tvar v Webhook\n\t\t\terr = r.apiService.client.decode(&v, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\t\t\tif err != nil {\n\t\t\t\tnewErr.error = err.Error()\n\t\t\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t\t\t}\n\t\t\tnewErr.model = v\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = r.apiService.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithWebhookID(webhookID string) *DeleteV1WebhooksWebhookIDParams {\n\to.SetWebhookID(webhookID)\n\treturn o\n}", "func (c *ApiService) CreateWebhook(ServiceSid string, params *CreateWebhookParams) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.FriendlyName != nil {\n\t\tdata.Set(\"FriendlyName\", *params.FriendlyName)\n\t}\n\tif params != nil && params.EventTypes != nil {\n\t\tfor _, item := range *params.EventTypes {\n\t\t\tdata.Add(\"EventTypes\", item)\n\t\t}\n\t}\n\tif params != nil && params.WebhookUrl != nil {\n\t\tdata.Set(\"WebhookUrl\", *params.WebhookUrl)\n\t}\n\tif params != nil && params.Status != nil {\n\t\tdata.Set(\"Status\", *params.Status)\n\t}\n\tif params != nil && params.Version != nil {\n\t\tdata.Set(\"Version\", *params.Version)\n\t}\n\n\tresp, err := c.requestHandler.Post(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (o *PaymentStatusUpdateWebhook) GetWebhookType() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.WebhookType\n}", "func (wh *Webhook) Fetch(webhookId string, accountId string, queryParams map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\turl := fmt.Sprintf(\"/%s%s/%s%s/%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK, url.PathEscape(webhookId))\n\treturn wh.Request.Get(url, queryParams, extraHeaders)\n}", "func Webhook(message string) {\n\tendpoint := os.Getenv(\"SLACK_WEBHOOK\")\n\n\tif len(endpoint) == 0 { // If the webhook endpoint is not set, ignore\n\t\treturn\n\t}\n\n\trequest := gorequest.New()\n\tresp, body, err := request.Post(os.Getenv(\"SLACK_WEBHOOK\")).\n\t\tSend(`{\"text\":\"` + message + `\"}`).\n\t\tEnd()\n\tif err != nil { // Die if there was an error\n\t\tlog.Panic(err)\n\t}\n\n\t// Leave these log statements here in case Slack starts being dumb\n\tlog.Println(resp)\n\tlog.Println(body)\n}", "func (o *AssetsErrorWebhook) GetWebhookType() string {\n\tif o == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\n\treturn o.WebhookType\n}", "func (o *TaskOptions) GetFireWebhook() bool {\n\tif o == nil || o.FireWebhook == nil {\n\t\tvar ret bool\n\t\treturn ret\n\t}\n\treturn *o.FireWebhook\n}", "func (s *WebhooksServiceOp) Create(webhook Webhook, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tjsonBody, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn webhookResponse.Data, err\n\t}\n\treqBody := bytes.NewReader(jsonBody)\n\tbody, reqErr := s.client.DoRequest(http.MethodPost, \"/v3/hooks\", reqBody)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\n\treturn webhookResponse.Data, nil\n}", "func GetWebhooksForEvent(event models.EventType) []models.Webhook {\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := `SELECT * FROM (\n\t\tWITH RECURSIVE split(id, url, event, rest) AS (\n\t\t SELECT id, url, '', events || ',' FROM webhooks\n\t\t UNION ALL\n\t\t SELECT id, url,\n\t\t\t\t substr(rest, 0, instr(rest, ',')),\n\t\t\t\t substr(rest, instr(rest, ',')+1)\n\t\t\tFROM split\n\t\t WHERE rest <> '')\n\t\tSELECT id, url, event\n\t\t FROM split\n\t\t WHERE event <> ''\n\t ) AS webhook WHERE event IS \"` + event + `\"`\n\n\trows, err := _db.Query(query)\n\tif err != nil || rows.Err() != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\n\t\tif err := rows.Scan(&id, &url, &event); err != nil {\n\t\t\tlog.Debugln(err)\n\t\t\tlog.Error(\"There is a problem with the database.\")\n\t\t\tbreak\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\treturn webhooks\n}", "func GetWebhookRevision(wh admitv1.MutatingWebhookConfiguration) (string, error) {\n\tif tagName, ok := wh.ObjectMeta.Labels[label.IoIstioRev.Name]; ok {\n\t\treturn tagName, nil\n\t}\n\treturn \"\", fmt.Errorf(\"could not extract tag revision from webhook\")\n}", "func (c *Client) GetWebhookLogs() (map[string]interface{}, error) {\n\tlog.info(\"========== GET WEBHOOK LOGS ==========\")\n\turl := buildURL(path[\"subscriptions\"], \"logs\")\n\n\treturn c.do(\"GET\", url, \"\", nil)\n}", "func Get(c *gophercloud.ServiceClient, id string) (r GetResult) {\n\tresp, err := c.Get(getURL(c, id), &r.Body, nil)\n\t_, r.Header, r.Err = gophercloud.ParseResponse(resp, err)\n\treturn\n}" ]
[ "0.8169553", "0.8138", "0.7985692", "0.7854135", "0.7710703", "0.7689335", "0.7653645", "0.737899", "0.7341168", "0.7315312", "0.6983266", "0.6481195", "0.6448597", "0.6343728", "0.62341195", "0.6145538", "0.61372566", "0.6099527", "0.6056138", "0.60435027", "0.6000879", "0.59823495", "0.59474075", "0.5939406", "0.59217644", "0.58748645", "0.586869", "0.5854107", "0.5820604", "0.5805686", "0.58029944", "0.57568276", "0.5733969", "0.571346", "0.56839615", "0.56537074", "0.56458837", "0.56417936", "0.5637336", "0.5636975", "0.56223774", "0.5542436", "0.55363023", "0.55167425", "0.5498237", "0.54752254", "0.54738814", "0.5444602", "0.54403454", "0.54332185", "0.5430977", "0.54308087", "0.5423382", "0.54193455", "0.54118323", "0.5382755", "0.53790855", "0.5361356", "0.53601944", "0.53565", "0.53482795", "0.5342386", "0.5332447", "0.5319501", "0.5300642", "0.52914286", "0.5279085", "0.5263123", "0.5256912", "0.5244953", "0.5226967", "0.5204447", "0.52043056", "0.5154978", "0.51328206", "0.51199704", "0.51186025", "0.5118343", "0.511364", "0.5090943", "0.508287", "0.5049119", "0.50478023", "0.5036925", "0.5033031", "0.50144804", "0.50136316", "0.500637", "0.49852943", "0.49849385", "0.49827895", "0.4973245", "0.49416792", "0.49390268", "0.4924876", "0.49226", "0.49213848", "0.49177173", "0.49154848", "0.49039578" ]
0.8115613
2
ListWebhooks Lists all of your webhooks. / Lists all of your webhooks.
func (s *WebhooksService) ListWebhooks(queryParams *ListWebhooksQueryParams) (*Webhooks, *resty.Response, error) { path := "/webhooks/" queryParamsString, _ := query.Values(queryParams) response, err := s.client.R(). SetQueryString(queryParamsString.Encode()). SetResult(&Webhooks{}). SetError(&Error{}). Get(path) if err != nil { return nil, nil, err } result := response.Result().(*Webhooks) if queryParams.Paginate { items := s.webhooksPagination(response.Header().Get("Link"), 0, 0) for _, webhook := range items.Items { result.AddWebhook(webhook) } } else { if len(result.Items) < queryParams.Max { items := s.webhooksPagination(response.Header().Get("Link"), len(result.Items), queryParams.Max) for _, webhook := range items.Items { result.AddWebhook(webhook) } } } return result, response, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *Client) ListWebhooks() ([]*Webhook, error) {\n\treturn c.ListWebhooksContext(context.TODO())\n}", "func (s *HangoutsChatWebhooksService) List(ctx context.Context) (webhooks []Webhook, err error) {\n\tvar r webhooksResponse\n\terr = s.client.request(ctx, http.MethodGet, \"v1/hangouts-chat-webhooks\", nil, &r)\n\treturn r.Webhooks, err\n}", "func (s *WebhooksServiceOp) List(options ...interface{}) ([]Webhook, error) {\n\twebhookListResponse := ListWebhookResponse{}\n\tbody, reqErr := s.client.DoRequest(http.MethodGet, \"/v3/hooks\", nil)\n\tif reqErr != nil {\n\t\treturn webhookListResponse.Data, reqErr\n\t}\n\tjsonErr := json.Unmarshal(body, &webhookListResponse)\n\tif jsonErr != nil {\n\t\treturn webhookListResponse.Data, jsonErr\n\t}\n\treturn webhookListResponse.Data, nil\n}", "func (w *WebhookServiceOp) List(options interface{}) ([]Webhook, error) {\n\tpath := fmt.Sprintf(\"%s\", webhooksBasePath)\n\tresource := make([]Webhook, 0)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func (c *ApiService) ListWebhook(ServiceSid string, params *ListWebhookParams) ([]VerifyV2Webhook, error) {\n\tresponse, errors := c.StreamWebhook(ServiceSid, params)\n\n\trecords := make([]VerifyV2Webhook, 0)\n\tfor record := range response {\n\t\trecords = append(records, record)\n\t}\n\n\tif err := <-errors; err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn records, nil\n}", "func (w Webhook) List(ctx context.Context, listOptions postmand.RepositoryListOptions) ([]*postmand.Webhook, error) {\n\twebhooks := []*postmand.Webhook{}\n\tquery, args := listQuery(\"webhooks\", listOptions)\n\terr := w.db.SelectContext(ctx, &webhooks, query, args...)\n\treturn webhooks, err\n}", "func (list ListResponse) GetWebHooks() (*ListOfWebHooks, error) {\n\tif err := list.CanMakeRequest(); err != nil {\n\t\treturn nil, err\n\t}\n\n\tendpoint := fmt.Sprintf(webhooks_path, list.ID)\n\tresponse := new(ListOfWebHooks)\n\n\treturn response, list.api.Request(\"GET\", endpoint, nil, nil, response)\n}", "func (c *Client) ListWebhooksContext(ctx context.Context) ([]*Webhook, error) {\n\treq := &api.WebhooksListRequest{}\n\tresp := &api.WebhooksListResponse{}\n\tif err := c.postContext(ctx, \"webhooks/list\", req, resp); err != nil {\n\t\treturn nil, err\n\t}\n\tres := []*Webhook{}\n\tfor _, h := range *resp {\n\t\thook := &Webhook{\n\t\t\tID: h.ID,\n\t\t\tURL: h.URL,\n\t\t\tDescription: h.Description,\n\t\t\tEvents: h.Events,\n\t\t\tAuthKey: h.AuthKey,\n\t\t\tCreatedAt: h.CreatedAt.Time,\n\t\t\tLastSentAt: h.LastSentAt.Time,\n\t\t\tBatchesSent: h.BatchesSent,\n\t\t\tEventsSent: h.EventsSent,\n\t\t\tLastError: h.LastError,\n\t\t}\n\t\tres = append(res, hook)\n\t}\n\treturn res, nil\n}", "func (a *API) ListRegisteredWebhooks() ([]RegisteredWebhook, error) {\n\tvar resp listRegisteredWebhooksResponse\n\terr := a.Call(\"list_registered_webhooks\", nil, &resp)\n\n\treturn resp, err\n}", "func (c *Client) Webhooks() (Webhooks, error) {\n\tvar res Webhooks\n\terr := c.get(c.baseURL+\"/webhooks\", &res)\n\n\treturn res, err\n}", "func (as *AdminServer) Webhooks(w http.ResponseWriter, r *http.Request) {\n\tparams := newTemplateParams(r)\n\tparams.Title = \"Webhooks\"\n\tgetTemplate(w, \"webhooks\").ExecuteTemplate(w, \"base\", params)\n}", "func GetWebhooks() ([]models.Webhook, error) { //nolint\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := \"SELECT * FROM webhooks\"\n\n\trows, err := _db.Query(query)\n\tif err != nil {\n\t\treturn webhooks, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\t\tvar events string\n\t\tvar timestampString string\n\t\tvar lastUsedString *string\n\n\t\tif err := rows.Scan(&id, &url, &events, &timestampString, &lastUsedString); err != nil {\n\t\t\tlog.Error(\"There is a problem reading the database.\", err)\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\ttimestamp, err := time.Parse(time.RFC3339, timestampString)\n\t\tif err != nil {\n\t\t\treturn webhooks, err\n\t\t}\n\n\t\tvar lastUsed *time.Time\n\t\tif lastUsedString != nil {\n\t\t\tlastUsedTime, _ := time.Parse(time.RFC3339, *lastUsedString)\n\t\t\tlastUsed = &lastUsedTime\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t\tEvents: strings.Split(events, \",\"),\n\t\t\tTimestamp: timestamp,\n\t\t\tLastUsed: lastUsed,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\n\tif err := rows.Err(); err != nil {\n\t\treturn webhooks, err\n\t}\n\n\treturn webhooks, nil\n}", "func (t *TauAPI) GetWebhooks() (webhooks []Webhook, error error) {\n\tvar w = []Webhook{}\n\tvar d struct {\n\t\tCount int64 `json:\"count\"`\n\t\tWebhooks []Webhook `json:\"results\"`\n\t\tDetail string `json:\"detail\"`\n\t}\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"GET\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t})\n\tif err != nil {\n\t\treturn w, err\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn w, err\n\t}\n\tif d.Detail == \"Invalid token.\" { //todo: really use http status code instead.\n\t\treturn w, fmt.Errorf(\"Tauros API: %s\", d.Detail)\n\t}\n\treturn d.Webhooks, nil\n}", "func ListHooks(ctx *context.APIContext) {\n\t// swagger:operation GET /user/hooks user userListHooks\n\t// ---\n\t// summary: List the authenticated user's webhooks\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: page\n\t// in: query\n\t// description: page number of results to return (1-based)\n\t// type: integer\n\t// - name: limit\n\t// in: query\n\t// description: page size of results\n\t// type: integer\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/HookList\"\n\n\tutils.ListOwnerHooks(\n\t\tctx,\n\t\tctx.Doer,\n\t)\n}", "func Webhooks(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlog.Infof(ctx, \"GET /webhooks\")\n\tvar webhooksObj model.WebhooksObj\n\tmakeWebhooksObj(&webhooksObj, r.URL.Query())\n\tlog.Infof(ctx, \"webhooksObj is: %+v\", webhooksObj)\n\n\tgaeMail := makeGaeMailForWebhooks(ctx, &webhooksObj)\n\tgaeMail.Send()\n}", "func (mr *MockRepoClientMockRecorder) ListWebhooks() *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"ListWebhooks\", reflect.TypeOf((*MockRepoClient)(nil).ListWebhooks))\n}", "func (m *MockRepoClient) ListWebhooks() ([]clients.Webhook, error) {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"ListWebhooks\")\n\tret0, _ := ret[0].([]clients.Webhook)\n\tret1, _ := ret[1].(error)\n\treturn ret0, ret1\n}", "func GetWebhooks() []*Webhook {\n\twebhooks := make([]*Webhook, 0, len(webhooksRegistry))\n\tfor _, wh := range webhooksRegistry {\n\t\twebhooks = append(webhooks, wh)\n\t}\n\treturn webhooks\n}", "func (c *EcomClient) GetWebhooks(ctx context.Context) ([]*WebhookResponse, error) {\n\turi := c.endpoint + \"/webhooks\"\n\tres, err := c.request(http.MethodGet, uri, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request failed: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tvar container WebhookContainer\n\tif err := json.NewDecoder(res.Body).Decode(&container); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode failed: %w\", err)\n\t}\n\treturn container.Data, nil\n}", "func (a *ManagementApiService) GetWebhooks(ctx _context.Context) apiGetWebhooksRequest {\n\treturn apiGetWebhooksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func (r *SpacesService) Webhooks(parent string, message *Message) *SpacesWebhooksCall {\n\tc := &SpacesWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func getWebhooks(context context.Context, email string) []Webhook {\n\tquery := datastore.NewQuery(\"Webhook\").Filter(\"User =\", email).Limit(50)\n\twebhooks := make([]Webhook, 0, 50)\n\tquery.GetAll(context, &webhooks)\n\treturn webhooks\n}", "func (a *AppBuilder) Webhooks(objs ...runtime.Object) *AppBuilder {\n\ta.init()\n\tfor _, obj := range objs {\n\t\tif obj == nil {\n\t\t\tcontinue\n\t\t}\n\t\tvar err error\n\t\tif setup, ok := obj.(WebhookSetup); ok {\n\t\t\terr = setup.SetupWebhookWithManager(a.Manager)\n\t\t} else {\n\t\t\terr = ctrl.NewWebhookManagedBy(a.Manager).\n\t\t\t\tFor(obj).\n\t\t\t\tComplete()\n\t\t}\n\t\tif err != nil {\n\t\t\ta.Logger.Fatalw(\"webhook setup error for obj\", \"obj\", obj.GetObjectKind(), \"err\", err)\n\t\t}\n\t}\n\treturn a\n}", "func (t *TauAPI) DeleteWebhooks() (error error) {\n\twebhooks, err := t.GetWebhooks()\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor _, w := range webhooks {\n\t\terr := t.DeleteWebhook(w.ID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (v *Kounta) GetWebHooks(token string, company string) (WebHooks, error) {\n\tclient := &http.Client{}\n\tclient.CheckRedirect = checkRedirectFunc\n\n\tu, _ := url.ParseRequestURI(baseURL)\n\tu.Path = fmt.Sprintf(webHookURL+\".json\", company)\n\turlStr := fmt.Sprintf(\"%v\", u)\n\n\tr, err := http.NewRequest(\"GET\", urlStr, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Header = http.Header(make(map[string][]string))\n\tr.Header.Set(\"Accept\", \"application/json\")\n\tr.Header.Set(\"Authorization\", \"Bearer \"+token)\n\n\tres, err := client.Do(r)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trawResBody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif res.StatusCode == 200 {\n\t\tvar resp WebHooks\n\n\t\tfmt.Println(string(rawResBody))\n\n\t\terr = json.Unmarshal(rawResBody, &resp)\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn resp, nil\n\t}\n\treturn nil, fmt.Errorf(\"Failed to get Kounta Web Hooks %s\", res.Status)\n\n}", "func (_m *Client) ListWebhooks(_a0 context.Context, _a1 build.ListWebhooksArgs) (*[]build.RepositoryWebhook, error) {\n\tret := _m.Called(_a0, _a1)\n\n\tvar r0 *[]build.RepositoryWebhook\n\tif rf, ok := ret.Get(0).(func(context.Context, build.ListWebhooksArgs) *[]build.RepositoryWebhook); ok {\n\t\tr0 = rf(_a0, _a1)\n\t} else {\n\t\tif ret.Get(0) != nil {\n\t\t\tr0 = ret.Get(0).(*[]build.RepositoryWebhook)\n\t\t}\n\t}\n\n\tvar r1 error\n\tif rf, ok := ret.Get(1).(func(context.Context, build.ListWebhooksArgs) error); ok {\n\t\tr1 = rf(_a0, _a1)\n\t} else {\n\t\tr1 = ret.Error(1)\n\t}\n\n\treturn r0, r1\n}", "func (session Session) GetWebhooks() (result []SubscriptionInfo, err error) {\n\treq, err := getWebhooksSubscriptions(nil)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tsession.addTokenAuth(req)\n\tres, err := session.client.Do(req)\n\tif err != nil {\n\t\tlog.Printf(\"Error while executing GetWebhooks request: %s\", err)\n\t\treturn\n\t}\n\n\tif res.StatusCode != 200 {\n\t\terr = fmt.Errorf(\"Request returned: %d\", res.StatusCode)\n\t\treturn\n\t}\n\n\tbody, err := ioutil.ReadAll(res.Body)\n\tif err != nil {\n\t\tlog.Printf(\"Error reading response body: %s\", err)\n\t\treturn\n\t}\n\n\tvar d dataResult\n\tif err = json.Unmarshal(body, &d); err != nil {\n\t\tlog.Printf(\"Error while parsing response body: %s\", err)\n\t\tlog.Printf(\"Body: %s\", body)\n\t\treturn\n\t}\n\n\tfor _, inner := range d.Data {\n\t\tvar sub SubscriptionInfo\n\t\tif err = json.Unmarshal(inner, &sub); err != nil {\n\t\t\tlog.Printf(\"Error while parsing internal JSON: %s\", err)\n\t\t\tlog.Printf(\"Invalid JSON: %s\", inner)\n\t\t\terr = nil\n\t\t\tcontinue\n\t\t}\n\t\tresult = append(result, sub)\n\t}\n\n\treturn\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func (a *Client) GetWebhooks(params *GetWebhooksParams, authInfo runtime.ClientAuthInfoWriter) (*GetWebhooksOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewGetWebhooksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"GetWebhooks\",\n\t\tMethod: \"GET\",\n\t\tPathPattern: \"/webhooks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &GetWebhooksReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*GetWebhooksOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for GetWebhooks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *ApiService) PageWebhook(ServiceSid string, params *ListWebhookParams, pageToken, pageNumber string) (*ListWebhookResponse, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.PageSize != nil {\n\t\tdata.Set(\"PageSize\", fmt.Sprint(*params.PageSize))\n\t}\n\n\tif pageToken != \"\" {\n\t\tdata.Set(\"PageToken\", pageToken)\n\t}\n\tif pageNumber != \"\" {\n\t\tdata.Set(\"Page\", pageNumber)\n\t}\n\n\tresp, err := c.requestHandler.Get(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &ListWebhookResponse{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (b *Bot) Webhook() (*Webhook, error) {\n\tdata, err := b.Raw(\"getWebhookInfo\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tResult Webhook\n\t}\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, wrapError(err)\n\t}\n\treturn &resp.Result, nil\n}", "func GetWebhooks(ctx context.Context) (Webhooks, error) {\n\twebhooks := Webhooks{}\n\terr := db.Bun().NewSelect().\n\t\tModel(&webhooks).\n\t\tRelation(\"Triggers\").\n\t\tScan(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn webhooks, nil\n}", "func (r *RoomsService) Webhooks(parent string, message *Message) *RoomsWebhooksCall {\n\tc := &RoomsWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func GetWebhooksForEvent(event models.EventType) []models.Webhook {\n\twebhooks := make([]models.Webhook, 0)\n\n\tquery := `SELECT * FROM (\n\t\tWITH RECURSIVE split(id, url, event, rest) AS (\n\t\t SELECT id, url, '', events || ',' FROM webhooks\n\t\t UNION ALL\n\t\t SELECT id, url,\n\t\t\t\t substr(rest, 0, instr(rest, ',')),\n\t\t\t\t substr(rest, instr(rest, ',')+1)\n\t\t\tFROM split\n\t\t WHERE rest <> '')\n\t\tSELECT id, url, event\n\t\t FROM split\n\t\t WHERE event <> ''\n\t ) AS webhook WHERE event IS \"` + event + `\"`\n\n\trows, err := _db.Query(query)\n\tif err != nil || rows.Err() != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar id int\n\t\tvar url string\n\n\t\tif err := rows.Scan(&id, &url, &event); err != nil {\n\t\t\tlog.Debugln(err)\n\t\t\tlog.Error(\"There is a problem with the database.\")\n\t\t\tbreak\n\t\t}\n\n\t\tsingleWebhook := models.Webhook{\n\t\t\tID: id,\n\t\t\tURL: url,\n\t\t}\n\n\t\twebhooks = append(webhooks, singleWebhook)\n\t}\n\treturn webhooks\n}", "func (webhooks *Webhooks) AddWebhook(item Webhook) []Webhook {\n\twebhooks.Items = append(webhooks.Items, item)\n\treturn webhooks.Items\n}", "func (db *MongoDB) GetAll() []Webhook {\n\tall := []Webhook{}\n\n\terr := Session.DB(db.DatabaseName).C(db.WebhooksCollectionName).Find(bson.M{}).All(&all)\n\tif err != nil {\n\t\treturn []Webhook{}\n\t}\n\n\treturn all\n}", "func WebAPIConversationList(w http.ResponseWriter, r *http.Request) {\n\tviewData := BaseViewData(w, r)\n\tresponse := webAPIConversationListResponse{}\n\tif viewData.Session == nil {\n\t\tresponse.HasError = true\n\t\tresponse.Error = \"Not Authenticated\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\toffers, err := viewData.Session.User.GetConversationsForUser(Base.Db)\n\tif err != nil {\n\t\tresponse.HasError = true\n\t\tresponse.Error = \"Internal Error\"\n\t\tRenderJSON(w, response)\n\t\treturn\n\t}\n\n\tresponse.HasError = false\n\tresponse.Offers = offers\n\tRenderJSON(w, response)\n}", "func (r *DmsService) Webhooks(parent string, message *Message) *DmsWebhooksCall {\n\tc := &DmsWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func registerWebhookAPIs(ws *restful.WebService) {\n\tws.Route(ws.POST(\"/{service_id}/webhook_github\").\n\t\tTo(webhookGithub).\n\t\tDoc(\"webhook from github\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookGithub{}).\n\t\tWrites(api.WebhookResponse{}))\n\n\tws.Route(ws.POST(\"/{service_id}/webhook_gitlab\").\n\t\tTo(webhookGitLab).\n\t\tDoc(\"webhook from gitlab\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookGitlab{}).\n\t\tWrites(api.WebhookResponse{}))\n\n\tws.Route(ws.POST(\"/{service_id}/webhook_svn\").\n\t\tTo(webhookSVN).\n\t\tDoc(\"webhook from svn\").\n\t\tParam(ws.PathParameter(\"service_id\", \"identifier of the service\").DataType(\"string\")).\n\t\tReads(api.WebhookSVN{}).\n\t\tWrites(api.WebhookResponse{}))\n}", "func (client *WebhooksClient) listHandleResponse(resp *http.Response) (WebhooksClientListResponse, error) {\n\tresult := WebhooksClientListResponse{}\n\tif err := runtime.UnmarshalAsJSON(resp, &result.WebhookListResult); err != nil {\n\t\treturn WebhooksClientListResponse{}, err\n\t}\n\treturn result, nil\n}", "func (command *ListHooksCommand) ListHooksAction(context *cli.Context) error {\n\tclient, err := command.Settings.GetAPIClient()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(command.flags.project) <= 0 {\n\t\treturn errors.New(\"--project flag is required\")\n\t}\n\tif len(command.flags.repository) <= 0 {\n\t\treturn errors.New(\"--repository flag is required\")\n\t}\n\n\tresponse, err := client.GetHooks(command.flags.project, command.flags.repository, bitclient.GetHooksRequest{})\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, hook := range response.Values {\n\n\t\tstatus := \"DISABLED\"\n\t\tif hook.Enabled == true {\n\t\t\tstatus = \"ENABLED \"\n\t\t}\n\n\t\tfmt.Printf(\"[%s] %s (%s)\\n\", status, hook.Details.Name, hook.Details.Key)\n\t}\n\n\treturn nil\n}", "func CleanWebhooks(ctx context.Context, l logr.Logger, c client.Client, requirements labels.Requirements) error {\n\tops := utilclient.DefaultCleanOps()\n\treturn flow.Parallel(\n\t\tcleanResourceFn(l, ops, c, &admissionregistrationv1beta1.MutatingWebhookConfigurationList{}, \"MutationsWebhook\", true, addAdditionalListOptions(botanist.MutatingWebhookConfigurationCleanOption, requirements)),\n\t\tcleanResourceFn(l, ops, c, &admissionregistrationv1beta1.ValidatingWebhookConfigurationList{}, \"ValidationWebhook\", true, addAdditionalListOptions(botanist.ValidatingWebhookConfigurationCleanOption, requirements)),\n\t)(ctx)\n}", "func (m *HookManager) List(opts ...ListOption) (r *HookList, err error) {\n\topts = m.defaults(opts)\n\terr = m.get(m.uri(\"roles\")+m.q(opts), &r)\n\treturn\n}", "func (a *ManagementApiService) GetNotificationWebhooks(ctx _context.Context, applicationId int32) apiGetNotificationWebhooksRequest {\n\treturn apiGetNotificationWebhooksRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t}\n}", "func SetupWebhooks(mgr ctrl.Manager) error {\n\t/*\n\t\tTotally undocumented and hard-to-find feature is that the builder automatically registers the URL path for the webhook.\n\t\tWhat's more, not even the tests in upstream controller-runtime reveal what this path is _actually_ going to look like.\n\t\tSo here's how the path is built (dots replaced with dash, lower-cased, single-form):\n\t\t /validate-<group>-<version>-<kind>\n\t\t /mutate-<group>-<version>-<kind>\n\t\tExample:\n\t\t /validate-clustercode-github-io-v1alpha1-blueprint\n\t\tThis path has to be given in the `//+kubebuilder:webhook:...` magic comment, see example:\n\t\t +kubebuilder:webhook:verbs=create;update;delete,path=/validate-clustercode-github-io-v1alpha1-blueprint,mutating=false,failurePolicy=fail,groups=clustercode.github.io,resources=blueprints,versions=v1alpha1,name=blueprints.clustercode.github.io,sideEffects=None,admissionReviewVersions=v1\n\t\tPay special attention to the plural forms and correct versions!\n\t*/\n\tfor _, setup := range []func(ctrl.Manager) error{\n\t\tblueprintwebhook.SetupWebhook,\n\t} {\n\t\tif err := setup(mgr); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (hh *HealthCheckHandler) List(w http.ResponseWriter, r *http.Request) {\n\tqueryParams := r.URL.Query()\n\tpage, err := strconv.Atoi(queryParams[\"page\"][0])\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlist := hh.db.List()\n\tsort.Sort(models.HealthChecks(list))\n\tstart, end := paginate(page, 10, len(list))\n\tpaginated := list[start:end]\n\n\tres := &models.HealthCheckList{\n\t\tItems: paginated,\n\t\tTotal: len(list),\n\t\tPage: page,\n\t\tSize: 10,\n\t}\n\n\tb, err := json.Marshal(res)\n\tif err != nil {\n\t\thttp.Error(w, marshalError(err.Error()), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tw.Write(b)\n}", "func GetList(w http.ResponseWriter, r *http.Request) {\n\tlist, err := watchlist.GetWatchList(r)\n\n\tif err != nil {\n\t\thttpext.AbortAPI(w, err.Error(), http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\thttpext.JSON(w, list)\n}", "func (s *hookLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAll(s.indexer, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (c *Client) List(ctx context.Context, params *razorpay.RefundListParams) (*razorpay.RefundList, error) {\n\tif params == nil {\n\t\tparams = &razorpay.RefundListParams{}\n\t}\n\n\trefundList := &razorpay.RefundList{}\n\terr := c.Call(ctx, http.MethodGet, \"/refunds\", params, refundList)\n\treturn refundList, err\n}", "func (api *API) ListPayFwds() (payments []PayFwd, err error) {\n\tu, err := api.buildURL(\"/payments\", nil)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = getResponse(u, &payments)\n\treturn\n}", "func (s *NamespaceWebhook) Name() string { return WebhookName }", "func (g *GH) ListHooks() []*github.Hook {\n\tctx := context.Background()\n\thooks, rsp, err := g.c.Organizations.ListHooks(ctx, g.org, nil)\n\tif err != nil {\n\t\tlog.Println(\"Unable to List Hooks in Org\", g.org, rsp, err)\n\t\treturn nil\n\t}\n\tlog.Println(\"Listing Hooks...\", hooks)\n\treturn hooks\n}", "func (c *ApiService) StreamWebhook(ServiceSid string, params *ListWebhookParams) (chan VerifyV2Webhook, chan error) {\n\tif params == nil {\n\t\tparams = &ListWebhookParams{}\n\t}\n\tparams.SetPageSize(client.ReadLimits(params.PageSize, params.Limit))\n\n\trecordChannel := make(chan VerifyV2Webhook, 1)\n\terrorChannel := make(chan error, 1)\n\n\tresponse, err := c.PageWebhook(ServiceSid, params, \"\", \"\")\n\tif err != nil {\n\t\terrorChannel <- err\n\t\tclose(recordChannel)\n\t\tclose(errorChannel)\n\t} else {\n\t\tgo c.streamWebhook(response, params, recordChannel, errorChannel)\n\t}\n\n\treturn recordChannel, errorChannel\n}", "func (m *GetWebhook) Validate(formats strfmt.Registry) error {\n\tvar res []error\n\n\tif err := m.validateCreatedAt(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateDescription(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateEvents(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateID(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateModifiedAt(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateType(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif err := m.validateURL(formats); err != nil {\n\t\t// prop\n\t\tres = append(res, err)\n\t}\n\n\tif len(res) > 0 {\n\t\treturn errors.CompositeValidationError(res...)\n\t}\n\treturn nil\n}", "func (u *UsersService) ListHooks(userID string, opts ...interface{}) (*UserHooks, *simpleresty.Response, error) {\n\thooks := new(UserHooks)\n\turlStr, urlStrErr := u.client.http.RequestURLWithQueryParams(\n\t\tfmt.Sprintf(\"/users/%s/hooks\", userID), opts...)\n\tif urlStrErr != nil {\n\t\treturn nil, nil, urlStrErr\n\t}\n\n\tresponse, err := u.client.http.Get(urlStr, hooks, nil)\n\n\treturn hooks, response, err\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func (wd Word) WordList(ctx context.Context, w http.ResponseWriter, r *http.Request) error {\n\n\tctx, span := trace.StartSpan(ctx, \"handlers.Word.WordList\")\n\tdefer span.End()\n\n\twordList, err := word.WordList(ctx, wd.DB)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn web.Respond(ctx, w, wordList, http.StatusOK)\n}", "func NewCmdWebhooks() *cobra.Command {\n\tvar cmd = &cobra.Command{\n\t\tUse: \"webhooks\",\n\t\tShort: \"Webhooks Management\",\n\t}\n\tcmd.AddCommand(NewCmdWebhooksCreate())\n\tcmd.AddCommand(NewCmdWebhooksList())\n\tcmd.AddCommand(NewCmdWebhooksGet())\n\tcmd.AddCommand(NewCmdWebhooksUpdate())\n\tcmd.AddCommand(NewCmdWebhooksDelete())\n\treturn cmd\n}", "func Webhook(message string) {\n\tendpoint := os.Getenv(\"SLACK_WEBHOOK\")\n\n\tif len(endpoint) == 0 { // If the webhook endpoint is not set, ignore\n\t\treturn\n\t}\n\n\trequest := gorequest.New()\n\tresp, body, err := request.Post(os.Getenv(\"SLACK_WEBHOOK\")).\n\t\tSend(`{\"text\":\"` + message + `\"}`).\n\t\tEnd()\n\tif err != nil { // Die if there was an error\n\t\tlog.Panic(err)\n\t}\n\n\t// Leave these log statements here in case Slack starts being dumb\n\tlog.Println(resp)\n\tlog.Println(body)\n}", "func (e *EventAPI) List() ([]*EventType, error) {\n\teventTypes := []*EventType{}\n\terr := e.client.httpGET(e.backOffConf.create(), e.eventBaseURL(), &eventTypes, \"unable to request event types\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn eventTypes, nil\n}", "func WebhookHandler(w http.ResponseWriter, r *http.Request, reconciler gitopsconfig.Reconciler) {\n\tlog.Info(\"received webhook call\")\n\tif r.Method != \"POST\" {\n\t\tlog.Info(\"webhook handler only accepts the POST method\", \"sent_method\", r.Method)\n\t\tw.WriteHeader(405)\n\t\treturn\n\t}\n\n\tpayload, err := ioutil.ReadAll(r.Body)\n\tif err != nil {\n\t\tlog.Error(err, \"error reading webhook request body\")\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\twebHookEvent, err := github.ParseWebHook(github.WebHookType(r), payload)\n\tif err != nil {\n\t\tlog.Error(err, \"error parsing webhook event payload\")\n\t\treturn\n\t}\n\n\tswitch e := webHookEvent.(type) {\n\tcase *github.PushEvent:\n\t\t// A commit push was received, determine if there is are GitOpsConfigs that match the event\n\t\t// The repository url and Git ref must match for the templateSource or parameterSource\n\t\t{\n\t\t\tlist, err := reconciler.GetAll()\n\t\t\tif err != nil {\n\t\t\t\tlog.Error(err, \"error getting the list of GitOpsConfigs\")\n\t\t\t\tw.WriteHeader(500)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\ttargetList := gitopsv1alpha1.GitOpsConfigList{\n\t\t\t\tTypeMeta: list.TypeMeta,\n\t\t\t\tListMeta: list.ListMeta,\n\t\t\t\tItems: make([]gitopsv1alpha1.GitOpsConfig, 0, len(list.Items)),\n\t\t\t}\n\n\t\t\tfor _, instance := range list.Items {\n\t\t\t\tif !gitopsconfig.ContainsTrigger(&instance, \"Webhook\") {\n\t\t\t\t\tlog.Info(\"skip instance without webhook trigger\", \"instance_name\", instance.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"comparing instance and event metadata\", \"event_name\", e.Repo.GetFullName(), \"event_ref\", e.GetRef(),\n\t\t\t\t\t\"template_uri\", instance.Spec.TemplateSource.URI, \"template_ref\", instance.Spec.TemplateSource.Ref,\n\t\t\t\t\t\"parameter_uri\", instance.Spec.ParameterSource.URI, \"parameter_ref\", instance.Spec.ParameterSource.Ref)\n\n\t\t\t\tif !repoURLAndRefMatch(&instance, e) {\n\t\t\t\t\tlog.Info(\"skip instance without matching repo url or git ref of the event\", \"instance_name\", instance.Name)\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tlog.Info(\"found matching instance\", \"instance_name\", instance.Name)\n\t\t\t\ttargetList.Items = append(targetList.Items, instance)\n\t\t\t}\n\n\t\t\tif len(targetList.Items) == 0 {\n\t\t\t\tlog.Info(\"no gitopsconfigs match the webhook event\", \"event_repo\", e.Repo.GetFullName(), \"event_ref\", strings.TrimPrefix(e.GetRef(), \"refs/heads/\"))\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tfor _, instance := range targetList.Items {\n\t\t\t\t//if secured discard those that do not validate\n\t\t\t\tsecret := getWebhookSecret(&instance)\n\t\t\t\tif secret != \"\" {\n\t\t\t\t\t_, err := github.ValidatePayload(r, []byte(secret))\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tlog.Error(err, \"webhook payload could not be validated with instance secret --> ignoring\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tlog.Info(\"Webhook triggering job\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t_, err := reconciler.CreateJob(\"create\", &instance)\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Error(err, \"Webhook unable to create job for instance\", \"instance\", instance.GetName(), \"namespace\", instance.GetNamespace())\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\tdefault:\n\t\t{\n\t\t\tlog.Info(\"unknown event type\", \"type\", github.WebHookType(r))\n\t\t\treturn\n\t\t}\n\t}\n\tlog.Info(\"webhook handling concluded correctly\")\n}", "func SendWebhook(wh data.WebhookServices, event string, data interface{}) {\n\theaders := make(map[string]string)\n\theaders[\"X-Webhook-Event\"] = event\n\n\tsubscribers, err := wh.AllSubscriptions(event)\n\tif err != nil {\n\t\tlog.Println(\"unable to get webhook subscribers for \", event)\n\t\treturn\n\t}\n\n\tfor _, sub := range subscribers {\n\t\tgo func(sub model.Webhook, headers map[string]string) {\n\t\t\tif err := post(sub.TargetURL, data, nil, headers); err != nil {\n\t\t\t\tlog.Println(\"error calling URL\", sub.TargetURL, err)\n\t\t\t}\n\t\t}(sub, headers)\n\t}\n}", "func (r *Webhooks) Gets(ro *WebhooksOptions) (interface{}, error) {\n\turlStr := r.c.requestUrl(\"/repositories/%s/%s/hooks/\", ro.Owner, ro.RepoSlug)\n\treturn r.c.executePaginated(\"GET\", urlStr, \"\", nil)\n}", "func ListenWebhook(a Application) {\n\thttp.HandleFunc(\"/\", func(w http.ResponseWriter, req *http.Request) {\n\t\tw.WriteHeader(200)\n\n\t\tif req.Method == http.MethodGet {\n\t\t\treturn\n\t\t}\n\n\t\tbody, err := ioutil.ReadAll(req.Body)\n\n\t\tlogrus.Infof(\"webhook data: %s\", string(body))\n\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\tevent := webhookEvent{}\n\n\t\terr = json.Unmarshal(body, &event)\n\t\tif err != nil {\n\t\t\tlogrus.Error(err)\n\t\t\treturn\n\t\t}\n\n\t\tif event.Data.StatementItem.Amount > 0 {\n\t\t\treturn\n\t\t}\n\n\t\titem := Item{\n\t\t\tName: event.Data.StatementItem.Description,\n\t\t\tAmount: event.Data.StatementItem.getNormalizedAmount(),\n\t\t\tCategory: event.Data.StatementItem.getCategory(),\n\t\t}\n\n\t\tif item.Name == \"\" {\n\t\t\tif item.Category != \"\" {\n\t\t\t\titem.Name = item.Category\n\t\t\t} else {\n\t\t\t\titem.Name = \"transaction\"\n\t\t\t}\n\t\t}\n\t\tvar account User\n\n\t\tif event.Data.Account == a.Config.MonobankAccount1 {\n\t\t\taccount = User{\n\t\t\t\tID: a.Config.SenderID1,\n\t\t\t\tUsername: a.Config.UserName1,\n\t\t\t}\n\t\t} else if event.Data.Account == a.Config.MonobankAccount2 {\n\t\t\taccount = User{\n\t\t\t\tID: a.Config.SenderID2,\n\t\t\t\tUsername: a.Config.UserName2,\n\t\t\t}\n\t\t} else {\n\t\t\treturn\n\t\t}\n\n\t\ta.IntegrationEvents <- BankData{Item: item, Account: account}\n\t})\n\n\tlogrus.Info(fmt.Sprintf(\"listen webhook on: %d\", a.Config.MonobankPort))\n\terr := http.ListenAndServe(fmt.Sprintf(\":%d\", a.Config.MonobankPort), nil)\n\tif err != nil {\n\t\tlogrus.Error(err)\n\t}\n}", "func WSList(set *config.Setup, secure bool) error {\n\twsClient := &wSList{\n\t\tUrl: \"/ws_list\",\n\t\tSetup: set,\n\t\tSecure: secure, // only for admins!\n\t}\n\tset.Route.HandleFunc(wsClient.Url, wsClient.HandleConnection)\n\treturn nil\n}", "func (c *ApiService) CreateWebhook(ServiceSid string, params *CreateWebhookParams) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.FriendlyName != nil {\n\t\tdata.Set(\"FriendlyName\", *params.FriendlyName)\n\t}\n\tif params != nil && params.EventTypes != nil {\n\t\tfor _, item := range *params.EventTypes {\n\t\t\tdata.Add(\"EventTypes\", item)\n\t\t}\n\t}\n\tif params != nil && params.WebhookUrl != nil {\n\t\tdata.Set(\"WebhookUrl\", *params.WebhookUrl)\n\t}\n\tif params != nil && params.Status != nil {\n\t\tdata.Set(\"Status\", *params.Status)\n\t}\n\tif params != nil && params.Version != nil {\n\t\tdata.Set(\"Version\", *params.Version)\n\t}\n\n\tresp, err := c.requestHandler.Post(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func webhooksRoutes(r *mux.Router, c *webhooks.Controller) {\n\tr.Handle(\"/{realm_id:[0-9]+}/twilio\", c.HandleTwilio()).Methods(http.MethodPost)\n}", "func (s *GitlabSCM) ListHooks(ctx context.Context, repo *Repository, org string) ([]*Hook, error) {\n\t// TODO no implementation provided yet\n\treturn nil, ErrNotSupported{\n\t\tSCM: \"gitlab\",\n\t\tMethod: \"ListHooks\",\n\t}\n}", "func ExtensionWebService(r Resource) *restful.WebService {\n\tws := new(restful.WebService)\n\tws.\n\t\tPath(\"/webhooks\").\n\t\tConsumes(restful.MIME_JSON, restful.MIME_JSON).\n\t\tProduces(restful.MIME_JSON, restful.MIME_JSON)\n\n\tws.Route(ws.POST(\"/\").To(r.createWebhook))\n\tws.Route(ws.GET(\"/\").To(r.getAllWebhooks))\n\tws.Route(ws.GET(\"/defaults\").To(r.getDefaults))\n\n\treturn ws\n}", "func (api *API) ListWAFRules(zoneID, packageID string) ([]WAFRule, error) {\n\tvar r WAFRulesResponse\n\tvar rules []WAFRule\n\tvar res []byte\n\tvar err error\n\turi := \"/zones/\" + zoneID + \"/firewall/waf/packages/\" + packageID + \"/rules\"\n\tres, err = api.makeRequest(\"GET\", uri, nil)\n\tif err != nil {\n\t\treturn []WAFRule{}, errors.Wrap(err, errMakeRequestError)\n\t}\n\terr = json.Unmarshal(res, &r)\n\tif err != nil {\n\t\treturn []WAFRule{}, errors.Wrap(err, errUnmarshalError)\n\t}\n\tif !r.Success {\n\t\t// TODO: Provide an actual error message instead of always returning nil\n\t\treturn []WAFRule{}, err\n\t}\n\tfor ri := range r.Result {\n\t\trules = append(rules, r.Result[ri])\n\t}\n\treturn rules, nil\n}", "func (lw *EventListWatch) List(options api.ListOptions) (runtime.Object, error) {\n\treturn lw.ListFunc(options)\n}", "func (o IntegrationSlackOutput) Webhook() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *IntegrationSlack) pulumi.StringOutput { return v.Webhook }).(pulumi.StringOutput)\n}", "func (c *Client) GetWebhookLogs() (map[string]interface{}, error) {\n\tlog.info(\"========== GET WEBHOOK LOGS ==========\")\n\turl := buildURL(path[\"subscriptions\"], \"logs\")\n\n\treturn c.do(\"GET\", url, \"\", nil)\n}", "func List(c blogpb.BlogServiceClient) {\n\tstream, err := c.ListBlog(context.Background(), &blogpb.ListBlogRequest{})\n\tif err != nil {\n\t\tlog.Fatalln(\"error while calling ListBlog RPC\", err)\n\t}\n\tfor {\n\t\tres, err := stream.Recv()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\tlog.Fatalln(\"Something happenned\", err)\n\t\t}\n\t\tfmt.Println(res.GetBlog())\n\t}\n}", "func (a *Api) List(w http.ResponseWriter, r *http.Request) error {\n\treturn nil\n}", "func (a *ManagementApiService) GetWebhookLogs(ctx _context.Context) apiGetWebhookLogsRequest {\n\treturn apiGetWebhookLogsRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t}\n}", "func HandleWebhook(messages chan<- string) http.HandlerFunc {\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\tlog.Print(\"got message\")\n\t\tif r.Method != \"POST\" {\n\t\t\tw.WriteHeader(http.StatusMethodNotAllowed)\n\t\t\treturn\n\t\t}\n\n\t\twebhook := decodeWebhook(r.Body)\n\n\t\tfor _, webAlert := range webhook.Alerts {\n\t\t\tlabels := make(map[model.LabelName]model.LabelValue)\n\t\t\tfor k, v := range webAlert.Labels {\n\t\t\t\tlabels[model.LabelName(k)] = model.LabelValue(v)\n\t\t\t}\n\n\t\t\tannotations := make(map[model.LabelName]model.LabelValue)\n\t\t\tfor k, v := range webAlert.Annotations {\n\t\t\t\tannotations[model.LabelName(k)] = model.LabelValue(v)\n\t\t\t}\n\n\t\t\talert := types.Alert{\n\t\t\t\tAlert: model.Alert{\n\t\t\t\t\tStartsAt: webAlert.StartsAt,\n\t\t\t\t\tEndsAt: webAlert.EndsAt,\n\t\t\t\t\tGeneratorURL: webAlert.GeneratorURL,\n\t\t\t\t\tLabels: labels,\n\t\t\t\t\tAnnotations: annotations,\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tmessages <- AlertToMessage(alert) + \"\\n\"\n\t\t}\n\n\t\tw.WriteHeader(http.StatusOK)\n\t}\n}", "func GetWebhook(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WebhookState, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tvar resource Webhook\n\terr := ctx.ReadResource(\"datadog:index/webhook:Webhook\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (h *Handler) WebhookHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := h.client.ParseRequest(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tfor _, event := range events {\n\t\tif event.Type != linebot.EventTypeMessage {\n\t\t\treturn\n\t\t}\n\n\t\tswitch message := event.Message.(type) {\n\t\tcase *linebot.TextMessage:\n\t\t\th.replyMessageExec(event, message)\n\n\t\tcase *linebot.StickerMessage:\n\t\t\treplyMessage := fmt.Sprintf(\n\t\t\t\t\"sticker id is %s, stickerResourceType is ...\", message.StickerID)\n\t\t\tif _, err := h.client.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(replyMessage)).Do(); err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func listTags(ctx context.Context, kubeClient kubernetes.Interface, writer io.Writer) error {\n\ttagWebhooks, err := GetTagWebhooks(ctx, kubeClient)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to retrieve revision tags: %v\", err)\n\t}\n\tif len(tagWebhooks) == 0 {\n\t\tfmt.Fprintf(writer, \"No Istio revision tag MutatingWebhookConfigurations to list\\n\")\n\t\treturn nil\n\t}\n\ttags := make([]tagDescription, 0)\n\tfor _, wh := range tagWebhooks {\n\t\ttagName, err := GetWebhookTagName(wh)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing tag name from webhook %q: %v\", wh.Name, err)\n\t\t}\n\t\ttagRevision, err := GetWebhookRevision(wh)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing revision from webhook %q: %v\", wh.Name, err)\n\t\t}\n\t\ttagNamespaces, err := GetNamespacesWithTag(ctx, kubeClient, tagName)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error retrieving namespaces for tag %q: %v\", tagName, err)\n\t\t}\n\t\ttagDesc := tagDescription{\n\t\t\tTag: tagName,\n\t\t\tRevision: tagRevision,\n\t\t\tNamespaces: tagNamespaces,\n\t\t}\n\t\ttags = append(tags, tagDesc)\n\t}\n\n\tswitch outputFormat {\n\tcase util.JSONFormat:\n\t\treturn PrintJSON(writer, tags)\n\tcase util.TableFormat:\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown format: %s\", outputFormat)\n\t}\n\tw := new(tabwriter.Writer).Init(writer, 0, 8, 1, ' ', 0)\n\tfmt.Fprintln(w, \"TAG\\tREVISION\\tNAMESPACES\")\n\tfor _, t := range tags {\n\t\tfmt.Fprintf(w, \"%s\\t%s\\t%s\\n\", t.Tag, t.Revision, strings.Join(t.Namespaces, \",\"))\n\t}\n\n\treturn w.Flush()\n}", "func List(ctx context.Context, params *razorpay.RefundListParams) (*razorpay.RefundList, error) {\n\treturn getDefaultClient().List(ctx, params)\n}", "func (p *PolicyService) List() (policies *PolicyListResult, err error) {\n\terr = p.client.magicRequestDecoder(\"GET\", \"/policies\", nil, &policies)\n\treturn\n}", "func (in *GitHubWebhookList) DeepCopy() *GitHubWebhookList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(GitHubWebhookList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func (client *WebhooksClient) listCreateRequest(ctx context.Context, resourceGroupName string, registryName string, options *WebhooksClientListOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\treq, err := runtime.NewRequest(ctx, http.MethodGet, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, nil\n}", "func (TelegramBotApp *TelegramBotApp) setupWebhook() (tgbotapi.UpdatesChannel, error) {\n\t_, err := TelegramBotApp.bot.SetWebhook(tgbotapi.NewWebhook(TelegramBotApp.conf.WebhookURL + \"/\" + TelegramBotApp.bot.Token))\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Webhook problem: \", err)\n\t\t//return nil, err\n\t}\n\tupdates := TelegramBotApp.bot.ListenForWebhook(\"/\" + TelegramBotApp.bot.Token)\n\tgo http.ListenAndServe(\":\"+TelegramBotApp.conf.Port, nil)\n\n\tfmt.Println(\"[+] Webhook method selected\")\n\n\treturn updates, nil\n\n}", "func (mock *MailgunMock) GetWebhooksCalls() []struct {\n} {\n\tvar calls []struct {\n\t}\n\tlockMailgunMockGetWebhooks.RLock()\n\tcalls = mock.calls.GetWebhooks\n\tlockMailgunMockGetWebhooks.RUnlock()\n\treturn calls\n}", "func DepleteOutboundList() {\n\tz := len(OutboundList)\n\tfor i := 0; i < z; i++ {\n\t\tdoc := <-OutboundList\n\t\t// Convert to HTTP-needs so we can send the message out.\n\t\tbody, err = json.Marshal(doc.Payload)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error: Could not marshal payload/%s\", err.Error())\n\t\t\t//return http.StatusBadRequest, \"JSON Error\"\n\t\t}\n\t\treq, err := http.NewRequest(\"POST\", doc.Hook, bytes.NewBuffer(body))\n\n\t\tclient := &http.Client{}\n\t\tresp, err := client.Do(req)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"error: Could not connect to Slack/%s\", err.Error())\n\t\t}\n\t\tdefer resp.Body.Close()\n\t\tlog.Printf(\"sent to channel %s\", doc.Payload.Channel)\n\t} // for\n}", "func (s hookNamespaceLister) List(selector labels.Selector) (ret []*v1alpha1.Hook, err error) {\n\terr = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) {\n\t\tret = append(ret, m.(*v1alpha1.Hook))\n\t})\n\treturn ret, err\n}", "func (s *WebhooksServiceOp) Create(webhook Webhook, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tjsonBody, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn webhookResponse.Data, err\n\t}\n\treqBody := bytes.NewReader(jsonBody)\n\tbody, reqErr := s.client.DoRequest(http.MethodPost, \"/v3/hooks\", reqBody)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\n\treturn webhookResponse.Data, nil\n}", "func (a *WorkflowsApiService) WorkflowWorkflowIDWebhooksGetExecute(r ApiWorkflowWorkflowIDWebhooksGetRequest) (ListResponse, *_nethttp.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = _nethttp.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue ListResponse\n\t)\n\n\tlocalBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, \"WorkflowsApiService.WorkflowWorkflowIDWebhooksGet\")\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()}\n\t}\n\n\tlocalVarPath := localBasePath + \"/workflow/{workflowID}/webhooks\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"workflowID\"+\"}\", _neturl.PathEscape(parameterToString(r.workflowID, \"\")), -1)\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := _neturl.Values{}\n\tlocalVarFormParams := _neturl.Values{}\n\n\tif r.pageSize != nil {\n\t\tlocalVarQueryParams.Add(\"pageSize\", parameterToString(*r.pageSize, \"\"))\n\t}\n\tif r.pageNumber != nil {\n\t\tlocalVarQueryParams.Add(\"pageNumber\", parameterToString(*r.pageNumber, \"\"))\n\t}\n\t// to determine the Content-Type header\n\tlocalVarHTTPContentTypes := []string{}\n\n\t// set Content-Type header\n\tlocalVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes)\n\tif localVarHTTPContentType != \"\" {\n\t\tlocalVarHeaderParams[\"Content-Type\"] = localVarHTTPContentType\n\t}\n\n\t// to determine the Accept header\n\tlocalVarHTTPHeaderAccepts := []string{\"application/json\"}\n\n\t// set Accept header\n\tlocalVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts)\n\tif localVarHTTPHeaderAccept != \"\" {\n\t\tlocalVarHeaderParams[\"Accept\"] = localVarHTTPHeaderAccept\n\t}\n\treq, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn localVarReturnValue, nil, err\n\t}\n\n\tlocalVarHTTPResponse, err := a.client.callAPI(req)\n\tif err != nil || localVarHTTPResponse == nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tlocalVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body)\n\tlocalVarHTTPResponse.Body.Close()\n\tlocalVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody))\n\tif err != nil {\n\t\treturn localVarReturnValue, localVarHTTPResponse, err\n\t}\n\n\tif localVarHTTPResponse.StatusCode >= 300 {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: localVarHTTPResponse.Status,\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\terr = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get(\"Content-Type\"))\n\tif err != nil {\n\t\tnewErr := GenericOpenAPIError{\n\t\t\tbody: localVarBody,\n\t\t\terror: err.Error(),\n\t\t}\n\t\treturn localVarReturnValue, localVarHTTPResponse, newErr\n\t}\n\n\treturn localVarReturnValue, localVarHTTPResponse, nil\n}", "func (client PublishedBlueprintsClient) ListResponder(resp *http.Response) (result PublishedBlueprintList, err error) {\n\terr = autorest.Respond(\n\t\tresp,\n\t\tazure.WithErrorUnlessStatusCode(http.StatusOK),\n\t\tautorest.ByUnmarshallingJSON(&result),\n\t\tautorest.ByClosing())\n\tresult.Response = autorest.Response{Response: resp}\n\treturn\n}", "func SetupWithWebhooks(mgr manager.Manager) {\n\thookServer := mgr.GetWebhookServer()\n\n\thookServer.Register(\"/validate-core-kubernetes-v1-resource-quota\", &webhook.Admission{Handler: &quota.ResourceQuotaValidator{PivotClient: utils.PivotClient}})\n\n\thookServer.Register(\"/warden-validate-hotplug-kubecube-io-v1-hotplug\", admisson.ValidatingWebhookFor(hotplug.NewHotplugValidator()))\n\n}", "func (a *Client) PostWebhooks(params *PostWebhooksParams, authInfo runtime.ClientAuthInfoWriter) (*PostWebhooksCreated, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPostWebhooksParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"PostWebhooks\",\n\t\tMethod: \"POST\",\n\t\tPathPattern: \"/webhooks\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PostWebhooksReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*PostWebhooksCreated)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for PostWebhooks: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (c *Client) ListWatches() (roots []string, err error) {\n\treq := &protocol.WatchListRequest{}\n\tif pdu, err := c.send(req); err == nil {\n\t\tres := protocol.NewWatchListResponse(pdu)\n\t\troots = res.Roots()\n\t}\n\treturn\n}", "func (v WidgetsResource) List(c buffalo.Context) error {\n\t// Get the DB connection from the context\n\ttx, ok := c.Value(\"tx\").(*pop.Connection)\n\tif !ok {\n\t\treturn errors.WithStack(errors.New(\"no transaction found\"))\n\t}\n\n\twidgets := &models.Widgets{}\n\n\t// Paginate results. Params \"page\" and \"per_page\" control pagination.\n\t// Default values are \"page=1\" and \"per_page=20\".\n\tq := tx.PaginateFromParams(c.Params())\n\n\t// Retrieve all Widgets from the DB\n\tif err := q.All(widgets); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\n\t// Add the paginator to the context so it can be used in the template.\n\tc.Set(\"pagination\", q.Paginator)\n\n\treturn c.Render(200, r.Auto(c, widgets))\n}", "func (s *WebhooksServiceOp) Get(id int64, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tbody, reqErr := s.client.DoRequest(http.MethodGet, fmt.Sprintf(\"/v3/hooks/%d\", id), nil)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\treturn webhookResponse.Data, nil\n}", "func (in *EKSPodIdentityWebhookList) DeepCopy() *EKSPodIdentityWebhookList {\n\tif in == nil {\n\t\treturn nil\n\t}\n\tout := new(EKSPodIdentityWebhookList)\n\tin.DeepCopyInto(out)\n\treturn out\n}", "func PostWebhooks(diagnostic structs.DiagnosticSpec, status string, promotestatus string, isCron bool, result structs.ResultSpec) error {\n\t// No configured webhook destinations\n\tif diagnostic.WebhookURLs == \"\" {\n\t\treturn nil\n\t}\n\n\t// Assemble the webhook payload\n\tpayload := WebhookPayload{\n\t\tJob: diagnostic.JobSpace + \"/\" + diagnostic.Job,\n\t\tTarget: diagnostic.App + \"-\" + diagnostic.Space,\n\t\tStatus: status,\n\t\tIsPreview: diagnostic.IsPreview,\n\t\tIsCron: isCron,\n\t\tLogURL: os.Getenv(\"LOG_URL\") + \"/logs/\" + diagnostic.RunID,\n\t\tKibanaURL: os.Getenv(\"KIBANA_URL\") + \"/app/kibana#/doc/logs/logs/run/?id=\" + diagnostic.RunID,\n\t\tArtifactsURL: os.Getenv(\"ARTIFACTS_URL\") + \"/v1/artifacts/\" + diagnostic.RunID + \"/\",\n\t\tRerunURL: os.Getenv(\"RERUN_URL\") + \"?space=\" + diagnostic.Space + \"&app=\" + diagnostic.App + \"&action=\" + diagnostic.Action + \"&result=\" + diagnostic.Result + \"&releaseid=\" + diagnostic.ReleaseID + \"&buildid=\" + diagnostic.BuildID,\n\t\tCommitAuthor: diagnostic.CommitAuthor,\n\t\tStartTime: result.Payload.StartTime,\n\t\tStopTime: result.Payload.StopTime,\n\t\tRunDurationMs: result.Payload.BuildTimeMillis,\n\t\tPromotionResults: PromotionResults{},\n\t}\n\n\tif diagnostic.GithubVersion != \"\" {\n\t\tpayload.GithubVersion = diagnostic.GithubVersion\n\t}\n\n\tif status != \"success\" {\n\t\tpayload.PromotionResults.Message = \"No promotion triggered - tests not successful\"\n\t} else if diagnostic.PipelineName == \"manual\" {\n\t\tpayload.PromotionResults.Message = \"No promotion triggered - set to manual\"\n\t\tpayload.PromotionResults.Pipeline = diagnostic.PipelineName\n\t} else {\n\t\tpayload.PromotionResults.Message = \"Promotion was triggered with result \" + promotestatus\n\t\tpayload.PromotionResults.Status = promotestatus\n\t\tpayload.PromotionResults.From = diagnostic.TransitionFrom\n\t\tpayload.PromotionResults.To = diagnostic.TransitionTo\n\t\tpayload.PromotionResults.Pipeline = diagnostic.PipelineName\n\t}\n\n\t// Send message to each hook URL\n\tfor _, hookURL := range strings.Split(diagnostic.WebhookURLs, \",\") {\n\t\tpayloadBytes, err := json.Marshal(payload)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\tif !strings.HasPrefix(hookURL, \"http://\") && !strings.HasPrefix(hookURL, \"https://\") {\n\t\t\thookURL = \"https://\" + hookURL\n\t\t}\n\n\t\treq, err := http.NewRequest(\"POST\", hookURL, bytes.NewBuffer(payloadBytes))\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\t\treq.Header.Add(\"Content-type\", \"application/json\")\n\n\t\tclient := http.Client{}\n\t\t_, err = client.Do(req)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn err\n\t\t}\n\n\t\t// If we ever want to save the result and do something with it\n\t\t// defer resp.Body.Close()\n\t\t// bodybytes, err := ioutil.ReadAll(resp.Body)\n\t\t// if err != nil {\n\t\t// \tfmt.Println(err)\n\t\t// \treturn err\n\t\t// }\n\t\t// fmt.Println(string(bodybytes))\n\t\t// fmt.Println(resp.status)\n\t}\n\treturn nil\n}", "func (s *BlueprintsService) List() ([]*Blueprint, *Response, error) {\n\treq, err := s.client.NewRequest(\"GET\", \"blueprint\", nil)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\troot := Root{}\n\tresp, err := s.client.Do(req, &root)\n\tif err != nil {\n\t\treturn nil, resp, err\n\t}\n\n\treturn root.Blueprints, resp, nil\n}", "func (c WebhooksConfig) NewWebhooks(ctx context.Context, server io.Server) (web.Webhooks, error) {\n\tvar target web.Sink\n\tswitch c.Target {\n\tcase \"\":\n\t\treturn nil, nil\n\tcase \"direct\":\n\t\ttarget = &web.HTTPClientSink{\n\t\t\tClient: &http.Client{\n\t\t\t\tTimeout: c.Timeout,\n\t\t\t},\n\t\t}\n\tdefault:\n\t\treturn nil, errWebhooksTarget.WithAttributes(\"target\", c.Target)\n\t}\n\tif c.Registry == nil {\n\t\treturn nil, errWebhooksRegistry.New()\n\t}\n\tif c.QueueSize > 0 || c.Workers > 0 {\n\t\ttarget = &web.QueuedSink{\n\t\t\tTarget: target,\n\t\t\tQueue: make(chan *http.Request, c.QueueSize),\n\t\t\tWorkers: c.Workers,\n\t\t}\n\t}\n\tif controllable, ok := target.(web.ControllableSink); ok {\n\t\tgo func() {\n\t\t\tif err := controllable.Run(ctx); err != nil && !errors.IsCanceled(err) {\n\t\t\t\tlog.FromContext(ctx).WithError(err).Error(\"Webhooks target sink failed\")\n\t\t\t}\n\t\t}()\n\t}\n\treturn web.NewWebhooks(ctx, server, c.Registry, target, c.Downlinks), nil\n}" ]
[ "0.85535747", "0.8307529", "0.7989463", "0.7700443", "0.7628448", "0.7608494", "0.7259451", "0.70235413", "0.69978625", "0.6991822", "0.67907065", "0.67228", "0.6624631", "0.6573754", "0.6538952", "0.64053786", "0.633853", "0.6296355", "0.6126621", "0.60276693", "0.6024295", "0.59125465", "0.5902845", "0.5896784", "0.5878739", "0.5869946", "0.5868729", "0.58328414", "0.5816842", "0.5804054", "0.5767543", "0.5762676", "0.57496005", "0.5705796", "0.5665686", "0.56518143", "0.5605337", "0.55974966", "0.55693275", "0.556521", "0.55556405", "0.54922986", "0.5453023", "0.5441686", "0.5425532", "0.53235286", "0.5286928", "0.5283034", "0.52798474", "0.5239543", "0.52287734", "0.5228279", "0.5223427", "0.52184504", "0.5192349", "0.5189085", "0.5182265", "0.51766175", "0.51760554", "0.51748174", "0.5172993", "0.5170927", "0.5156955", "0.5139505", "0.513125", "0.5128367", "0.5115984", "0.51123095", "0.5073669", "0.5068247", "0.50625575", "0.50535727", "0.5044603", "0.5037983", "0.5036486", "0.50343144", "0.503152", "0.5030722", "0.5030597", "0.50305325", "0.5030358", "0.5020955", "0.50038135", "0.49961343", "0.49816057", "0.4980862", "0.4980195", "0.49656647", "0.49644792", "0.49578568", "0.49404544", "0.4938659", "0.49261823", "0.49226096", "0.49207753", "0.49152064", "0.4914149", "0.4901671", "0.48993227", "0.4899278" ]
0.83958155
1
UpdateWebhook Updates a webhook, by ID. / Updates a webhook, by ID. Specify the webhook ID in the webhookID parameter in the URI.
func (s *WebhooksService) UpdateWebhook(webhookID string, webhookUpdateRequest *WebhookUpdateRequest) (*Webhook, *resty.Response, error) { path := "/webhooks/{webhookId}" path = strings.Replace(path, "{"+"webhookId"+"}", fmt.Sprintf("%v", webhookID), -1) response, err := s.client.R(). SetBody(webhookUpdateRequest). SetResult(&Webhook{}). SetError(&Error{}). Put(path) if err != nil { return nil, nil, err } result := response.Result().(*Webhook) return result, response, err }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func (c *EcomClient) UpdateWebhook(ctx context.Context, webhookID string, req *UpdateWebhookRequest) (*WebhookResponse, error) {\n\trequest, err := json.Marshal(&req)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"json marshal: %w\", err)\n\t}\n\n\tbody := strings.NewReader(string(request))\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodPatch, url, body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode >= 400 {\n\t\tvar e badRequestResponse\n\t\tif err := json.NewDecoder(res.Body).Decode(&e); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"Status: %d, Code: %s, Message: %s\", e.Status, e.Code, e.Message)\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, errors.Wrapf(err, \"json decode url %s\", url)\n\t}\n\treturn &w, nil\n}", "func (z *Client) UpdateWebhook(ctx context.Context, webhookID string, hook *Webhook) error {\n\tvar data struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\tdata.Webhook = hook\n\n\t_, err := z.put(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID), data)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (c *Client) UpdateWebhook(ctx context.Context, repo bitbucket.Repo, id int, hook bitbucket.Webhook) (bitbucket.Webhook, error) {\n\tmarshalledPayload, err := json.Marshal(hook)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPut, url, bytes.NewBuffer(marshalledPayload))\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\tvar response bitbucket.Webhook\n\tif err := c.sendRequest(req, &response); err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\treturn response, nil\n}", "func (c *MockWebhookClient) UpdateWebhook(ctx context.Context, repo bitbucket.Repo, id int, hook bitbucket.Webhook) (result bitbucket.Webhook, err error) {\n\treturn c.MockUpdateWebhook(ctx, repo, id, hook)\n}", "func (c *Client) UpdateWebhook(w *Webhook) error {\n\treturn c.UpdateWebhookContext(context.TODO(), w)\n}", "func (s *WebhookServiceOp) Update(ctx context.Context, webhook Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d.json\", webhooksBasePath, webhook.ID)\n\twrappedData := WebhookResource{Webhook: &webhook}\n\tresource := new(WebhookResource)\n\terr := s.client.Put(ctx, path, wrappedData, resource)\n\treturn resource.Webhook, err\n}", "func (w *WebhookServiceOp) Update(webhook *Webhook) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhook.ID)\n\tresource := new(Webhook)\n\terr := w.client.Put(path, webhook, &resource)\n\n\treturn resource, err\n}", "func (s *WebhooksServiceOp) Update(webhook Webhook, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tjsonBody, err := json.Marshal(webhook)\n\tif err != nil {\n\t\treturn webhookResponse.Data, err\n\t}\n\treqBody := bytes.NewReader(jsonBody)\n\tbody, reqErr := s.client.DoRequest(http.MethodPut, fmt.Sprintf(\"/v3/hooks/%d\", webhook.ID), reqBody)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\n\treturn webhookResponse.Data, nil\n}", "func (c *Client) Webhook(id int) (*Webhook, error) {\n\tvar res Webhook\n\terr := c.get(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), &res)\n\n\treturn &res, err\n}", "func (w Webhook) Update(ctx context.Context, webhook *postmand.Webhook) error {\n\tquery, args := updateQuery(\"webhooks\", webhook.ID, webhook)\n\t_, err := w.db.ExecContext(ctx, query, args...)\n\treturn err\n}", "func (c Client) Update(input *UpdateWebhookInput) (*UpdateWebhookResponse, error) {\n\treturn c.UpdateWithContext(context.Background(), input)\n}", "func (a *ManagementApiService) UpdateNotificationWebhook(ctx _context.Context, applicationId int32, notificationWebhookId int32) apiUpdateNotificationWebhookRequest {\n\treturn apiUpdateNotificationWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\tapplicationId: applicationId,\n\t\tnotificationWebhookId: notificationWebhookId,\n\t}\n}", "func UpdateBotProxyWebHook(id, token string) (*viber.PutWebhooksViberWebhookIDOK, error) {\n\tclient := getBotProxyClient()\n\tparams := viber.NewPutWebhooksViberWebhookIDParams().WithBody(&botproxymodels.PutWebhooksViberWebhookIDParamsBody{})\n\tparams.Body.Token = &token\n\tparams.WebhookID = id\n\n\treturn client.Viber.PutWebhooksViberWebhookID(params)\n}", "func DeleteWebhook(id int) error {\n\tlog.Traceln(\"Deleting webhook\")\n\n\ttx, err := _db.Begin()\n\tif err != nil {\n\t\treturn err\n\t}\n\tstmt, err := tx.Prepare(\"DELETE FROM webhooks WHERE id = ?\")\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer stmt.Close()\n\n\tresult, err := stmt.Exec(id)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif rowsDeleted, _ := result.RowsAffected(); rowsDeleted == 0 {\n\t\t_ = tx.Rollback()\n\t\treturn errors.New(fmt.Sprint(id) + \" not found\")\n\t}\n\n\tif err = tx.Commit(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (t *TauAPI) DeleteWebhook(ID int64) error {\n\t_, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"DELETE\",\n\t\tPath: \"webhooks/webhooks/\" + strconv.FormatInt(ID, 10),\n\t\tNeedsAuth: true,\n\t})\n\treturn err\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.delete(c.baseURL+fmt.Sprintf(\"/webhooks/%d\", id), nil)\n}", "func (o *DeleteV1WebhooksWebhookIDParams) SetWebhookID(webhookID string) {\n\to.WebhookID = webhookID\n}", "func (s *WebhooksService) GetWebhook(webhookID string) (*Webhook, *resty.Response, error) {\n\n\tpath := \"/webhooks/{webhookId}\"\n\tpath = strings.Replace(path, \"{\"+\"webhookId\"+\"}\", fmt.Sprintf(\"%v\", webhookID), -1)\n\n\tresponse, err := s.client.R().\n\t\tSetResult(&Webhook{}).\n\t\tSetError(&Error{}).\n\t\tGet(path)\n\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\tresult := response.Result().(*Webhook)\n\treturn result, response, err\n\n}", "func (m *Client) UpdateWebhook(arg0 context.Context, arg1 string, arg2 *zendesk.Webhook) error {\n\tm.ctrl.T.Helper()\n\tret := m.ctrl.Call(m, \"UpdateWebhook\", arg0, arg1, arg2)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (c *Client) DeleteWebhook(id int) error {\n\treturn c.DeleteWebhookContext(context.TODO(), id)\n}", "func (c *Client) UpdateWebhookContext(ctx context.Context, w *Webhook) error {\n\treturn nil\n}", "func DeleteWebhook(ctx context.Context, id WebhookID) error {\n\t_, err := db.Bun().NewDelete().Model((*Webhook)(nil)).Where(\"id = ?\", id).Exec(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func (m *HookManager) Update(id string, r *Hook) error {\n\treturn m.patch(m.uri(\"hooks\", id), r)\n}", "func (c *ApiService) DeleteWebhook(ServiceSid string, Sid string) error {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks/{Sid}\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\tpath = strings.Replace(path, \"{\"+\"Sid\"+\"}\", Sid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tresp, err := c.requestHandler.Delete(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\n\treturn nil\n}", "func (z *Client) GetWebhook(ctx context.Context, webhookID string) (*Webhook, error) {\n\tvar result struct {\n\t\tWebhook *Webhook `json:\"webhook\"`\n\t}\n\n\tbody, err := z.get(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = json.Unmarshal(body, &result)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result.Webhook, nil\n}", "func (c *Client) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) error {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn c.sendRequest(req, nil)\n}", "func (s *WebhooksService) DeleteWebhook(webhookID string) (*resty.Response, error) {\n\n\tpath := \"/webhooks/{webhookId}\"\n\tpath = strings.Replace(path, \"{\"+\"webhookId\"+\"}\", fmt.Sprintf(\"%v\", webhookID), -1)\n\n\tresponse, err := s.client.R().\n\t\tSetError(&Error{}).\n\t\tDelete(path)\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn response, err\n\n}", "func (a *API) UnregisterWebhook(id string) error {\n\treturn a.Call(\"unregister_webhook\", unregisterWebhookRequest{\n\t\tID: id,\n\t}, &emptyResponse{})\n}", "func (mr *ClientMockRecorder) UpdateWebhook(arg0, arg1, arg2 interface{}) *gomock.Call {\n\tmr.mock.ctrl.T.Helper()\n\treturn mr.mock.ctrl.RecordCallWithMethodType(mr.mock, \"UpdateWebhook\", reflect.TypeOf((*Client)(nil).UpdateWebhook), arg0, arg1, arg2)\n}", "func (b *Bot) SetWebhook(w *Webhook) error {\n\t_, err := b.sendFiles(\"setWebhook\", w.getFiles(), w.getParams())\n\treturn err\n}", "func (bot *Bot) handleWebhook(epr *http.EndpointRequest) (resBody []byte, err error) {\n\tupdate := Update{}\n\n\terr = json.Unmarshal(epr.RequestBody, &update)\n\tif err != nil {\n\t\treturn nil, errors.Internal(err)\n\t}\n\n\tvar isHandled bool\n\n\tif len(bot.commands.Commands) > 0 && update.Message != nil {\n\t\tisHandled = bot.handleUpdateCommand(update)\n\t}\n\n\t// If no Command handler found, forward it to global handler.\n\tif !isHandled {\n\t\tbot.opts.HandleUpdate(update)\n\t}\n\n\treturn resBody, nil\n}", "func (c *EcomClient) GetWebhook(ctx context.Context, webhookID string) (*WebhookResponse, error) {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 400 {\n\t\treturn nil, ErrBadRequest\n\t}\n\tif res.StatusCode == 404 {\n\t\treturn nil, ErrWebhookNotFound\n\t}\n\n\tvar w WebhookResponse\n\tif err := json.NewDecoder(res.Body).Decode(&w); err != nil {\n\t\treturn nil, fmt.Errorf(\"decode: %w\", err)\n\t}\n\treturn &w, nil\n}", "func (o *ItemImportRequestOptions) SetWebhook(v string) {\n\to.Webhook = &v\n}", "func TestCreateAndUpdateWebhook(t *testing.T) {\n\tc, _ := NewClient(testClientID, testSecret, APIBaseSandBox)\n\tc.GetAccessToken()\n\n\tcreationPayload := &CreateWebhookRequest{\n\t\tURL: \"https://example.com/paypal_webhooks\",\n\t\tEventTypes: []WebhookEventType{\n\t\t\tWebhookEventType{\n\t\t\t\tName: \"PAYMENT.AUTHORIZATION.CREATED\",\n\t\t\t},\n\t\t},\n\t}\n\n\tcreatedWebhook, err := c.CreateWebhook(creationPayload)\n\tif err != nil {\n\t\tt.Errorf(\"Webhook couldn't be created, error %v\", err)\n\t}\n\n\tupdatePayload := []WebhookField{\n\t\tWebhookField{\n\t\t\tOperation: \"replace\",\n\t\t\tPath: \"/event_types\",\n\t\t\tValue: []interface{}{\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"name\": \"PAYMENT.SALE.REFUNDED\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err = c.UpdateWebhook(createdWebhook.ID, updatePayload)\n\tif err != nil {\n\t\tt.Errorf(\"Couldn't update webhook, error %v\", err)\n\t}\n\n\terr = c.DeleteWebhook(createdWebhook.ID)\n\tif err != nil {\n\t\tt.Errorf(\"An error occurred while webhooks deletion, error %v\", err)\n\t}\n}", "func (c *Client) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (bitbucket.Webhook, error) {\n\turl := c.BaseURL + fmt.Sprintf(\"/rest/api/1.0/projects/%s/repos/%s/webhooks/%d\",\n\t\turl.PathEscape(repo.ProjectKey), url.PathEscape(repo.Repo), id)\n\treq, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)\n\tif err != nil {\n\t\treturn bitbucket.Webhook{}, err\n\t}\n\n\t// The documentation says this is a paged API but it is not\n\tvar payload bitbucket.Webhook\n\tif err := c.sendRequest(req, &payload); err != nil {\n\t\treturn bitbucket.Webhook{}, fmt.Errorf(\"GetWebhook(%+v, %d): %w\", repo, id, err)\n\t}\n\n\treturn payload, nil\n}", "func (c *EcomClient) DeleteWebhook(ctx context.Context, webhookID string) error {\n\turl := c.endpoint + \"/webhooks/\" + webhookID\n\tres, err := c.request(http.MethodDelete, url, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"request: %w\", err)\n\t}\n\tdefer res.Body.Close()\n\n\tif res.StatusCode == 404 {\n\t\treturn ErrWebhookNotFound\n\t}\n\n\treturn nil\n}", "func GetWebhook(ctx *pulumi.Context,\n\tname string, id pulumi.IDInput, state *WebhookState, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tvar resource Webhook\n\terr := ctx.ReadResource(\"datadog:index/webhook:Webhook\", name, id, state, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func (s *WebhooksServiceOp) Get(id int64, options ...interface{}) (Webhook, error) {\n\tvar webhookResponse GetWebhookResponse\n\tbody, reqErr := s.client.DoRequest(http.MethodGet, fmt.Sprintf(\"/v3/hooks/%d\", id), nil)\n\tif reqErr != nil {\n\t\treturn webhookResponse.Data, reqErr\n\t}\n\tjsonErr := json.Unmarshal(body, &webhookResponse)\n\tif jsonErr != nil {\n\t\treturn webhookResponse.Data, jsonErr\n\t}\n\treturn webhookResponse.Data, nil\n}", "func EditHook(ctx *context.APIContext) {\n\t// swagger:operation PATCH /user/hooks/{id} user userEditHook\n\t// ---\n\t// summary: Update a hook\n\t// consumes:\n\t// - application/json\n\t// produces:\n\t// - application/json\n\t// parameters:\n\t// - name: id\n\t// in: path\n\t// description: id of the hook to update\n\t// type: integer\n\t// format: int64\n\t// required: true\n\t// - name: body\n\t// in: body\n\t// schema:\n\t// \"$ref\": \"#/definitions/EditHookOption\"\n\t// responses:\n\t// \"200\":\n\t// \"$ref\": \"#/responses/Hook\"\n\n\tutils.EditOwnerHook(\n\t\tctx,\n\t\tctx.Doer,\n\t\tweb.GetForm(ctx).(*api.EditHookOption),\n\t\tctx.ParamsInt64(\"id\"),\n\t)\n}", "func AddWebhook(ctx context.Context, w *Webhook) error {\n\treturn db.Bun().RunInTx(ctx, nil, func(ctx context.Context, tx bun.Tx) error {\n\t\t_, err := tx.NewInsert().Model(w).Exec(ctx)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, t := range w.Triggers {\n\t\t\tt.WebhookID = w.ID\n\t\t}\n\n\t\tif len(w.Triggers) != 0 {\n\t\t\t_, err = tx.NewInsert().Model(&w.Triggers).Exec(ctx)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n}", "func (cm *CertificateManager) updateWebhookSecret(ctx context.Context, secret *corev1.Secret) error {\n\tnamespacedName := fmt.Sprintf(\"%s/%s\", secret.Namespace, secret.Name)\n\tcm.opts.Logger.Info(\"Updating secret with certificate data\", \"namespacedName\", namespacedName)\n\terr := retry.RetryOnConflict(retry.DefaultRetry, func() error {\n\t\treturn cm.opts.Client.Update(ctx, secret)\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to update webhook secret %s: %w\", namespacedName, err)\n\t}\n\treturn nil\n}", "func (wh *Webhook) Edit(webhookId string, accountId string, data map[string]interface{}, extraHeaders map[string]string) (map[string]interface{}, error) {\n\tif accountId != \"\" {\n\t\turl := fmt.Sprintf(\"/%s%s/%s%s/%s\", constants.VERSION_V2, constants.ACCOUNT_URL, url.PathEscape(accountId), constants.WEBHOOK, url.PathEscape(webhookId))\n\t\treturn wh.Request.Patch(url, data, extraHeaders)\n\t}\n\turl := fmt.Sprintf(\"/%s%s/%s\", constants.VERSION_V1, constants.WEBHOOK, url.PathEscape(accountId))\n\treturn wh.Request.Put(url, data, extraHeaders)\n}", "func (w *Webhook) Update() error {\n\treturn w.UpdateContext(context.TODO())\n}", "func (c *Context) HandleWebhook(w http.ResponseWriter, r *http.Request) {\n\trequestID := l.GenerateContextID()\n\tlogger := &l.Logger{Context: map[string]interface{}{\n\t\t\"request_id\": requestID,\n\t}}\n\tlog := logger.StartLog()\n\tdefer log.Write()\n\n\tlog[\"request_url\"] = r.URL.String()\n\tlog[\"request_path\"] = r.URL.Path\n\tlog[\"request_header\"] = r.Header\n\n\twebhookID := GetRequestWebhookID(r)\n\tif len(webhookID) == 0 {\n\t\tlog[\"error\"] = \"couldn't identify webhook ID from URL\"\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tlog[\"webhook_id\"] = webhookID\n\twebhookSecret, err := c.WebhookSecret.SecretForWebhookID(webhookID)\n\tif err != nil {\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"fetching webhook secret\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tpayload, err := github.ValidatePayload(r, []byte(webhookSecret.Secret))\n\tif err != nil {\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"validating webhook request\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\tdefer r.Body.Close()\n\n\tevent, err := github.ParseWebHook(github.WebHookType(r), payload)\n\tif err != nil {\n\t\tlog[\"request_body\"] = string(payload)\n\t\tlog[\"error\"] = serr.ContextualizeErrorf(err, \"parsing webhook request\")\n\t\thttp.Error(w, requestID, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\tswitch event := event.(type) {\n\tcase *github.PushEvent:\n\t\tlog[\"push_event\"] = event\n\tcase *github.PullRequestEvent:\n\t\tlog[\"pull_event\"] = event\n\n\t\t// Handle the event asynchronously.\n\t\tgo c.HandlePullEvent(webhookSecret, event, requestID, logger)\n\tdefault:\n\t\tlog[\"body\"] = string(payload)\n\t\tlog[\"other_event\"] = true\n\t}\n}", "func (c *Client) UpdateBottle(path string, payload *UpdateBottlePayload) (*http.Response, error) {\n\tvar body io.Reader\n\tb, err := json.Marshal(payload)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to serialize body: %s\", err)\n\t}\n\tbody = bytes.NewBuffer(b)\n\tu := url.URL{Host: c.Host, Scheme: c.Scheme, Path: path}\n\treq, err := http.NewRequest(\"PATCH\", u.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\theader := req.Header\n\theader.Set(\"Content-Type\", \"application/json\")\n\treturn c.Client.Do(req)\n}", "func (b *Bot) Webhook() (*Webhook, error) {\n\tdata, err := b.Raw(\"getWebhookInfo\", nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar resp struct {\n\t\tResult Webhook\n\t}\n\tif err := json.Unmarshal(data, &resp); err != nil {\n\t\treturn nil, wrapError(err)\n\t}\n\treturn &resp.Result, nil\n}", "func (c *Client) UpdateFirewall(ctx context.Context, id int, updateOpts FirewallUpdateOptions) (*Firewall, error) {\n\te, err := c.Firewalls.Endpoint()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq := c.R(ctx).SetResult(&Firewall{})\n\n\tbodyData, err := json.Marshal(updateOpts)\n\tif err != nil {\n\t\treturn nil, NewError(err)\n\t}\n\n\tbody := string(bodyData)\n\n\te = fmt.Sprintf(\"%s/%d\", e, id)\n\tr, err := coupleAPIErrors(req.SetBody(body).Put(e))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r.Result().(*Firewall), nil\n}", "func (b *Bot) SetWebhook(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"setWebhook\", request); err == nil {\n\t\tresult = response.(bool)\n\t}\n\treturn\n}", "func (a *ManagementApiService) GetWebhook(ctx _context.Context, webhookId int32) apiGetWebhookRequest {\n\treturn apiGetWebhookRequest{\n\t\tapiService: a,\n\t\tctx: ctx,\n\t\twebhookId: webhookId,\n\t}\n}", "func Webhook(u *url.URL, h http.Header, req *stripe.Event) (int, http.Header, interface{}, error) {\n\t// if we dont support the handler, just return success so they dont try again.\n\thandler, err := payment.GetHandler(req.Type)\n\tif err != nil {\n\t\treturn response.NewDefaultOK()\n\t}\n\n\t// get the event from stripe api again since they dont provide a way to\n\t// authenticate incoming requests\n\tevent, err := event.Get(req.ID, nil)\n\tif err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\tif err := handler(event.Data.Raw); err != nil {\n\t\treturn response.NewBadRequest(err)\n\t}\n\n\treturn response.NewDefaultOK()\n}", "func (client *Client) SetWebHook(webHook string) *VoidResponse {\n\tbody := JSON{\n\t\t\"url\": webHook,\n\t}\n\tendpoint := client.baseURL + fmt.Sprintf(EndpointSetWebHook, client.accessToken)\n\trequest := gorequest.New().Post(endpoint).Type(gorequest.TypeJSON).Set(UserAgentHeader, UserAgent+\"/\"+Version).Send(body)\n\n\treturn &VoidResponse{\n\t\tClient: client,\n\t\tRequest: request,\n\t}\n}", "func (w *WebhookServiceOp) Get(webhookID int64, options interface{}) (*Webhook, error) {\n\tpath := fmt.Sprintf(\"%s/%d\", webhooksBasePath, webhookID)\n\tresource := new(Webhook)\n\terr := w.client.Get(path, &resource, options)\n\treturn resource, err\n}", "func (TelegramBotApp *TelegramBotApp) setupWebhook() (tgbotapi.UpdatesChannel, error) {\n\t_, err := TelegramBotApp.bot.SetWebhook(tgbotapi.NewWebhook(TelegramBotApp.conf.WebhookURL + \"/\" + TelegramBotApp.bot.Token))\n\tif err != nil {\n\t\tlog.Fatal(\"[!] Webhook problem: \", err)\n\t\t//return nil, err\n\t}\n\tupdates := TelegramBotApp.bot.ListenForWebhook(\"/\" + TelegramBotApp.bot.Token)\n\tgo http.ListenAndServe(\":\"+TelegramBotApp.conf.Port, nil)\n\n\tfmt.Println(\"[+] Webhook method selected\")\n\n\treturn updates, nil\n\n}", "func Webhooks(w http.ResponseWriter, r *http.Request) {\n\tctx := r.Context()\n\tlog.Infof(ctx, \"GET /webhooks\")\n\tvar webhooksObj model.WebhooksObj\n\tmakeWebhooksObj(&webhooksObj, r.URL.Query())\n\tlog.Infof(ctx, \"webhooksObj is: %+v\", webhooksObj)\n\n\tgaeMail := makeGaeMailForWebhooks(ctx, &webhooksObj)\n\tgaeMail.Send()\n}", "func (t *TauAPI) CreateWebhook(webhook Webhook) (ID int64, error error) {\n\tjsonPostMsg, _ := json.Marshal(webhook)\n\tjsonData, err := t.doTauRequest(&TauReq{\n\t\tVersion: 2,\n\t\tMethod: \"POST\",\n\t\tPath: \"webhooks/webhooks\",\n\t\tNeedsAuth: true,\n\t\tPostMsg: jsonPostMsg,\n\t})\n\tif err != nil {\n\t\treturn 0, nil\n\t}\n\tif string(jsonData) == \"[\\\"Limit reached\\\"]\" {\n\t\treturn 0, fmt.Errorf(\"Limit of webhooks reached (5)\")\n\t}\n\tvar d struct {\n\t\tID int64 `json:\"id\"`\n\t}\n\tif err := json.Unmarshal(jsonData, &d); err != nil {\n\t\treturn 0, fmt.Errorf(\"CreateWebhook -> unmarshal jsonData %v\", err)\n\t}\n\treturn d.ID, nil\n}", "func (z *Client) DeleteWebhook(ctx context.Context, webhookID string) error {\n\terr := z.delete(ctx, fmt.Sprintf(\"/webhooks/%s\", webhookID))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}", "func (r *RoomsService) Webhooks(parent string, message *Message) *RoomsWebhooksCall {\n\tc := &RoomsWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func (a *Client) PutWebhooksID(params *PutWebhooksIDParams, authInfo runtime.ClientAuthInfoWriter) (*PutWebhooksIDOK, error) {\n\t// TODO: Validate the params before sending\n\tif params == nil {\n\t\tparams = NewPutWebhooksIDParams()\n\t}\n\n\tresult, err := a.transport.Submit(&runtime.ClientOperation{\n\t\tID: \"PutWebhooksID\",\n\t\tMethod: \"PUT\",\n\t\tPathPattern: \"/webhooks/{id}\",\n\t\tProducesMediaTypes: []string{\"application/json\"},\n\t\tConsumesMediaTypes: []string{\"application/json\"},\n\t\tSchemes: []string{\"https\"},\n\t\tParams: params,\n\t\tReader: &PutWebhooksIDReader{formats: a.formats},\n\t\tAuthInfo: authInfo,\n\t\tContext: params.Context,\n\t\tClient: params.HTTPClient,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tsuccess, ok := result.(*PutWebhooksIDOK)\n\tif ok {\n\t\treturn success, nil\n\t}\n\t// unexpected success response\n\t// safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue\n\tmsg := fmt.Sprintf(\"unexpected success response for PutWebhooksID: API contract not enforced by server. Client expected to get an error, but got: %T\", result)\n\tpanic(msg)\n}", "func (mh *MonkeyHandler) UpdateMonkey(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\tid, err := strconv.Atoi(vars[\"id\"])\n\n\tif err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid monkey ID\")\n\t\treturn\n\t}\n\n\tupdateMonkey := &mh.MonkeyService.Monkey\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(updateMonkey); err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid request payload for updating a Monkey!\")\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\tif err := mh.MonkeyService.UpdateMonkey(id); err != nil {\n\t\terrorRespond(w, http.StatusInternalServerError, err.Error())\n\t}\n\n\tjsonRespond(w, http.StatusOK, updateMonkey)\n\n}", "func GetWebhook(ctx context.Context, webhookID int) (*Webhook, error) {\n\twebhook := Webhook{}\n\terr := db.Bun().NewSelect().\n\t\tModel(&webhook).\n\t\tRelation(\"Triggers\").\n\t\tWhere(\"id = ?\", webhookID).\n\t\tScan(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &webhook, nil\n}", "func (bot *Bot) DeleteWebhook() (err error) {\n\t_, resBody, err := bot.client.PostForm(methodDeleteWebhook, nil, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\tres := &response{}\n\terr = json.Unmarshal(resBody, res)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"DeleteWebhook: %w\", err)\n\t}\n\n\treturn nil\n}", "func (c Client) UpdateWithContext(context context.Context, input *UpdateWebhookInput) (*UpdateWebhookResponse, error) {\n\top := client.Operation{\n\t\tMethod: http.MethodPost,\n\t\tURI: \"/Conversations/Webhooks\",\n\t\tContentType: client.URLEncoded,\n\t}\n\n\tif input == nil {\n\t\tinput = &UpdateWebhookInput{}\n\t}\n\n\tresponse := &UpdateWebhookResponse{}\n\tif err := c.client.Send(context, op, input, response); err != nil {\n\t\treturn nil, err\n\t}\n\treturn response, nil\n}", "func (c *Client) Update(ctx context.Context, id string, params *razorpay.RefundUpdateParams) (*razorpay.Refund, error) {\n\trefund := &razorpay.Refund{}\n\terr := c.Call(ctx, http.MethodPatch, \"/refunds/\"+id, params, refund)\n\treturn refund, err\n}", "func (r *DmsService) Webhooks(parent string, message *Message) *DmsWebhooksCall {\n\tc := &DmsWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func ExecProjectWebhookUpdateMutation(client graphql.Client, id string, input graphql.Variables, upsert bool) (*ProjectWebhook, error) {\n\tif !upsert && id == \"\" {\n\t\treturn nil, fmt.Errorf(\"id is required with upsert false\")\n\t}\n\tvariables := make(graphql.Variables)\n\tvariables[\"id\"] = id\n\tvariables[\"upsert\"] = upsert\n\tvariables[\"input\"] = input\n\tvar sb strings.Builder\n\tsb.WriteString(\"mutation GoProjectWebhookUpdateMutation($id: String, $input: UpdateWorkProjectWebhookInput, $upsert: Boolean) {\\n\")\n\tsb.WriteString(\"\\twork {\\n\")\n\tsb.WriteString(\"\\t\\tupdateProjectWebhook(_id: $id, input: $input, upsert: $upsert) {\\n\")\n\tsb.WriteString(getProjectWebhookQueryFields())\n\tsb.WriteString(\"\\t\\t}\\n\")\n\tsb.WriteString(\"\\t}\\n\")\n\tsb.WriteString(\"}\\n\")\n\tvar res UpdateProjectWebhookData\n\tif err := client.Mutate(sb.String(), variables, &res); err != nil {\n\t\treturn nil, err\n\t}\n\treturn res.Data.Object, nil\n}", "func (c *MockWebhookClient) DeleteWebhook(ctx context.Context, repo bitbucket.Repo, id int) (err error) {\n\treturn c.MockDeleteWebhook(ctx, repo, id)\n}", "func (b *Bot) DeleteWebhook(request axon.O) (result bool, err error) {\n\tvar response interface{}\n\tif response, err = b.doPost(\"deleteWebhook\", request); err == nil {\n\t\tresult = response.(bool)\n\t}\n\treturn\n}", "func (sdk *Sdk) UpdateCampaignTrigger(id string, body *CampaignTriger) (string, error) {\n\tsdkC := sdk.cms\n\tendpoint := fmt.Sprintf(\"/campaigns/%s/triggers\", id)\n\n\treturn sdkC.rq.PutJSON(endpoint, body)\n}", "func (c *Client) WebhookInfo(id int) (*Webhook, error) {\n\treturn c.WebhookInfoContext(context.TODO(), id)\n}", "func (c *Client) AddWebhook(w *Webhook) error {\n\treturn c.AddWebHookContext(context.TODO(), w)\n}", "func Webhook(message string) {\n\tendpoint := os.Getenv(\"SLACK_WEBHOOK\")\n\n\tif len(endpoint) == 0 { // If the webhook endpoint is not set, ignore\n\t\treturn\n\t}\n\n\trequest := gorequest.New()\n\tresp, body, err := request.Post(os.Getenv(\"SLACK_WEBHOOK\")).\n\t\tSend(`{\"text\":\"` + message + `\"}`).\n\t\tEnd()\n\tif err != nil { // Die if there was an error\n\t\tlog.Panic(err)\n\t}\n\n\t// Leave these log statements here in case Slack starts being dumb\n\tlog.Println(resp)\n\tlog.Println(body)\n}", "func (c *Client) UpdateParseWebhook(hostname string, spamCheck bool, sendRaw bool) RequestError {\n\tif hostname == \"\" {\n\t\treturn RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: ErrHostnameRequired,\n\t\t}\n\t}\n\n\tt := ParseWebhook{}\n\tt.SpamCheck = spamCheck\n\tt.SendRaw = sendRaw\n\n\t_, _, err := c.Post(\"PUT\", \"/user/webhooks/parse/settings/\"+hostname, t)\n\tif err != nil {\n\t\treturn RequestError{\n\t\t\tStatusCode: http.StatusInternalServerError,\n\t\t\tErr: err,\n\t\t}\n\t}\n\n\treturn RequestError{\n\t\tStatusCode: http.StatusOK,\n\t}\n}", "func (b *Bot) SetWebhook(url string) bool {\n\tendpoint := fmt.Sprintf(\"https://api.telegram.org/bot%s/setWebhook?url=%s\", b.Token, url)\n\tresp, err := http.Get(endpoint)\n\tif err != nil {\n\t\treturn false\n\t}\n\tvar res APIResponse\n\n\tdecoder := json.NewDecoder(resp.Body)\n\n\terr = decoder.Decode(&res)\n\n\tif !res.Ok {\n\t\treturn false\n\t}\n\treturn true\n}", "func (svc *AdminHookService) Update(h *library.Hook) (*library.Hook, *Response, error) {\n\t// set the API endpoint path we send the request to\n\tu := \"/api/v1/admin/hook\"\n\n\t// library Hook type we want to return\n\tv := new(library.Hook)\n\n\t// send request using client\n\tresp, err := svc.client.Call(\"PUT\", u, h, v)\n\n\treturn v, resp, err\n}", "func (c *MockWebhookClient) GetWebhook(ctx context.Context, repo bitbucket.Repo, id int) (result bitbucket.Webhook, err error) {\n\treturn c.MockGetWebhook(ctx, repo, id)\n}", "func (api *API) ProcessWebhook(c echo.Context) error {\n\tdata, err := ioutil.ReadAll(c.Request().Body)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\tdefer func() { _ = c.Request().Body.Close() }()\n\tp, err := api.services.WebhookDispatcher.GetWebhookProcessor(c.Request().Context(), c.Request().Header, data)\n\tif err != nil {\n\t\tresponse := &MessageResponse{Status: enums.StatusError, Message: err.Error()}\n\t\treturn c.JSON(http.StatusBadRequest, response)\n\t}\n\n\tgo func() {\n\t\tif err := p.Process(c.Request().Context(), c.Request().Header, data); err != nil {\n\t\t\tlogger := logging.FromContext(c.Request().Context())\n\t\t\tlogger.WithField(\"error\", err).Warn(\"could not process webhook\")\n\t\t}\n\t}()\n\treturn c.JSON(http.StatusOK, &MessageResponse{Message: \"ok\"})\n}", "func (r *SpacesService) Webhooks(parent string, message *Message) *SpacesWebhooksCall {\n\tc := &SpacesWebhooksCall{s: r.s, urlParams_: make(gensupport.URLParams)}\n\tc.parent = parent\n\tc.message = message\n\treturn c\n}", "func NewWebhookHandler(e *echo.Echo, u webhook.WebhooksUsecase) {\n\thandler := &WebhookHandler{\n\t\tWebhoolUsecase: u,\n\t}\n\te.POST(\"/webhoooks\", handler.CreateWebhooks)\n\te.DELETE(\"/webhoooks/:id\", handler.DeleteWebhooks)\n}", "func (repo *Repository) UpdateBot(id uuid.UUID, args repository.UpdateBotArgs) error {\n\tif id == uuid.Nil {\n\t\treturn repository.ErrNilID\n\t}\n\tvar (\n\t\tb model.Bot\n\t\tupdated bool\n\t\tuserUpdated bool\n\t)\n\terr := repo.db.Transaction(func(tx *gorm.DB) error {\n\t\tif err := tx.First(&b, &model.Bot{ID: id}).Error; err != nil {\n\t\t\treturn convertError(err)\n\t\t}\n\n\t\tchanges := map[string]interface{}{}\n\t\tif args.Description.Valid {\n\t\t\tchanges[\"description\"] = args.Description.V\n\t\t}\n\t\tif args.Privileged.Valid {\n\t\t\tchanges[\"privileged\"] = args.Privileged.V\n\t\t}\n\t\tif args.Mode.Valid {\n\t\t\tchanges[\"mode\"] = args.Mode.V\n\t\t}\n\t\tif args.WebhookURL.Valid {\n\t\t\tw := args.WebhookURL.V\n\t\t\tchanges[\"post_url\"] = w\n\t\t\tchanges[\"state\"] = model.BotPaused\n\t\t}\n\t\tif args.CreatorID.Valid {\n\t\t\tchanges[\"creator_id\"] = args.CreatorID.V\n\t\t}\n\t\tif args.SubscribeEvents != nil {\n\t\t\tchanges[\"subscribe_events\"] = args.SubscribeEvents\n\t\t}\n\n\t\tif len(changes) > 0 {\n\t\t\tif err := tx.Model(&b).Updates(changes).Error; err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tupdated = true\n\t\t}\n\n\t\tif args.DisplayName.Valid {\n\t\t\tif err := tx.Model(&model.User{ID: b.BotUserID}).Update(\"display_name\", args.DisplayName.V).Error; err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tuserUpdated = true\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif userUpdated {\n\t\trepo.hub.Publish(hub.Message{\n\t\t\tName: event.UserUpdated,\n\t\t\tFields: hub.Fields{\n\t\t\t\t\"user_id\": b.BotUserID,\n\t\t\t},\n\t\t})\n\t}\n\tif updated || userUpdated {\n\t\trepo.hub.Publish(hub.Message{\n\t\t\tName: event.BotUpdated,\n\t\t\tFields: hub.Fields{\n\t\t\t\t\"bot_id\": b.ID,\n\t\t\t},\n\t\t})\n\t}\n\treturn nil\n}", "func (bot *BotAPI) ListenForWebhook(config WebhookConfig) UpdatesChannel {\n\tch := make(chan Update, bot.Buffer)\n\n\thttp.HandleFunc(config.Pattern, func(w http.ResponseWriter, r *http.Request) {\n\t\tbytes, _ := ioutil.ReadAll(r.Body)\n\n\t\tif bot.Secret != \"\" {\n\t\t\tmac := hmac.New(sha1.New, []byte(bot.Secret))\n\t\t\tmac.Write(bytes)\n\t\t\texpectedMac := r.Header.Get(\"X-Signature\")[len(\"sha1=\"):]\n\t\t\tmessageMac := hex.EncodeToString(mac.Sum(nil))\n\t\t\tif expectedMac != messageMac {\n\t\t\t\tbot.debugLog(\"ListenForWebhook HMAC\", expectedMac, messageMac)\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tvar update Update\n\t\tjson.Unmarshal(bytes, &update)\n\n\t\tupdate.ParseRawMessage()\n\t\tif config.PreloadUserInfo {\n\t\t\tbot.PreloadUserInfo(&update)\n\t\t}\n\n\t\tbot.debugLog(\"ListenForWebhook\", update)\n\n\t\tch <- update\n\n\t\tw.WriteHeader(http.StatusNoContent)\n\t})\n\n\treturn ch\n}", "func (b *Bdiscord) isWebhookID(id string) bool {\n\tif b.GetString(\"WebhookURL\") != \"\" {\n\t\twID, _ := b.splitURL(b.GetString(\"WebhookURL\"))\n\t\tif wID == id {\n\t\t\treturn true\n\t\t}\n\t}\n\n\tb.channelsMutex.RLock()\n\tdefer b.channelsMutex.RUnlock()\n\n\tfor _, channel := range b.channelInfoMap {\n\t\tif channel.Options.WebhookURL != \"\" {\n\t\t\twID, _ := b.splitURL(channel.Options.WebhookURL)\n\t\t\tif wID == id {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}", "func (o *DeleteV1WebhooksWebhookIDParams) WithWebhookID(webhookID string) *DeleteV1WebhooksWebhookIDParams {\n\to.SetWebhookID(webhookID)\n\treturn o\n}", "func (s *Service) UpdateHookURL(c context.Context, username string, req *model.HookURLUpdateReq) (rep map[string]interface{}, err error) {\n\tvar repID int64\n\n\tif req.ID > 0 {\n\t\t// update\n\t\tvar (\n\t\t\turlEvents []*model.UrlEvent\n\t\t\turlEventsInDB []*model.UrlEvent\n\t\t\thookUrlInDB *model.HookUrl\n\t\t)\n\n\t\tif hookUrlInDB, err = s.dao.QueryHookURLByID(req.ID); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif hookUrlInDB.ID == 0 {\n\t\t\terr = ecode.NothingFound\n\t\t\treturn\n\t\t}\n\n\t\thookUrl := &model.HookUrl{\n\t\t\tID: req.ID,\n\t\t\tURL: req.URL,\n\t\t\tWorkspaceID: req.WorkspaceID,\n\t\t\tStatus: req.Status,\n\t\t\tUpdateBy: username,\n\t\t}\n\n\t\tif urlEventsInDB, err = s.dao.QueryURLEventByUrl(req.ID); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\t//新增 或修改为可用\n\t\tfor _, eventStr := range req.Events {\n\t\t\turlEvent := &model.UrlEvent{\n\t\t\t\tEvent: eventStr,\n\t\t\t\tStatus: model.HookEventStatusEnable,\n\t\t\t\tUrlID: req.ID,\n\t\t\t}\n\n\t\t\tfor _, urlEventInDB := range urlEventsInDB {\n\t\t\t\tif urlEventInDB.Event == eventStr {\n\t\t\t\t\turlEvent.ID = urlEventInDB.ID\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\turlEvents = append(urlEvents, urlEvent)\n\t\t}\n\n\t\t// 未传值,视为disable\n\t\tfor _, urlEventInDB := range urlEventsInDB {\n\t\t\tif urlEventInDB.Status == model.HookEventStatusEnable {\n\t\t\t\tvar isEnable bool\n\t\t\t\tfor _, eventStr := range req.Events {\n\t\t\t\t\tif eventStr == urlEventInDB.Event {\n\t\t\t\t\t\tisEnable = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif !isEnable {\n\t\t\t\t\turlEvent := &model.UrlEvent{\n\t\t\t\t\t\tEvent: urlEventInDB.Event,\n\t\t\t\t\t\tStatus: model.HookEventStatusDisable,\n\t\t\t\t\t\tID: urlEventInDB.ID,\n\t\t\t\t\t\tUrlID: urlEventInDB.UrlID,\n\t\t\t\t\t}\n\t\t\t\t\turlEvents = append(urlEvents, urlEvent)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif err = s.dao.UpdateHookURLandEvent(hookUrl, urlEvents); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\trepID = req.ID\n\n\t} else {\n\t\t// add\n\t\tvar urlEvents []*model.UrlEvent\n\n\t\thookUrl := &model.HookUrl{\n\t\t\tURL: req.URL,\n\t\t\tWorkspaceID: req.WorkspaceID,\n\t\t\tStatus: req.Status,\n\t\t\tUpdateBy: username,\n\t\t}\n\n\t\tfor _, eventStr := range req.Events {\n\t\t\turlEvent := &model.UrlEvent{\n\t\t\t\tEvent: eventStr,\n\t\t\t\tStatus: model.HookEventStatusEnable,\n\t\t\t}\n\t\t\turlEvents = append(urlEvents, urlEvent)\n\n\t\t}\n\t\tif err = s.dao.AddHookURLandEvent(hookUrl, urlEvents); err != nil {\n\t\t\treturn\n\t\t}\n\t\trepID = hookUrl.ID\n\t}\n\n\trep = make(map[string]interface{})\n\trep[\"url_id\"] = repID\n\treturn\n}", "func (dh *DogHandler) UpdateDog(w http.ResponseWriter, r *http.Request) {\n\n\tvars := mux.Vars(r)\n\n\tid, err := strconv.Atoi(vars[\"id\"])\n\n\tif err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid dog ID\")\n\t\treturn\n\t}\n\n\tupdateDog := &dh.DogService.Dog\n\n\tdecoder := json.NewDecoder(r.Body)\n\tif err := decoder.Decode(updateDog); err != nil {\n\t\terrorRespond(w, http.StatusBadRequest, \"Invalid request payload for updating a Dog!\")\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\n\tif err := dh.DogService.UpdateDog(id); err != nil {\n\t\terrorRespond(w, http.StatusInternalServerError, err.Error())\n\t}\n\n\tjsonRespond(w, http.StatusOK, updateDog)\n\n}", "func (as *AdminServer) Webhooks(w http.ResponseWriter, r *http.Request) {\n\tparams := newTemplateParams(r)\n\tparams.Title = \"Webhooks\"\n\tgetTemplate(w, \"webhooks\").ExecuteTemplate(w, \"base\", params)\n}", "func (c *ApiService) CreateWebhook(ServiceSid string, params *CreateWebhookParams) (*VerifyV2Webhook, error) {\n\tpath := \"/v2/Services/{ServiceSid}/Webhooks\"\n\tpath = strings.Replace(path, \"{\"+\"ServiceSid\"+\"}\", ServiceSid, -1)\n\n\tdata := url.Values{}\n\theaders := make(map[string]interface{})\n\n\tif params != nil && params.FriendlyName != nil {\n\t\tdata.Set(\"FriendlyName\", *params.FriendlyName)\n\t}\n\tif params != nil && params.EventTypes != nil {\n\t\tfor _, item := range *params.EventTypes {\n\t\t\tdata.Add(\"EventTypes\", item)\n\t\t}\n\t}\n\tif params != nil && params.WebhookUrl != nil {\n\t\tdata.Set(\"WebhookUrl\", *params.WebhookUrl)\n\t}\n\tif params != nil && params.Status != nil {\n\t\tdata.Set(\"Status\", *params.Status)\n\t}\n\tif params != nil && params.Version != nil {\n\t\tdata.Set(\"Version\", *params.Version)\n\t}\n\n\tresp, err := c.requestHandler.Post(c.baseURL+path, data, headers)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer resp.Body.Close()\n\n\tps := &VerifyV2Webhook{}\n\tif err := json.NewDecoder(resp.Body).Decode(ps); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn ps, err\n}", "func (o *PaymentStatusUpdateWebhook) SetWebhookType(v string) {\n\to.WebhookType = v\n}", "func HandleTelegramWebHook(w http.ResponseWriter, r *http.Request) {\n\n\t// Parse incoming request\n\tvar update, err = parseTelegramRequest(r)\n\tif err != nil {\n\t\tlog.Printf(\"error parsing update, %s\", err.Error())\n\t\treturn\n\t}\n\n\t// Sanitize input\n\tvar sanitizedSeed = sanitize(update.Message.Text)\n\n\t// Call RapLyrics to get a punchline\n\tvar lyric, errRapLyrics = getPunchline(sanitizedSeed)\n\tif errRapLyrics != nil {\n\t\tlog.Printf(\"got error when calling RapLyrics API %s\", errRapLyrics.Error())\n\t\treturn\n\t}\n\n\t// Send the punchline back to Telegram\n\tvar telegramResponseBody, errTelegram = sendTextToTelegramChat(update.Message.Chat.Id, lyric)\n\tif errTelegram != nil {\n\t\tlog.Printf(\"got error %s from telegram, response body is %s\", errTelegram.Error(), telegramResponseBody)\n\t} else {\n\t\tlog.Printf(\"punchline %s successfully distributed to chat id %d\", lyric, update.Message.Chat.Id)\n\t}\n}", "func FormatWebhookURL(url string, event events.Event) string {\n\treturn strings.ReplaceAll(url, WebhookURLEvent, string(event))\n}", "func NewWebhook(db *sqlx.DB) *Webhook {\n\treturn &Webhook{db: db}\n}", "func NewWebhook(ctx *pulumi.Context,\n\tname string, args *WebhookArgs, opts ...pulumi.ResourceOption) (*Webhook, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Name == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Name'\")\n\t}\n\tif args.Url == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Url'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Webhook\n\terr := ctx.RegisterResource(\"datadog:index/webhook:Webhook\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}", "func updateBlog(c blogpb.BlogServiceClient, blogID string) {\n\tupdatedBlog := &blogpb.Blog{\n\t\tId: blogID,\n\t\tAuthorId: \"TESTER\",\n\t\tTitle: \"Changed Name\",\n\t\tContent: \"Changed content\",\n\t}\n\n\tupdBlog, err := c.UpdateBlog(context.Background(), &blogpb.UpdateBlogRequest{\n\t\tBlog: updatedBlog,\n\t})\n\tif err == nil {\n\t\tfmt.Printf(\"%+v\\n\\n\", updBlog.GetBlog())\n\t} else {\n\t\tfmt.Println(err)\n\t}\n}", "func SetWebhook(token string, url string, port int) error {\n\tdata, _ := json.Marshal(webhook{WebHookURL: url})\n\tr, _ := http.NewRequest(\"POST\", fmt.Sprintf(\"%s/personal/webhook\", monobankAPIURL), bytes.NewReader(data))\n\tr.Header.Set(\"X-Token\", token)\n\tr.Header.Set(\"Content-Type\", \"application/json\")\n\n\tclient := http.Client{}\n\tresp, err := client.Do(r)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != 200 {\n\t\tbody, _ := ioutil.ReadAll(resp.Body)\n\t\treturn fmt.Errorf(\"Status code: %d, Resp: %s\", resp.StatusCode, string(body))\n\t}\n\treturn nil\n}", "func (client *WebhooksClient) updateCreateRequest(ctx context.Context, resourceGroupName string, registryName string, webhookName string, webhookUpdateParameters WebhookUpdateParameters, options *WebhooksClientBeginUpdateOptions) (*policy.Request, error) {\n\turlPath := \"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerRegistry/registries/{registryName}/webhooks/{webhookName}\"\n\tif client.subscriptionID == \"\" {\n\t\treturn nil, errors.New(\"parameter client.subscriptionID cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{subscriptionId}\", url.PathEscape(client.subscriptionID))\n\tif resourceGroupName == \"\" {\n\t\treturn nil, errors.New(\"parameter resourceGroupName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{resourceGroupName}\", url.PathEscape(resourceGroupName))\n\tif registryName == \"\" {\n\t\treturn nil, errors.New(\"parameter registryName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{registryName}\", url.PathEscape(registryName))\n\tif webhookName == \"\" {\n\t\treturn nil, errors.New(\"parameter webhookName cannot be empty\")\n\t}\n\turlPath = strings.ReplaceAll(urlPath, \"{webhookName}\", url.PathEscape(webhookName))\n\treq, err := runtime.NewRequest(ctx, http.MethodPatch, runtime.JoinPaths(client.internal.Endpoint(), urlPath))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treqQP := req.Raw().URL.Query()\n\treqQP.Set(\"api-version\", \"2019-05-01\")\n\treq.Raw().URL.RawQuery = reqQP.Encode()\n\treq.Raw().Header[\"Accept\"] = []string{\"application/json\"}\n\treturn req, runtime.MarshalAsJSON(req, webhookUpdateParameters)\n}", "func (h *Handler) WebhookHandler(w http.ResponseWriter, r *http.Request) {\n\tevents, err := h.client.ParseRequest(r)\n\tif err != nil {\n\t\tlog.Print(err)\n\t\treturn\n\t}\n\tfor _, event := range events {\n\t\tif event.Type != linebot.EventTypeMessage {\n\t\t\treturn\n\t\t}\n\n\t\tswitch message := event.Message.(type) {\n\t\tcase *linebot.TextMessage:\n\t\t\th.replyMessageExec(event, message)\n\n\t\tcase *linebot.StickerMessage:\n\t\t\treplyMessage := fmt.Sprintf(\n\t\t\t\t\"sticker id is %s, stickerResourceType is ...\", message.StickerID)\n\t\t\tif _, err := h.client.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(replyMessage)).Do(); err != nil {\n\t\t\t\tlog.Print(err)\n\t\t\t}\n\t\t}\n\t}\n}", "func UpdateAPI(id string, reqBody *APIReqBody) error {\n\tendpoint, err := utils.ConstructURL(publisherAPIEndpoint, id)\n\tif err != nil {\n\t\treturn err\n\t}\n\treq, err := creatHTTPPUTAPIRequest(endpoint, reqBody)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = send(UpdateAPIContext, req, nil, http.StatusOK)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}", "func NewWebhook(url string, filterFnString string, timeout uint64) (*Webhook, error) {\n\n\tvar err error\n\n\tif url == \"\" {\n\t\terr = errors.New(\"url parameter must be defined for webhook events.\")\n\t\treturn nil, err\n\t}\n\n\twh := &Webhook{\n\t\turl: url,\n\t}\n\tif filterFnString != \"\" {\n\t\twh.filter = NewJSEventFunction(filterFnString)\n\t}\n\n\tif timeout != 0 {\n\t\twh.timeout = time.Duration(timeout) * time.Second\n\t} else {\n\t\twh.timeout = time.Duration(kDefaultWebhookTimeout) * time.Second\n\t}\n\n\treturn wh, err\n}", "func (listener *WebhookListener) HandleWebhook(w http.ResponseWriter, r *http.Request) {\n\tklog.Info(\"handleWebhook headers: \", r.Header)\n\n\tif r.Header.Get(GithubEventHeader) != \"\" {\n\t\t// This is an event from a GitHub repository.\n\t\terr := listener.handleGithubWebhook(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_, err = w.Write([]byte(err.Error()))\n\n\t\t\tif err != nil {\n\t\t\t\tklog.Error(err.Error())\n\t\t\t}\n\t\t}\n\t} else if r.Header.Get(BitbucketEventHeader) != \"\" {\n\t\t// This is an event from a BitBucket repository.\n\t\terr := listener.handleBitbucketWebhook(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_, err = w.Write([]byte(err.Error()))\n\n\t\t\tif err != nil {\n\t\t\t\tklog.Error(err.Error())\n\t\t\t}\n\t\t}\n\t} else if r.Header.Get(GitlabEventHeader) != \"\" {\n\t\t// This is an event from a GitLab repository.\n\t\terr := listener.handleGitlabWebhook(r)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\t\t_, err = w.Write([]byte(err.Error()))\n\n\t\t\tif err != nil {\n\t\t\t\tklog.Error(err.Error())\n\t\t\t}\n\t\t}\n\t} else {\n\t\tklog.Info(\"handleWebhook headers: \", r.Header)\n\t\tklog.Info(\"Unsupported webhook event type.\")\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t_, err := w.Write([]byte(\"Unsupported webhook event type.\"))\n\t\tif err != nil {\n\t\t\tklog.Error(err.Error())\n\t\t}\n\t}\n}", "func (c *client) SetWebhook(args SetWebhookArgs) TelegramError {\n\tresponse, err := c.sendFile(args)\n\tif err != nil {\n\t\treturn errToTelegramErr(err)\n\t}\n\n\tif response.StatusCode != http.StatusOK {\n\t\treturn responseToTgError(response)\n\t}\n\tresponse.Body.Close()\n\n\treturn nil\n}", "func (b *Bot) RemoveWebhook(dropPending ...bool) error {\n\tdrop := false\n\tif len(dropPending) > 0 {\n\t\tdrop = dropPending[0]\n\t}\n\t_, err := b.Raw(\"deleteWebhook\", map[string]bool{\n\t\t\"drop_pending_updates\": drop,\n\t})\n\treturn err\n}" ]
[ "0.78075427", "0.77893424", "0.74463326", "0.7313295", "0.72011757", "0.71203977", "0.6948749", "0.67705953", "0.6759209", "0.6579646", "0.6442859", "0.62431467", "0.61949384", "0.6162747", "0.6156637", "0.6046015", "0.6004151", "0.58870095", "0.5867243", "0.5795031", "0.5760673", "0.56854236", "0.5661326", "0.5647057", "0.5589812", "0.55879885", "0.55839276", "0.55677336", "0.55672127", "0.5515435", "0.5515417", "0.54635006", "0.5460066", "0.545827", "0.5432493", "0.54276896", "0.5403732", "0.53827536", "0.53805065", "0.5358618", "0.5357897", "0.53487116", "0.5341519", "0.53368914", "0.53010964", "0.5289693", "0.5278426", "0.52668446", "0.5238001", "0.5230715", "0.52120167", "0.52043414", "0.5198052", "0.5195428", "0.51915914", "0.51802236", "0.51719975", "0.51534736", "0.51505303", "0.5145877", "0.5141214", "0.51377237", "0.508229", "0.5051188", "0.50419044", "0.5028936", "0.50117344", "0.49960506", "0.4981438", "0.49600565", "0.49593338", "0.4949", "0.49471113", "0.49464434", "0.49431905", "0.49398872", "0.49313784", "0.49284053", "0.49217167", "0.49072564", "0.49053836", "0.4899888", "0.4893277", "0.48910558", "0.4889107", "0.4875152", "0.48730183", "0.48666495", "0.48586679", "0.48547953", "0.4853885", "0.48457095", "0.48422506", "0.4830069", "0.4820512", "0.4815399", "0.48141566", "0.4811574", "0.48102582", "0.47988492" ]
0.782977
0
TrimBytePrefix trims the given prefix.
func TrimBytePrefix(str string, prefix byte) string { if len(str) > 0 && str[0] == prefix { str = str[1:] } return str }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func trimToPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i:]\n}", "func trimOutPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i+len(prefix):]\n}", "func (s *Stringish) TrimPrefix(prefix string) *Stringish {\n\ts.str = strings.TrimPrefix(s.str, prefix)\n\treturn s\n}", "func TrimByteSuffix(str string, suffix byte) string {\n\tif len(str) > 0 && str[len(str)-1] == suffix {\n\t\tstr = str[:len(str)-1]\n\t}\n\treturn str\n}", "func TrimPrefix(prefix, operand string) string { return strings.TrimPrefix(operand, prefix) }", "func (id ID) trimPrefix() ID {\n\treturn ID(strings.TrimPrefix(string(id), \"sha256:\"))\n}", "func compactPrefix() []byte { return []byte{0, 3, 0, 0} }", "func RemovePrefix(prefix, str string) (string, bool) {\n\thad := strings.HasPrefix(str, prefix)\n\treturn strings.TrimPrefix(str, prefix), had\n}", "func compactPrefix() []byte { return []byte{0, 1, 0, 0} }", "func (n *nodeHeader) leftTrimPrefix(l uint16) {\n\tif l < 1 {\n\t\treturn\n\t}\n\tpLen, pBytes := n.prefixFields()\n\tif l > *pLen {\n\t\tl = *pLen\n\t}\n\tnewLen := *pLen - uint16(l)\n\tcopy(pBytes[0:newLen], pBytes[l:*pLen])\n\t*pLen = newLen\n}", "func TrimPrefix(prefix string) MapFunc {\n\treturn func(s string) string { return strings.TrimPrefix(s, prefix) }\n}", "func removePrefix(s string) string {\n\tif !strings.ContainsRune(s, ':') {\n\t\treturn s\n\t}\n\treturn strings.Split(s, \":\")[1]\n}", "func StripPrefix(prefix string, handler func(*Request, *Response)) func(*Request, *Response) {\n\t// check for nil prefix\n\tif prefix == \"\" {\n\t\treturn handler\n\t}\n\t// create handler to trip the prefix before running handler\n\treturn func(req *Request, resp *Response) {\n\t\treq.RequestURI = strings.TrimPrefix(req.RequestURI, prefix)\n\t\thandler(req, resp)\n\t}\n}", "func (o BucketNotificationQueueOutput) FilterPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) *string { return v.FilterPrefix }).(pulumi.StringPtrOutput)\n}", "func trim(name string) string {\n\treturn strings.TrimPrefix(name, Prefix)\n}", "func (tr *NormalizingTarReader) Strip(prefix string) {\n\ttr.headerOpts = append(tr.headerOpts, func(header *tar.Header) *tar.Header {\n\t\theader.Name = strings.TrimPrefix(header.Name, prefix)\n\t\treturn header\n\t})\n}", "func TrimPrefix(objects []string, prefix string) []string {\n\tvar results []string\n\tfor _, object := range objects {\n\t\tresults = append(results, strings.TrimPrefix(object, prefix))\n\t}\n\treturn results\n}", "func (o *Orders) TrimPrefixOrderId(prefix_id string) (int, error) {\n\ttrimmed_id := bytes.TrimPrefix([]byte(prefix_id), []byte(\"order-\"))\n\torder_id, err := strconv.Atoi(string(trimmed_id))\n\treturn order_id, err\n}", "func CleanPrefix(prefix string) string {\n\trunes := []rune(prefix)\n\tif len(runes) == 0 {\n\t\treturn prefix\n\t}\n\t// Trim duplicate leading slash(es).\n\tif runes[0] == '/' {\n\t\tfor len(runes) > 1 && runes[1] == '/' {\n\t\t\trunes = runes[1:]\n\t\t}\n\t}\n\t// Trim trailing slash(es).\n\tfor len(runes) > 0 && runes[len(runes)-1] == '/' {\n\t\trunes = runes[:len(runes)-1]\n\t}\n\t// Were there nothing but slashes?\n\tif len(runes) == 0 {\n\t\treturn \"\"\n\t}\n\t// Build a properly formatted string.\n\tvar b strings.Builder\n\tif runes[0] != '/' {\n\t\tb.Grow(len(runes) + 1)\n\t\tb.WriteRune('/')\n\t} else {\n\t\tb.Grow(len(runes))\n\t}\n\tfor _, r := range runes {\n\t\tb.WriteRune(r)\n\t}\n\treturn b.String()\n}", "func (o BucketNotificationTopicOutput) FilterPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) *string { return v.FilterPrefix }).(pulumi.StringPtrOutput)\n}", "func (db *DB) DeletePrefix(prefix interface{}, value interface{}) error {\n\treturn db.bolt.Update(func(tx *bolt.Tx) error {\n\t\treturn db.DeleteTx(tx, prefix, value)\n\t})\n}", "func (g *gnmiPath) StripPrefix(pfx *gnmiPath) (*gnmiPath, error) {\n\tif !g.isSameType(pfx) {\n\t\treturn nil, fmt.Errorf(\"mismatched path formats in prefix and path, isElementPath: %v != %v\", g.isStringSlicePath(), pfx.isStringSlicePath())\n\t}\n\n\tif !g.isValid() || !pfx.isValid() {\n\t\treturn nil, fmt.Errorf(\"invalid paths supplied for stripPrefix: %v, %v\", g, pfx)\n\t}\n\n\tif pfx.isStringSlicePath() {\n\t\tfor i, e := range pfx.stringSlicePath {\n\t\t\tif g.stringSlicePath[i] != e {\n\t\t\t\treturn nil, fmt.Errorf(\"prefix is not a prefix of the supplied path, %v is not a subset of %v\", pfx, g)\n\t\t\t}\n\t\t}\n\t\treturn newStringSliceGNMIPath(g.stringSlicePath[len(pfx.stringSlicePath):]), nil\n\t}\n\n\tfor i, e := range pfx.pathElemPath {\n\t\tif !util.PathElemsEqual(g.pathElemPath[i], e) {\n\t\t\treturn nil, fmt.Errorf(\"prefix is not a prefix of the supplied path, %v is not a subset of %v\", pfx, g)\n\t\t}\n\t}\n\treturn newPathElemGNMIPath(g.pathElemPath[len(pfx.pathElemPath):]), nil\n}", "func execTrimBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := textproto.TrimBytes(args[0].([]byte))\n\tp.Ret(1, ret)\n}", "func trimmed(bs []byte) []byte {\n\tfor i, b := range bs {\n\t\tif b == 0x00 {\n\t\t\treturn bs[:i]\n\t\t}\n\t}\n\treturn bs\n}", "func (s *IPSet) RemovePrefix(p IPPrefix) { s.RemoveRange(p.Range()) }", "func (s *IPSet) RemovePrefix(p IPPrefix) { s.RemoveRange(p.Range()) }", "func TrimPrefixPath(prefix string, path string) string {\n\treturn strings.TrimPrefix(path, prefix)\n}", "func (o BucketReplicationConfigurationRuleFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRuleFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterPrefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketReplicationConfigurationRuleFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigurationRuleFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketReplicationConfigRuleFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketMetricFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketMetricFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketMetricFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketMetricFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketReplicationConfigRuleFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func trimPrefix(command, prefix string) (string, bool) {\n\tvar c string\n\tif prefix == \"\" && command != \"\" {\n\t\treturn command, true\n\t}\n\tif command == \"\" {\n\t\treturn command, false\n\t}\n\tif c = strings.TrimPrefix(command, prefix); c == command {\n\t\treturn \"\", false\n\t}\n\n\treturn c, len(c) != 0 // if command was \"[prefix]\" and it's trimmed into \"\" it should be false\n\n}", "func (o *SignalPersonName) UnsetPrefix() {\n\to.Prefix.Unset()\n}", "func (o InventoryDestinationBucketOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InventoryDestinationBucket) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketV2ReplicationConfigurationRuleFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2ReplicationConfigurationRuleFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (s *S3Bucket) SetPrefix(v string) *S3Bucket {\n\ts.Prefix = &v\n\treturn s\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func (o BucketReplicationConfigRuleFilterAndPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketReplicationConfigRuleFilterAnd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func DeletePrefix(ctx context.Context, prefix string) error {\n\terr := Client().DeletePrefix(ctx, prefix)\n\tTrace(\"DeletePrefix\", err, logrus.Fields{fieldPrefix: prefix})\n\treturn err\n}", "func (b *Bucket) UnsetMetadataWithPrefix(pre string) {\n\tif b.Version == 0 {\n\t\treturn\n\t}\n\n\tfor p := range b.Metadata {\n\t\tif strings.HasPrefix(p, pre) {\n\t\t\tdelete(b.Metadata, p)\n\t\t}\n\t}\n}", "func stripPrefixes(subj string) string {\n\tredo := true\n\tfor redo {\n\t\tredo = false\n\t\tfor _, prefix := range _BAD_PREFIXES {\n\t\t\tif strings.HasPrefix(strings.ToLower(subj), prefix) {\n\t\t\t\tsubj = subj[len(prefix):]\n\t\t\t\tredo = true\n\t\t\t}\n\t\t}\n\t}\n\n\treturn subj\n}", "func StripPrefix(prefix string, h Handler) Handler {\n\tif prefix == \"\" {\n\t\treturn h\n\t}\n\treturn HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tp := strings.TrimPrefix(r.URL.Path, prefix)\n\t\trp := strings.TrimPrefix(r.URL.RawPath, prefix)\n\t\tif len(p) < len(r.URL.Path) && (r.URL.RawPath == \"\" || len(rp) < len(r.URL.RawPath)) {\n\t\t\tr2 := new(Request)\n\t\t\t*r2 = *r\n\t\t\tr2.URL = new(url.URL)\n\t\t\t*r2.URL = *r.URL\n\t\t\tr2.URL.Path = p\n\t\t\tr2.URL.RawPath = rp\n\t\t\th.ServeHTTP(w, r2)\n\t\t} else {\n\t\t\tNotFound(w, r)\n\t\t}\n\t})\n}", "func (s Settings) TrimPrefix() bool {\n\treturn s.trimPrefix\n}", "func (o BucketReplicationConfigRuleFilterAndOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRuleFilterAnd) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o InventoryDestinationBucketPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InventoryDestinationBucket) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketLifecycleConfigurationV2RuleFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketLifecycleConfigurationV2RuleFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (d *Driver) trimMacAddress(rawUUID string) string {\n\tre := regexp.MustCompile(`[0]([A-Fa-f0-9][:])`)\n\tmac := re.ReplaceAllString(rawUUID, \"$1\")\n\n\treturn mac\n}", "func StripHeader(b []byte) []byte {\n\tif !bytes.HasPrefix(b, frontMatterDash) {\n\t\treturn b\n\t}\n\tb = b[len(frontMatterDash):]\n\tend := bytes.Index(b, frontMatterDash)\n\tif end == -1 {\n\t\treturn b\n\t}\n\treturn b[end+len(frontMatterDash):]\n}", "func (s *Stringish) TrimPrefixSpaces() *Stringish {\n\treturn s.TrimPrefix(\" \")\n}", "func (o BucketIntelligentTieringConfigurationFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketIntelligentTieringConfigurationFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (s *levelsController) dropPrefix(prefix []byte) error {\n\topt := s.kv.opt\n\tfor _, l := range s.levels {\n\t\tl.RLock()\n\t\tif l.level == 0 {\n\t\t\tsize := len(l.tables)\n\t\t\tl.RUnlock()\n\n\t\t\tif size > 0 {\n\t\t\t\tcp := compactionPriority{\n\t\t\t\t\tlevel: 0,\n\t\t\t\t\tscore: 1.74,\n\t\t\t\t\t// A unique number greater than 1.0 does two things. Helps identify this\n\t\t\t\t\t// function in logs, and forces a compaction.\n\t\t\t\t\tdropPrefix: prefix,\n\t\t\t\t}\n\t\t\t\tif err := s.doCompact(cp); err != nil {\n\t\t\t\t\topt.Warningf(\"While compacting level 0: %v\", err)\n\t\t\t\t\treturn nil\n\t\t\t\t}\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\n\t\tvar tables []*table.Table\n\t\tfor _, table := range l.tables {\n\t\t\tvar absent bool\n\t\t\tswitch {\n\t\t\tcase bytes.HasPrefix(table.Smallest(), prefix):\n\t\t\tcase bytes.HasPrefix(table.Biggest(), prefix):\n\t\t\tcase bytes.Compare(prefix, table.Smallest()) > 0 &&\n\t\t\t\tbytes.Compare(prefix, table.Biggest()) < 0:\n\t\t\tdefault:\n\t\t\t\tabsent = true\n\t\t\t}\n\t\t\tif !absent {\n\t\t\t\ttables = append(tables, table)\n\t\t\t}\n\t\t}\n\t\tl.RUnlock()\n\t\tif len(tables) == 0 {\n\t\t\tcontinue\n\t\t}\n\n\t\tcd := compactDef{\n\t\t\telog: trace.New(fmt.Sprintf(\"Badger.L%d\", l.level), \"Compact\"),\n\t\t\tthisLevel: l,\n\t\t\tnextLevel: l,\n\t\t\ttop: []*table.Table{},\n\t\t\tbot: tables,\n\t\t\tdropPrefix: prefix,\n\t\t}\n\t\tif err := s.runCompactDef(l.level, cd); err != nil {\n\t\t\topt.Warningf(\"While running compact def: %+v. Error: %v\", cd, err)\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}", "func (o BucketReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketLifecycleConfigurationV2RuleFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketLifecycleConfigurationV2RuleFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (db *DB) DeletePrefixTx(tx *bolt.Tx, prefix interface{}, value interface{}) error {\n\tpb, err := db.encode(prefix)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tb := tx.Bucket(db.bucket(value))\n\tif b == nil {\n\t\treturn ErrKeyNotExists\n\t}\n\n\tc := b.Cursor()\n\tfor k, _ := c.Seek(pb); k != nil && bytes.HasPrefix(k, pb); k, _ = c.Next() {\n\t\tif err := b.Delete(k); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}", "func (n *nodeHeader) prefix() []byte {\n\tpLen, pBytes := n.prefixFields()\n\n\tif *pLen <= maxPrefixLen {\n\t\t// We have the whole prefix from the node\n\t\treturn pBytes[0:*pLen]\n\t}\n\n\t// Prefix is too long for node, we have to go find it from the leaf\n\tminLeaf := n.minChild().leafNode()\n\treturn minLeaf.key[0:*pLen]\n}", "func (o BucketLifecycleConfigurationV2RuleFilterAndOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketLifecycleConfigurationV2RuleFilterAnd) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o BucketIntelligentTieringConfigurationFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketIntelligentTieringConfigurationFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketLifecycleConfigurationV2RuleFilterAndPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketLifecycleConfigurationV2RuleFilterAnd) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func trimTreePrefix(name string, n int) string {\n\ti := 0\n\tfor ; i < len(name) && n > 0; i++ {\n\t\tif name[i] == '/' {\n\t\t\tn--\n\t\t}\n\t}\n\treturn name[i:]\n}", "func (o BucketLifecycleRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketLifecycleRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func TrimLeadingSpaces(p []byte) []byte {\n\tfor i := 0; i < len(p); i++ {\n\t\tif p[i] != 0x20 && p[i] != '\\t' {\n\t\t\treturn p[i:]\n\t\t}\n\t}\n\t// it was all spaces\n\treturn p[:0]\n}", "func stripZone(zone string) string {\n\treturn strings.TrimRight(zone, \"abc\")\n}", "func (o InventoryFilterPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InventoryFilter) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o ClusterS3ImportOutput) BucketPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v ClusterS3Import) *string { return v.BucketPrefix }).(pulumi.StringPtrOutput)\n}", "func (s *SlackNotify) SetPrefix(v string) {\n\ts.prefix = v\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportDestinationS3BucketDestinationOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v AnalyticsConfigurationStorageClassAnalysisDataExportDestinationS3BucketDestination) *string {\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketReplicationConfigRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketReplicationConfigRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (o InstanceS3ImportOutput) BucketPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InstanceS3Import) *string { return v.BucketPrefix }).(pulumi.StringPtrOutput)\n}", "func (o *SignalPersonName) SetPrefix(v string) {\n\to.Prefix.Set(&v)\n}", "func (o InventoryFilterOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v InventoryFilter) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (s *KinesisVideoStreamConfig) SetPrefix(v string) *KinesisVideoStreamConfig {\n\ts.Prefix = &v\n\treturn s\n}", "func trimLWS(in []byte) []byte {\n\tfirstNonWS := 0\n\tfor ; firstNonWS < len(in) && isWS(in[firstNonWS]); firstNonWS++ {\n\t}\n\n\treturn in[firstNonWS:]\n}", "func (r *Bucket) BucketPrefix() pulumi.StringOutput {\n\treturn (pulumi.StringOutput)(r.s.State[\"bucketPrefix\"])\n}", "func (f *msgFilter) SetPrefix(p string) {\n\tf.prefix = p\n}", "func TrimNull(in []byte) (out []byte) {\n\tvar start int\n\tfor ; start < len(in); start++ {\n\t\tif in[start] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar end = len(in) - 1\n\tfor ; end > start; end-- {\n\t\tif in[end] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tend++\n\n\treturn in[start:end]\n}", "func (b DeleteBuilder) Prefix(sql string, args ...interface{}) DeleteCondition {\n\treturn builder.Append(b, \"Prefixes\", Expr(sql, args...)).(DeleteBuilder)\n}", "func trimIncompleteRune(b []byte) []byte {\n\ti := len(b) - utf8.UTFMax\n\tif i < 0 {\n\t\ti = 0\n\t}\n\tlastStart := len(b)\n\tfor ; i < len(b); i++ {\n\t\tif r, n := utf8.DecodeRune(b[i:]); r != utf8.RuneError || n > 1 {\n\t\t\tlastStart = len(b)\n\t\t\tcontinue\n\t\t}\n\t\tif utf8.RuneStart(b[i]) {\n\t\t\tlastStart = i\n\t\t}\n\t}\n\treturn b[0:lastStart]\n}", "func (o AnalyticsConfigurationStorageClassAnalysisDataExportDestinationS3BucketDestinationPtrOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *AnalyticsConfigurationStorageClassAnalysisDataExportDestinationS3BucketDestination) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.Prefix\n\t}).(pulumi.StringPtrOutput)\n}", "func (kvclient *MockResKVClient) DeleteWithPrefix(ctx context.Context, prefix string) error {\n\treturn nil\n}", "func (fps *FetcherProcessStream) SetPrefix(prefix string) *FetcherProcessStream {\n\tfps.prefix = prefix + \" \"\n\treturn fps\n}", "func TrimBase(r *http.Request, prefix string) string {\n\treturn strings.TrimPrefix(r.URL.Path, AddBase(prefix))\n}", "func (o ClusterS3ImportPtrOutput) BucketPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *ClusterS3Import) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.BucketPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func Uint8ToStringHasPrefix(v string) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.HasPrefix(s.C(FieldUint8ToString), v))\n\t})\n}", "func (o BucketV2ReplicationConfigurationRuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketV2ReplicationConfigurationRule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func trimCut(label []byte, maxlen int, left, right string) []byte {\n\ttrim := bytes.TrimLeft(label, left)\n\tsize := min(len(trim), maxlen)\n\thead := bytes.TrimRight(trim[:size], right)\n\tif len(head) == size {\n\t\treturn head\n\t}\n\ttail := bytes.TrimLeft(trim[size:], right)\n\tif len(tail) > 0 {\n\t\treturn append(head, tail[:min(len(tail), size-len(head))]...)\n\t}\n\treturn head\n}", "func (o InstanceS3ImportPtrOutput) BucketPrefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *InstanceS3Import) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.BucketPrefix\n\t}).(pulumi.StringPtrOutput)\n}", "func RemovePad(t []byte) []byte {\n\tpadLength := int(t[len(t)-1])\n\tfmt.Printf(\"WILL remove %d\\n\", padLength)\n\treturn t[:len(t)-padLength]\n}", "func (h hash) PayloadTrimmed() []byte {\n\tpayload := h.Payload()\n\tfor i := range payload {\n\t\tif payload[i] != 0 {\n\t\t\treturn payload[i:]\n\t\t}\n\t}\n\treturn payload[len(payload)-1:]\n}", "func TrimCVMFSRepoPrefix(path string) string {\n\treturn strings.Join(strings.Split(path, string(os.PathSeparator))[3:], string(os.PathSeparator))\n}", "func StripPrefixHandler(prefix string, h Handler) Handler {\n\tif prefix == \"\" {\n\t\treturn h\n\t}\n\treturn HandlerFunc(func(w ResponseWriter, r *Request) {\n\t\tif p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {\n\t\t\tr2 := new(Request)\n\t\t\t*r2 = *r\n\t\t\tr2.URL = new(url.URL)\n\t\t\t*r2.URL = *r.URL\n\t\t\tr2.URL.Path = p\n\t\t\th.ServeGemini(w, r2)\n\t\t\treturn\n\t\t}\n\t\tNotFound(w, r)\n\t})\n}", "func stripPrefix(s string) (string, bool) {\n\ts = strings.TrimSpace(s)\n\tres := strings.TrimPrefix(s, \"What is\")\n\tif res == s {\n\t\treturn \"\", false\n\t}\n\treturn res, true\n}", "func PrefixBytesDetector(prefix []byte, handler Handler) Detector {\n\treturn Detector{\n\t\tNeeded: len(prefix),\n\t\tTest: func(b []byte) bool {\n\t\t\tfor i, v := range prefix {\n\t\t\t\tif b[i] != v {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true\n\t\t},\n\t\tHandler: handler,\n\t}\n}", "func (a *AbbrFieldNamer) SetPrefix(s string) {\n\ta.Prefix = s\n}", "func (m *MockKeystore) CleanPrefix(prefix string) error {\n\tret := m.ctrl.Call(m, \"CleanPrefix\", prefix)\n\tret0, _ := ret[0].(error)\n\treturn ret0\n}", "func (o BucketLifecycleConfigurationV2RuleOutput) Prefix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketLifecycleConfigurationV2Rule) *string { return v.Prefix }).(pulumi.StringPtrOutput)\n}", "func (w *PrefixedWriter) SetPrefix(p string) {\n\tw.prefix = []byte(p)\n}" ]
[ "0.6788466", "0.66914725", "0.6660232", "0.6501308", "0.649567", "0.6125453", "0.6005247", "0.6002578", "0.5963877", "0.58189476", "0.58109987", "0.58011794", "0.57906777", "0.5790033", "0.57887894", "0.5696721", "0.56474185", "0.5643969", "0.5591693", "0.55878025", "0.55802953", "0.55764717", "0.5560156", "0.5517461", "0.55097306", "0.55097306", "0.55075824", "0.54922", "0.54911494", "0.5434681", "0.54292804", "0.5420137", "0.5414154", "0.5382768", "0.537335", "0.53389907", "0.53068614", "0.53038836", "0.53017676", "0.52906215", "0.52906215", "0.52715164", "0.5266184", "0.5247428", "0.52468157", "0.5234207", "0.52311385", "0.52253515", "0.52228737", "0.52217966", "0.52092886", "0.5190566", "0.51805687", "0.5165342", "0.51534814", "0.5152884", "0.5152542", "0.5145526", "0.5144585", "0.51418155", "0.51381636", "0.5136277", "0.51348585", "0.51279855", "0.5125411", "0.5076162", "0.5073853", "0.5067438", "0.50623024", "0.50530535", "0.5050877", "0.50413924", "0.502933", "0.5014087", "0.5012744", "0.501253", "0.5008945", "0.50030583", "0.5001514", "0.50002617", "0.49917787", "0.49900433", "0.4975359", "0.49711767", "0.4965382", "0.4956538", "0.49513176", "0.49423808", "0.49305415", "0.4930389", "0.4916845", "0.4914511", "0.49110997", "0.4891309", "0.48889524", "0.48875687", "0.48855442", "0.48835352", "0.48802248", "0.48782542" ]
0.8418694
0
TrimByteSuffix trims the given suffix.
func TrimByteSuffix(str string, suffix byte) string { if len(str) > 0 && str[len(str)-1] == suffix { str = str[:len(str)-1] } return str }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func TrimBytePrefix(str string, prefix byte) string {\n\tif len(str) > 0 && str[0] == prefix {\n\t\tstr = str[1:]\n\t}\n\treturn str\n}", "func TrimSuffix(suffix, operand string) string { return strings.TrimSuffix(operand, suffix) }", "func removeSuffix(value, suffix string) string {\n\treturn value[0 : len(value)-len(suffix)]\n}", "func (s *Stringish) TrimSuffix(suffix string) *Stringish {\n\ts.str = strings.TrimSuffix(s.str, suffix)\n\treturn s\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func trimSpace(b []byte) string {\n\treturn string(bytes.TrimRight(b, \" \"))\n}", "func TestTrimKafkaChannelServiceNameSuffix(t *testing.T) {\n\n\t// Test Data\n\tchannelName := \"TestChannelName\"\n\tchannelServiceName := fmt.Sprintf(\"%s-%s\", channelName, constants.KafkaChannelServiceNameSuffix)\n\n\t// Perform The Test\n\tactualResult := TrimKafkaChannelServiceNameSuffix(channelServiceName)\n\n\t// Verify The Results\n\texpectedResult := channelName\n\tassert.Equal(t, expectedResult, actualResult)\n}", "func (o BucketNotificationQueueOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationQueue) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func (o BucketNotificationTopicOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationTopic) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func TrimSuffix(suffix string) MapFunc {\n\treturn func(s string) string { return strings.TrimSuffix(s, suffix) }\n}", "func execTrimBytes(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := textproto.TrimBytes(args[0].([]byte))\n\tp.Ret(1, ret)\n}", "func (o BucketNotificationLambdaFunctionOutput) FilterSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketNotificationLambdaFunction) *string { return v.FilterSuffix }).(pulumi.StringPtrOutput)\n}", "func truncateSuffix(value string, suffix string, max int) (string, error) {\n\tvalLen := len(value)\n\tsufLen := len(suffix)\n\tif valLen+sufLen <= max {\n\t\treturn value, nil\n\t}\n\tif sufLen+1 >= max {\n\t\treturn errorMessage[0].val, fmt.Errorf(\"sufixo [%s] nao pode ser aplicado porque estoura \"+\n\t\t\t\"o tamanho maximo [%d] no elemento [%s]\", suffix, max, value)\n\t}\n\tr := []rune(value)\n\tif l := len(r); max > l {\n\t\tmax = l\n\t}\n\tfor l := max - 1; l >= 0 && r[l] == '_'; l-- {\n\t\tmax--\n\t}\n\tsafeSubstring := string(r[0:max])\n\treturn testInvalidChars(safeSubstring)\n}", "func removeByteIndex(bs []byte, idx int) {\n\tcopy(bs[idx:], bs[idx+1:])\n\tbs[len(bs)-1] = 0\n}", "func WithoutSuffix(filename string) string {\n\tsuffix := Suffix(filename)\n\tif suffix == \"\" {\n\t\treturn filename\n\t}\n\treturn filename[0 : len(filename)-len(suffix)-1]\n}", "func Remove0byte(name string) error {\n\ts, err := os.Stat(name)\n\tif errors.Is(err, fs.ErrNotExist) {\n\t\treturn nil\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"remove 0byte stat: %w\", err)\n\t}\n\tif s.Size() == 0 {\n\t\tif err := os.Remove(name); err != nil {\n\t\t\treturn fmt.Errorf(\"remove 0byte: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}", "func trimmed(bs []byte) []byte {\n\tfor i, b := range bs {\n\t\tif b == 0x00 {\n\t\t\treturn bs[:i]\n\t\t}\n\t}\n\treturn bs\n}", "func CleanSig(sigB []byte) []byte {\n\tif len(sigB) == 0 {\n\t\treturn sigB\n\t}\n\tif bytes.HasSuffix(sigB, []byte{0x1b}) {\n\t\treturn append(sigB[:len(sigB)-1], 0x00)\n\t}\n\tif bytes.HasSuffix(sigB, []byte{0x1c}) {\n\t\treturn append(sigB[:len(sigB)-1], 0x01)\n\t}\n\n\treturn sigB\n}", "func Suffix(filename string) string {\n\tname := path.Base(filename) // Make sure we only have filename, not full path\n\n\t// Many files in aspera_test have suffixes like \"mxf.xml\" or \"mov.aspx\" or similar.\n\t// We need to check the full siffix, not only the last part.\n\tindex := strings.Index(name, \".\")\n\tif index < 0 || index == len(name)-1 {\n\t\treturn \"\"\n\t}\n\treturn strings.ToLower(name[index+1:])\n}", "func trimOutPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i+len(prefix):]\n}", "func (o *SignalPersonName) SetSuffix(v string) {\n\to.Suffix.Set(&v)\n}", "func stripZone(zone string) string {\n\treturn strings.TrimRight(zone, \"abc\")\n}", "func (s *Stringish) TrimSuffixSpaces() *Stringish {\n\treturn s.TrimSuffix(\" \")\n}", "func (o *SignalPersonName) UnsetSuffix() {\n\to.Suffix.Unset()\n}", "func trim(name string) string {\n\treturn strings.TrimPrefix(name, Prefix)\n}", "func trimEOL(b []byte) []byte {\n lns := len(b)\n if lns > 0 && b[lns-1] == '\\n' {\n lns--\n if lns > 0 && b[lns-1] == '\\r' {\n lns--\n }\n }\n return b[:lns]\n}", "func (o *PostAutoDiscoveryPingsweepParams) SetStripDomainSuffix(stripDomainSuffix *string) {\n\to.StripDomainSuffix = stripDomainSuffix\n}", "func LRemoveByte(v []byte, item byte) (newPtr []byte) {\n\t_, newPtr = PopByte(v, LIndexByte(v, item))\n\treturn\n}", "func (o BucketWebsiteOutput) MainPageSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketWebsite) *string { return v.MainPageSuffix }).(pulumi.StringPtrOutput)\n}", "func (o BucketWebsiteOutput) MainPageSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v BucketWebsite) *string { return v.MainPageSuffix }).(pulumi.StringPtrOutput)\n}", "func trimChar(s string, r byte) string {\n\tsz := len(s)\n\n\tif sz > 0 && s[sz-1] == r {\n\t\ts = s[:sz-1]\n\t}\n\tsz = len(s)\n\tif sz > 0 && s[0] == r {\n\t\ts = s[1:sz]\n\t}\n\treturn s\n}", "func trimChar(s string, r byte) string {\n\tsz := len(s)\n\n\tif sz > 0 && s[sz-1] == r {\n\t\ts = s[:sz-1]\n\t}\n\tsz = len(s)\n\tif sz > 0 && s[0] == r {\n\t\ts = s[1:sz]\n\t}\n\treturn s\n}", "func trim(s []byte) []byte {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\tn := len(s)\n\tfor n > i && (s[n-1] == ' ' || s[n-1] == '\\t') {\n\t\tn--\n\t}\n\treturn s[i:n]\n}", "func trim(s []byte) []byte {\n\ti := 0\n\tfor i < len(s) && (s[i] == ' ' || s[i] == '\\t') {\n\t\ti++\n\t}\n\tn := len(s)\n\tfor n > i && (s[n-1] == ' ' || s[n-1] == '\\t') {\n\t\tn--\n\t}\n\treturn s[i:n]\n}", "func trimToPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i:]\n}", "func trimIncompleteRune(b []byte) []byte {\n\ti := len(b) - utf8.UTFMax\n\tif i < 0 {\n\t\ti = 0\n\t}\n\tlastStart := len(b)\n\tfor ; i < len(b); i++ {\n\t\tif r, n := utf8.DecodeRune(b[i:]); r != utf8.RuneError || n > 1 {\n\t\t\tlastStart = len(b)\n\t\t\tcontinue\n\t\t}\n\t\tif utf8.RuneStart(b[i]) {\n\t\t\tlastStart = i\n\t\t}\n\t}\n\treturn b[0:lastStart]\n}", "func TrimBuffToString(bytes []byte) string {\n\tfor i, b := range bytes {\n\t\tif b == 0 {\n\t\t\treturn string(bytes[:i])\n\t\t}\n\t}\n\treturn string(bytes)\n}", "func trimDot(s string) string {\n\treturn strings.Trim(s, \".\")\n}", "func (n Name) Suffix() Name {\n\tif len(n) > 0 {\n\t\treturn n[1:]\n\t}\n\treturn nil\n}", "func (o BucketWebsitePtrOutput) MainPageSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketWebsite) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MainPageSuffix\n\t}).(pulumi.StringPtrOutput)\n}", "func (o BucketWebsitePtrOutput) MainPageSuffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketWebsite) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn v.MainPageSuffix\n\t}).(pulumi.StringPtrOutput)\n}", "func TestDeleteCleanerBytes(t *testing.T) {\n\topts := deleteCleanerOptions{Name: \"foo\", Logger: noopLogger()}\n\topts.Retention.Bytes = 100\n\tcleaner := newDeleteCleaner(opts)\n\tdir := tempDir(t)\n\tdefer remove(t, dir)\n\n\tsegs := make([]*segment, 5)\n\tfor i := 0; i < 5; i++ {\n\t\tsegs[i] = createSegment(t, dir, int64(i), 20)\n\t\twriteToSegment(t, segs[i], int64(i), []byte(\"blah\"))\n\t}\n\tactual, err := cleaner.Clean(segs)\n\trequire.NoError(t, err)\n\trequire.Len(t, actual, 2)\n\trequire.Equal(t, int64(3), actual[0].BaseOffset)\n\trequire.Equal(t, int64(4), actual[1].BaseOffset)\n}", "func Suffix() string {\n\treturn std.Suffix()\n}", "func (o HybridConnectionOutput) ServiceBusSuffix() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *HybridConnection) pulumi.StringOutput { return v.ServiceBusSuffix }).(pulumi.StringOutput)\n}", "func StripHeader(b []byte) []byte {\n\tif !bytes.HasPrefix(b, frontMatterDash) {\n\t\treturn b\n\t}\n\tb = b[len(frontMatterDash):]\n\tend := bytes.Index(b, frontMatterDash)\n\tif end == -1 {\n\t\treturn b\n\t}\n\treturn b[end+len(frontMatterDash):]\n}", "func SuffixTransform(b []byte) []byte { return append([]byte(\".\"), b...) }", "func cleanBytesToString(s []byte) string {\n\treturn strings.SplitN(string(s), \"\\000\", 2)[0]\n}", "func (o BucketWebsiteResponseOutput) MainPageSuffix() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketWebsiteResponse) string { return v.MainPageSuffix }).(pulumi.StringOutput)\n}", "func Uint8ToStringHasSuffix(v string) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldUint8ToString), v))\n\t})\n}", "func BytesStripRight(s []byte, pad byte) []byte {\n\tn := len(s)\n\tfor n > 0 && s[n-1] == pad {\n\t\tn--\n\t}\n\treturn s[:n]\n}", "func (fn *FakeName) Suffix() string {\n\treturn random.PickString(fn.Suffixs)\n}", "func SuffixLen(f EncryptFunc, bs int) int {\n\treturn FixedLen(f, bs) - PrefixLen(f, bs)\n}", "func (s *Srt) TrimTo(ms uint32) int {\n\tvar deleted int = 0\n\ts.ForEach(func(_ int, sub *Subtitle) bool {\n\t\tif sub.StartMs < ms {\n\t\t\tsub.MarkAsDeleted()\n\t\t\tdeleted++\n\t\t\ts.count--\n\t\t\treturn true\n\t\t}\n\t\tsub.StartMs -= ms\n\t\tsub.EndMs -= ms\n\t\treturn true\n\t})\n\treturn deleted\n}", "func (o BucketWebsiteConfigurationV2IndexDocumentPtrOutput) Suffix() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v *BucketWebsiteConfigurationV2IndexDocument) *string {\n\t\tif v == nil {\n\t\t\treturn nil\n\t\t}\n\t\treturn &v.Suffix\n\t}).(pulumi.StringPtrOutput)\n}", "func removePrefix(s string) string {\n\tif !strings.ContainsRune(s, ':') {\n\t\treturn s\n\t}\n\treturn strings.Split(s, \":\")[1]\n}", "func TrimPrefix(prefix, operand string) string { return strings.TrimPrefix(operand, prefix) }", "func UserUploadHasSuffix(v string) predicate.Watchlist {\n\treturn predicate.Watchlist(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldUserUpload), v))\n\t})\n}", "func truncate(str string, maxByteLength int, ellipsis bool) string {\n\tif len(str) <= maxByteLength {\n\t\treturn str\n\t}\n\n\tbytes := []byte(str)\n\n\tif ellipsis && maxByteLength > 3 {\n\t\tmaxByteLength -= 3\n\t} else {\n\t\tellipsis = false\n\t}\n\n\tfor maxByteLength > 0 && maxByteLength < len(bytes) && isUTF8ContinuationByte(bytes[maxByteLength]) {\n\t\tmaxByteLength--\n\t}\n\n\tresult := string(bytes[0:maxByteLength])\n\tif ellipsis {\n\t\tresult += \"...\"\n\t}\n\n\treturn result\n}", "func BunameHasSuffix(v string) predicate.Building {\n\treturn predicate.Building(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldBuname), v))\n\t})\n}", "func LastTokenByte(s string, sep byte) string {\n\treturn s[strings.LastIndexByte(s, sep)+1:]\n}", "func TrimExtension(file FileEntry, extensions []string) (new FileEntry) {\n\tnew = file\n\tfor _, ext := range extensions {\n\t\tif file.Extension == ext {\n\t\t\tnew.Name = strings.TrimSuffix(file.Name, ext)\n\t\t\tnew.Extension = filepath.Ext(new.Name)\n\t\t}\n\t}\n\treturn\n}", "func (m *ItemItemsItemWorkbookFunctionsComplexPostRequestBody) GetSuffix()(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.Jsonable) {\n val, err := m.GetBackingStore().Get(\"suffix\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.Jsonable)\n }\n return nil\n}", "func removeZone(host string) string {\n\tif !strings.HasPrefix(host, \"[\") {\n\t\treturn host\n\t}\n\ti := strings.LastIndex(host, \"]\")\n\tif i < 0 {\n\t\treturn host\n\t}\n\tj := strings.LastIndex(host[:i], \"%\")\n\tif j < 0 {\n\t\treturn host\n\t}\n\treturn host[:j] + host[i:]\n}", "func removeZone(host string) string {\n\tif !strings.HasPrefix(host, \"[\") {\n\t\treturn host\n\t}\n\ti := strings.LastIndex(host, \"]\")\n\tif i < 0 {\n\t\treturn host\n\t}\n\tj := strings.LastIndex(host[:i], \"%\")\n\tif j < 0 {\n\t\treturn host\n\t}\n\treturn host[:j] + host[i:]\n}", "func trimCut(label []byte, maxlen int, left, right string) []byte {\n\ttrim := bytes.TrimLeft(label, left)\n\tsize := min(len(trim), maxlen)\n\thead := bytes.TrimRight(trim[:size], right)\n\tif len(head) == size {\n\t\treturn head\n\t}\n\ttail := bytes.TrimLeft(trim[size:], right)\n\tif len(tail) > 0 {\n\t\treturn append(head, tail[:min(len(tail), size-len(head))]...)\n\t}\n\treturn head\n}", "func TrimSlash(str string) string {\n\treturn TrimByteSuffix(TrimBytePrefix(str, '/'), '/')\n}", "func (o BucketWebsiteConfigurationV2IndexDocumentOutput) Suffix() pulumi.StringOutput {\n\treturn o.ApplyT(func(v BucketWebsiteConfigurationV2IndexDocument) string { return v.Suffix }).(pulumi.StringOutput)\n}", "func ByteSize(b float64) string {\n\tvar (\n\t\tunit string\n\t\tdel float64 = 1\n\t)\n\n\tswitch {\n\tcase b >= YB:\n\t\tunit = \"Y\"\n\t\tdel = YB\n\tcase b >= ZB:\n\t\tunit = \"Z\"\n\t\tdel = ZB\n\tcase b >= EB:\n\t\tunit = \"E\"\n\t\tdel = EB\n\tcase b >= PB:\n\t\tunit = \"P\"\n\t\tdel = PB\n\tcase b >= TB:\n\t\tunit = \"T\"\n\t\tdel = TB\n\tcase b >= GB:\n\t\tunit = \"G\"\n\t\tdel = GB\n\tcase b >= MB:\n\t\tunit = \"M\"\n\t\tdel = MB\n\tcase b >= KB:\n\t\tunit = \"K\"\n\t\tdel = KB\n\tcase b == 0:\n\t\treturn \"0\"\n\tdefault:\n\t\tunit = \"B\"\n\t}\n\treturn strings.TrimSuffix(\n\t\tstrconv.FormatFloat(b/del, 'f', 1, 32),\n\t\t\".0\",\n\t) + unit\n}", "func RemovePad(t []byte) []byte {\n\tpadLength := int(t[len(t)-1])\n\tfmt.Printf(\"WILL remove %d\\n\", padLength)\n\treturn t[:len(t)-padLength]\n}", "func TrimNull(in []byte) (out []byte) {\n\tvar start int\n\tfor ; start < len(in); start++ {\n\t\tif in[start] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tvar end = len(in) - 1\n\tfor ; end > start; end-- {\n\t\tif in[end] != 0 {\n\t\t\tbreak\n\t\t}\n\t}\n\tend++\n\n\treturn in[start:end]\n}", "func (rw *RWType) FmtSuffix(key string) string {\n\tif *rw == ReadAndWrite {\n\t\treturn key\n\t}\n\treturn key + \"_\" + string(*rw)\n}", "func removeZeroAtTail(str string) string {\n\ti := len(str) - 1\n\tfor ; i >= 0; i-- {\n\t\tif str[i] != '0' {\n\t\t\tbreak\n\t\t}\n\t}\n\tstr = str[:i+1]\n\t// delete \".\" at last of result\n\tif str[len(str)-1] == '.' {\n\t\tstr = str[:len(str)-1]\n\t}\n\treturn str\n}", "func removeZeroAtTail(str string) string {\n\ti := len(str) - 1\n\tfor ; i >= 0; i-- {\n\t\tif str[i] != '0' {\n\t\t\tbreak\n\t\t}\n\t}\n\tstr = str[:i+1]\n\t// delete \".\" at last of result\n\tif str[len(str)-1] == '.' {\n\t\tstr = str[:len(str)-1]\n\t}\n\treturn str\n}", "func DropOptionalHasSuffix(v string) predicate.User {\n\treturn predicate.User(sql.FieldHasSuffix(FieldDropOptional, v))\n}", "func STATUSBABYNAMEHasSuffix(v string) predicate.Babystatus {\n\treturn predicate.Babystatus(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldSTATUSBABYNAME), v))\n\t})\n}", "func trim(strn string) string {\n\treturn strings.Trim(strn, \" \\t\\n\\r\")\n}", "func truncate(in []byte) int64 {\n\toffset := int(in[len(in)-1] & 0xF)\n\tp := in[offset : offset+4]\n\tvar binCode int32\n\tbinCode = int32((p[0] & 0x7f)) << 24\n\tbinCode += int32((p[1] & 0xff)) << 16\n\tbinCode += int32((p[2] & 0xff)) << 8\n\tbinCode += int32((p[3] & 0xff))\n\treturn int64(binCode) & 0x7FFFFFFF\n}", "func trimIndex(b []byte) int {\n\tfor i := len(b) - 1; i >= 0; i-- {\n\t\tif b[i] != '0' {\n\t\t\treturn i + 1\n\t\t}\n\t}\n\treturn -1\n}", "func (p containerJSONItemRemover) MakeCleanedUpByte(dataToClean []byte) []byte {\n\tdefer func() {\n\t\tif err := recover(); err != nil {\n\t\t\tprintln(err)\n\t\t}\n\t}()\n\tif p.removedPathCount == 0 {\n\t\treturn dataToClean\n\t}\n\tvar containerX bytes.Buffer\n\tfor i := 0; i < len(dataToClean); i++ {\n\t\tif !p.removedDataIndex[i] {\n\t\t\tcontainerX.WriteByte(dataToClean[i])\n\t\t}\n\t}\n\treturn containerX.Bytes()\n}", "func stripExt(s string) string {\n\text := filepath.Ext(s)\n\tif len(ext) > 0 {\n\t\treturn s[:len(s)-len(ext)]\n\t}\n\treturn s\n}", "func (n *Name) Suffix() string {\n\t// TODO handle gender\n\treturn n.pick(namePrefix + \"/suffix\")\n}", "func Int8ToStringHasSuffix(v string) predicate.Conversion {\n\treturn predicate.Conversion(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldInt8ToString), v))\n\t})\n}", "func RemoveBytes(dest *[]byte, pos, count int) {\n\tif pos < 0 || pos >= len(*dest) {\n\t\tmod.Error(\"Position\", pos, \"out of range; len(*dest):\", len(*dest))\n\t\treturn\n\t}\n\tif count == 0 {\n\t\treturn\n\t}\n\t(*dest) = (*dest)[:pos+copy((*dest)[pos:], (*dest)[pos+count:])]\n}", "func trimTrailingWhiteSpace(s []byte) []byte {\n\tfor (len(s) > 0) && ((s[len(s)-1] == ' ') || (s[len(s)-1] == '\\t')) {\n\t\ts = s[:len(s)-1]\n\t}\n\treturn s\n}", "func (m *Immutable) Suffix() string {\n\treturn m.contained.Suffix()\n}", "func trimLast(text string) string {\n\ttextLen := len(text)\n\tif textLen == 0 {\n\t\treturn text\n\t}\n\treturn text[:textLen-1]\n}", "func TestDeleteCleanerBytesMessages(t *testing.T) {\n\topts := deleteCleanerOptions{Name: \"foo\", Logger: noopLogger()}\n\topts.Retention.Messages = 15\n\topts.Retention.Bytes = 240\n\tcleaner := newDeleteCleaner(opts)\n\tdir := tempDir(t)\n\tdefer remove(t, dir)\n\n\tsegs := make([]*segment, 20)\n\tfor i := 0; i < 20; i++ {\n\t\tsegs[i] = createSegment(t, dir, int64(i), 20)\n\t\twriteToSegment(t, segs[i], int64(i), []byte(\"blah\"))\n\t}\n\tactual, err := cleaner.Clean(segs)\n\trequire.NoError(t, err)\n\trequire.Len(t, actual, 5)\n\tfor i := 0; i < 5; i++ {\n\t\trequire.Equal(t, int64(i+15), actual[i].BaseOffset)\n\t}\n}", "func Suffix() (string, error) {\n\tslice, err := loader(\"name_suffixes\")\n\tcheckErr(err)\n\treturn random(slice), nil\n}", "func (srv *PolicyDBServer) DeleteBaseName(\n\tctx context.Context, lookup *protos.ChargingRuleBaseNameLookup,\n) (*orcprotos.Void, error) {\n\n\ttable := datastore.GetTableName(lookup.GetNetworkID().GetId(), CHARGING_RULE_BASE_NAME_TABLE)\n\tif err := srv.store.Delete(table, lookup.GetName()); err != nil {\n\t\tglog.Errorf(\"Error deleting rule %s: %s\", lookup.GetName(), err)\n\t\treturn &orcprotos.Void{}, status.Errorf(codes.Aborted, \"Deletion error!\")\n\t}\n\treturn &orcprotos.Void{}, nil\n}", "func MaxByte(s []byte) (byte, error) {\n\tif err := verifymax(s); err != nil {\n\t\treturn 0, err\n\t}\n\n\tret := s[0]\n\n\tfor _, a := range s {\n\t\tif a > ret {\n\t\t\tret = a\n\t\t}\n\t}\n\n\treturn ret, nil\n}", "func (m *ItemItemsItemWorkbookFunctionsComplexPostRequestBody) SetSuffix(value iadcd81124412c61e647227ecfc4449d8bba17de0380ddda76f641a29edf2b242.Jsonable)() {\n err := m.GetBackingStore().Set(\"suffix\", value)\n if err != nil {\n panic(err)\n }\n}", "func UniqSuffix(s string) string {\n\treturn s + \"_\" + Uniq8()\n}", "func dropExtension(path string) string {\n\textension := filepath.Ext(path)\n\treturn path[:len(path)-len(extension)]\n}", "func (o *SignalPersonName) GetSuffix() string {\n\tif o == nil || o.Suffix.Get() == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Suffix.Get()\n}", "func (tr *NormalizingTarReader) Strip(prefix string) {\n\ttr.headerOpts = append(tr.headerOpts, func(header *tar.Header) *tar.Header {\n\t\theader.Name = strings.TrimPrefix(header.Name, prefix)\n\t\treturn header\n\t})\n}", "func MednoHasSuffix(v string) predicate.Medicalfile {\n\treturn predicate.Medicalfile(func(s *sql.Selector) {\n\t\ts.Where(sql.HasSuffix(s.C(FieldMedno), v))\n\t})\n}", "func (ar *AdapterRequest) StripBasePath(basePath string) string {\n\tif strings.Trim(basePath, \" \") == \"\" {\n\t\tar.stripBasePath = \"\"\n\t\treturn \"\"\n\t}\n\n\tnewBasePath := basePath\n\tif !strings.HasPrefix(newBasePath, \"/\") {\n\t\tnewBasePath = \"/\" + newBasePath\n\t}\n\n\tif strings.HasSuffix(newBasePath, \"/\") {\n\t\tnewBasePath = newBasePath[:len(newBasePath)-1]\n\t}\n\n\tar.stripBasePath = newBasePath\n\n\treturn newBasePath\n}", "func basename2(s string) string {\n\tslash := strings.LastIndex(s, \"/\")\n\ts = s[slash+1:]\n\tif dot := strings.LastIndex(s, \".\"); dot >= 0 {\n\t\ts = s[:dot]\n\t}\n\treturn s\n}", "func (s *BasevhdlListener) ExitSuffix(ctx *SuffixContext) {}", "func fileNameWOExt(filePath string) string {\n\tfileName := filepath.Base(filePath)\n\treturn strings.TrimSuffix(fileName, filepath.Ext(fileName))\n}" ]
[ "0.75272393", "0.65279657", "0.62334776", "0.60795295", "0.5917014", "0.5917014", "0.57284635", "0.56404513", "0.5460224", "0.5442952", "0.5383099", "0.53826004", "0.53525347", "0.53358984", "0.530792", "0.5267426", "0.5265462", "0.5264854", "0.52100724", "0.51917565", "0.5191722", "0.51601166", "0.5110279", "0.5091554", "0.5089618", "0.50197875", "0.5008126", "0.49992156", "0.49833587", "0.49833587", "0.49765208", "0.49765208", "0.4976143", "0.4976143", "0.49595436", "0.49486175", "0.49451074", "0.49181914", "0.49128354", "0.48986432", "0.48986432", "0.48977846", "0.4867912", "0.48601583", "0.48599964", "0.4852881", "0.48443806", "0.48434663", "0.48055068", "0.480404", "0.48027855", "0.4794356", "0.4786469", "0.47835112", "0.4764656", "0.4762675", "0.47551712", "0.47393906", "0.47278216", "0.47179118", "0.46993575", "0.46933588", "0.4688123", "0.4688123", "0.46875337", "0.46811616", "0.46802965", "0.4678803", "0.46473247", "0.46391687", "0.46378744", "0.46248257", "0.46248257", "0.46213838", "0.46176633", "0.46173376", "0.46159965", "0.4614585", "0.4613465", "0.461177", "0.46069175", "0.46018746", "0.46014306", "0.4591779", "0.4589445", "0.45860505", "0.45837745", "0.4583493", "0.45813274", "0.457149", "0.4559524", "0.45423684", "0.45385244", "0.45326254", "0.4528902", "0.45261395", "0.4525988", "0.45148513", "0.45132065", "0.45053026" ]
0.85977143
0
TrimSlash trims '/' from the given string.
func TrimSlash(str string) string { return TrimByteSuffix(TrimBytePrefix(str, '/'), '/') }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func stripSlash(str string) string {\n\treturn strings.TrimRight(strings.TrimLeft(str, \"/\"), \"/\")\n}", "func StripSlash(str string) string {\n\tre := regexp.MustCompile(\"/+$\")\n\treturn re.ReplaceAllString(str, \"\")\n}", "func TrimSlashes(c string) string {\n\treturn strings.TrimSuffix(strings.TrimPrefix(cleanPath(c), \"/\"), \"/\")\n}", "func trimLeftSlash(name string) string {\n\treturn strings.TrimPrefix(name, \"/\")\n}", "func RemoveFirstSlash(s string) string {\n\treturn slashes.ReplaceAllString(s, \"\")\n}", "func slashClean(name string) string {\n\tif name == \"\" || name[0] != '/' {\n\t\tname = \"/\" + name\n\t}\n\treturn path.Clean(name)\n}", "func removeTrailingSlash(path string) string {\n\treturn strings.TrimRight(path, \"/\")\n}", "func StripSlashes(str string) string {\n\tvar buf bytes.Buffer\n\tl, skip := len(str), false\n\tfor i, char := range str {\n\t\tif skip {\n\t\t\tskip = false\n\t\t} else if char == '\\\\' {\n\t\t\tif i+1 < l && str[i+1] == '\\\\' {\n\t\t\t\tskip = true\n\t\t\t}\n\t\t\tcontinue\n\t\t}\n\t\tbuf.WriteRune(char)\n\t}\n\treturn buf.String()\n}", "func RemoveStartingSlash(dir string) string {\n\treturn strings.TrimLeft(dir, string(os.PathSeparator))\n}", "func TrimmedPath(fullPath string) string {\n\t// nb. To make sure we trim the path correctly on Windows too, we\n\t// counter-intuitively need to use '/' and *not* os.PathSeparator here,\n\t// because the path given originates from Go stdlib, specifically\n\t// runtime.Caller() which (as of Mar/17) returns forward slashes even on\n\t// Windows.\n\t//\n\t// See https://github.com/golang/go/issues/3335\n\t// and https://github.com/golang/go/issues/18151\n\t//\n\t// for discussion on the issue on Go side.\n\t//\n\t// Find the last separator.\n\t//\n\tidx := strings.LastIndexByte(fullPath, '/')\n\tif idx == -1 {\n\t\treturn fullPath\n\t}\n\t// Find the penultimate separator.\n\tidx = strings.LastIndexByte(fullPath[:idx], '/')\n\tif idx == -1 {\n\t\treturn fullPath\n\t}\n\treturn fullPath[idx+1:]\n}", "func StripSlashes(s string) string {\n\tvar buf bytes.Buffer\n\n\tl, skip := len(s), false\n\n\tfor i, ch := range s {\n\t\tif skip {\n\t\t\tbuf.WriteRune(ch)\n\t\t\tskip = false\n\n\t\t\tcontinue\n\t\t}\n\n\t\tif ch == '\\\\' {\n\t\t\tif i+1 < l && s[i+1] == '\\\\' {\n\t\t\t\tskip = true\n\t\t\t}\n\n\t\t\tcontinue\n\t\t}\n\n\t\tbuf.WriteRune(ch)\n\t}\n\n\treturn buf.String()\n}", "func RemoveTrailingSlash(s string) string {\n\tre := regexp.MustCompile(`/$`)\n\treturn re.ReplaceAllString(s, \"\")\n}", "func trimPathAfterLastSlash(path string) string {\n\tif index := strings.LastIndex(path, \"/\"); index != -1 {\n\t\t// fmt.Println(path, \" Trimmed =\", path[:index])\n\t\treturn path[:index] //remove including the last /\n\t}\n\tfmt.Println(\"Failed to trim strings after last '/'\")\n\treturn path\n}", "func CleanSlashes(p string) string {\n\treturn MoreSlashes.ReplaceAllString(filepath.ToSlash(p), \"/\")\n}", "func RemoveTrailingSlash(path string) string {\n\tif len(path) > 1 && strings.HasSuffix(path, \"/\") {\n\t\treturn path[:len(path)-1]\n\t}\n\treturn path\n}", "func StripSlashes(s string) string {\n\tout := make([]byte, 0, len(s)) // might be more than we need, but no reallocs\n\tfor i := 0; i < len(s); i++ {\n\t\tif s[i] == '\\\\' && i < len(s)-1 {\n\t\t\tswitch s[i+1] {\n\t\t\tcase '.', '_', '-': // these pass unquoted\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tout = append(out, byte(s[i]))\n\t}\n\treturn string(out)\n}", "func NormalizeSlashes(path string) string {\n\tpath = strings.ReplaceAll(path, `/`, string(os.PathSeparator))\n\tpath = strings.ReplaceAll(path, `\\`, string(os.PathSeparator))\n\treturn path\n}", "func normalizePath(s string) string {\n\tif s == \"/\" {\n\t\treturn \"\"\n\t}\n\treturn s\n}", "func Clean(pathStr string) string {\n\tif pathStr == \"\" {\n\t\treturn \"\"\n\t}\n\tpath := []byte(pathStr)\n\tbuf := new(bytes.Buffer)\n\tbuf.Grow(len(path))\n\tbuf.WriteByte(path[0])\n\tfor i := 1; i < len(path); i++ {\n\t\tif path[i] == '/' && path[i-1] == '/' {\n\t\t\t// skip\n\t\t} else if path[i] == '.' && path[i-1] == '/' && i+1 < len(path) && path[i+1] == '/' {\n\t\t\t// skip 2 bytes\n\t\t\ti++\n\t\t} else {\n\t\t\tbuf.WriteByte(path[i])\n\t\t}\n\t}\n\tres := buf.String()\n\tif pathStr == res {\n\t\treturn pathStr\n\t} else {\n\t\treturn res\n\t}\n}", "func Unnormalize(path string) string {\n\treturn filepath.FromSlash(path)\n}", "func Trim(str string) string {\n\treturn strings.Trim(str, \" \")\n}", "func (util copyHandlerUtil) replaceBackSlashWithSlash(urlStr string) string {\n\tstr := strings.Replace(urlStr, \"\\\\\", \"/\", -1)\n\n\treturn str\n}", "func slash(prefix string) string {\n\tprefix = strings.TrimSpace(prefix)\n\tif prefix == \"\" || prefix == \"/\" {\n\t\treturn \"/\"\n\t}\n\tif prefix[0] != '/' {\n\t\tif prefix[len(prefix)-1] == '/' {\n\t\t\treturn \"/\" + prefix[:len(prefix)-1]\n\t\t}\n\t\treturn \"/\" + prefix\n\t}\n\tif prefix[len(prefix)-1] == '/' {\n\t\treturn prefix[:len(prefix)-1]\n\t}\n\treturn prefix\n}", "func DenormalizeSlashes(path string) string {\n\tpath = strings.ReplaceAll(path, `\\`, `/`)\n\treturn path\n}", "func (URI) CleanPath(path string) string {\n\treturn \"/\" + strings.TrimPrefix(path, \"/\")\n}", "func normalizePath(s string) string {\n\tseparator := \"/\"\n\tif !strings.HasPrefix(s, separator) {\n\t\ts = separator + s\n\t}\n\n\tif len(s) > 1 && strings.HasSuffix(s, separator) {\n\t\ts = s[:len(s)-1]\n\t}\n\treturn s\n}", "func Trim(str string) string {\n\treturn strings.TrimSpace(str)\n}", "func RemoveTrailingSlash(dir string) string {\n\treturn strings.TrimRight(dir, string(os.PathSeparator))\n}", "func Clean(path string, leading bool) string {\n\tpath = filepath.Clean(path)\n\t// path returns '.' if the result of the Clean was an empty string.\n\tif path == \".\" {\n\t\treturn \"\"\n\t}\n\n\tif leading {\n\t\tpath = strings.TrimPrefix(path, \"/\")\n\t}\n\n\treturn path\n}", "func clean(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\n\tnp := path.Clean(p)\n\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\t// Fast path for common case of p being the string we want:\n\t\tif len(p) == len(np)+1 && strings.HasPrefix(p, np) {\n\t\t\tnp = p\n\t\t} else {\n\t\t\tnp += \"/\"\n\t\t}\n\t}\n\n\treturn np\n}", "func cleanString(s string) string {\n\ts = strings.TrimPrefix(s, \"\\\"\")\n\ts = strings.TrimSuffix(s, \"\\\"\")\n\treturn s\n}", "func StripBasepath(p string) string {\n\tbp := Basepath()\n\treturn strings.TrimPrefix(p, bp+string(os.PathSeparator))\n}", "func Trim(chars string, operand string) string { return strings.Trim(operand, chars) }", "func normalizePathSeparator(path string) string {\n\treturn strings.ReplaceAll(path, string(os.PathSeparator), \"/\")\n}", "func normalizeStr(str string) string {\n\treturn strings.Replace(str, \"/\", \"-\", -1)\n}", "func cleanPath(p string, mode TrailingSlashMode) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\n\tswitch mode {\n\tcase Add:\n\t\tif np[len(np)-1] != '/' {\n\t\t\tnp += \"/\"\n\t\t}\n\tcase Remove:\n\t\tif len(np) > 1 && np[len(np)-1] == '/' {\n\t\t\tnp = np[:len(np)-1]\n\t\t}\n\t}\n\treturn np\n}", "func TrimVendorPath(s string) string {\n\tif strings.Contains(s, \"/vendor/\") {\n\t\tif s[:1] == \"*\" {\n\t\t\treturn \"*\" + strings.Split(s, \"/vendor/\")[1]\n\t\t}\n\t\treturn strings.Split(s, \"/vendor/\")[1]\n\t}\n\treturn s\n}", "func SanitizeRoute(path string) string {\n\treturn strings.Trim(path, \"/\")\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\t// Fast path for common case of p being the string we want:\n\t\tif len(p) == len(np)+1 && strings.HasPrefix(p, np) {\n\t\t\tnp = p\n\t\t} else {\n\t\t\tnp += \"/\"\n\t\t}\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\t// Fast path for common case of p being the string we want:\n\t\tif len(p) == len(np)+1 && strings.HasPrefix(p, np) {\n\t\t\tnp = p\n\t\t} else {\n\t\t\tnp += \"/\"\n\t\t}\n\t}\n\treturn np\n}", "func Trim(str, chars string) string {\n\treturn LeftTrim(RightTrim(str, chars), chars)\n}", "func Normalize(path string) string {\n\treturn filepath.Clean(filepath.ToSlash(path))\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func cleanPath(p string) string {\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\tif p[0] != '/' {\n\t\tp = \"/\" + p\n\t}\n\tnp := path.Clean(p)\n\t// path.Clean removes trailing slash except for root;\n\t// put the trailing slash back if necessary.\n\tif p[len(p)-1] == '/' && np != \"/\" {\n\t\tnp += \"/\"\n\t}\n\treturn np\n}", "func trimRight(s string) string {\n\treturn strings.TrimRightFunc(s, unicode.IsSpace)\n}", "func StrTrim(s string) string {\n\treturn strings.TrimSpace(s)\n}", "func TrimPrefixPath(prefix string, path string) string {\n\treturn strings.TrimPrefix(path, prefix)\n}", "func TrimSpace(operand string) string { return strings.TrimSpace(operand) }", "func ScanlineTrim() string {\n\treturn strings.TrimSpace(Scanline())\n}", "func trimS(s string) string {\r\n\treturn strings.TrimSpace(s)\r\n}", "func URLPathClean(urlPath string) string {\n\tflag := strings.HasSuffix(urlPath, \"/\")\n\tstr := path.Clean(fmt.Sprintf(\"/%s\", urlPath))\n\tif flag && str != \"/\" {\n\t\treturn fmt.Sprintf(\"%s/\", str)\n\t}\n\treturn str\n}", "func Trim(text string) string {\n\treturn trimRx.FindStringSubmatch(text)[1]\n}", "func (s *Str) Trim(cutset string) *Str {\n\ts.val = strings.Trim(s.val, cutset)\n\treturn s\n}", "func clean(name string) string {\n\tname = strings.Trim(name, \"/\")\n\tname = filepath.Clean(name)\n\tif name == \".\" || name == \"/\" {\n\t\tname = \"\"\n\t}\n\treturn name\n}", "func trimToPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i:]\n}", "func trimWhitespaces(value string) string {\n\treturn strings.Trim(value, \"\")\n}", "func (ix *Search) nicelyTrimPath(fn []byte, cut int) string {\n\t// Adjust for leading / after cutting.\n\tif cut > 0 && fn[cut] == filepath.Separator && cut < len(fn) {\n\t\tcut++\n\t}\n\tcutstring := fn[cut:]\n\ttrimstring := ix.trimmer(fn)\n\tif len(cutstring) < len(trimstring) {\n\t\treturn \".../\" + string(cutstring)\n\t}\n\treturn \".../\" + string(trimstring)\n}", "func trim(strn string) string {\n\treturn strings.Trim(strn, \" \\t\\n\\r\")\n}", "func Strip(str string) string {\n\treturn regexp.MustCompile(`^\\s+|\\s+$`).ReplaceAllString(str, \"\")\n}", "func TrimPrefix(prefix, operand string) string { return strings.TrimPrefix(operand, prefix) }", "func CleanPrefix(prefix string) string {\n\trunes := []rune(prefix)\n\tif len(runes) == 0 {\n\t\treturn prefix\n\t}\n\t// Trim duplicate leading slash(es).\n\tif runes[0] == '/' {\n\t\tfor len(runes) > 1 && runes[1] == '/' {\n\t\t\trunes = runes[1:]\n\t\t}\n\t}\n\t// Trim trailing slash(es).\n\tfor len(runes) > 0 && runes[len(runes)-1] == '/' {\n\t\trunes = runes[:len(runes)-1]\n\t}\n\t// Were there nothing but slashes?\n\tif len(runes) == 0 {\n\t\treturn \"\"\n\t}\n\t// Build a properly formatted string.\n\tvar b strings.Builder\n\tif runes[0] != '/' {\n\t\tb.Grow(len(runes) + 1)\n\t\tb.WriteRune('/')\n\t} else {\n\t\tb.Grow(len(runes))\n\t}\n\tfor _, r := range runes {\n\t\tb.WriteRune(r)\n\t}\n\treturn b.String()\n}", "func trim(name string) string {\n\treturn strings.TrimPrefix(name, Prefix)\n}", "func trim(s string) string {\n\tfor len(s) > 0 {\n\t\tif s[0] <= ' ' {\n\t\t\ts = s[1:]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\tfor len(s) > 0 {\n\t\tif s[len(s)-1] <= ' ' {\n\t\t\ts = s[:len(s)-1]\n\t\t\tcontinue\n\t\t}\n\t\tbreak\n\t}\n\treturn s\n}", "func CleanDir(o string) string {\n\to = strings.TrimSuffix(o, \"\\n\")\n\to = strings.TrimSuffix(o, \"\\r\")\n\to = strings.TrimSuffix(o, \"\\\"\")\n\to = strings.TrimPrefix(o, \"\\\"\")\n\treturn o\n}", "func TrimBase(r *http.Request, prefix string) string {\n\treturn strings.TrimPrefix(r.URL.Path, AddBase(prefix))\n}", "func CleanString(str string, unescape bool) string {\n\tif unescape {\n\t\tstr = html.UnescapeString(str)\n\t}\n\tstr = strings.Replace(str, \"\\n\", \"\", -1)\n\tstr = strings.Replace(str, \"\\r\", \"\", -1)\n\treturn strings.TrimFunc(str, unicode.IsSpace)\n}", "func (ar *AdapterRequest) StripBasePath(basePath string) string {\n\tif strings.Trim(basePath, \" \") == \"\" {\n\t\tar.stripBasePath = \"\"\n\t\treturn \"\"\n\t}\n\n\tnewBasePath := basePath\n\tif !strings.HasPrefix(newBasePath, \"/\") {\n\t\tnewBasePath = \"/\" + newBasePath\n\t}\n\n\tif strings.HasSuffix(newBasePath, \"/\") {\n\t\tnewBasePath = newBasePath[:len(newBasePath)-1]\n\t}\n\n\tar.stripBasePath = newBasePath\n\n\treturn newBasePath\n}", "func pkgPathStdStrip(path string) string {\n\treturn strings.TrimPrefix(path, \"std/\")\n}", "func getCleanPath(r *http.Request) string {\n\tpath := r.URL.Path\n\tif strings.HasPrefix(path, \"/\") {\n\t\tpath = path[1:]\n\t}\n\tif strings.HasSuffix(path, \"/\") {\n\t\tpath = path[:len(path)-1]\n\t}\n\treturn path\n}", "func Canonicalize(nsPath string) string {\n\tif nsPath == \"\" {\n\t\treturn \"\"\n\t}\n\n\t// Canonicalize the path to not have a '/' prefix\n\tnsPath = strings.TrimPrefix(nsPath, \"/\")\n\n\t// Canonicalize the path to always having a '/' suffix\n\tif !strings.HasSuffix(nsPath, \"/\") {\n\t\tnsPath += \"/\"\n\t}\n\n\treturn nsPath\n}", "func filterTrim(ctx stick.Context, val stick.Value, args ...stick.Value) stick.Value {\n\treturn strings.TrimSpace(stick.CoerceString(val))\n}", "func unixPath(s string) string {\n\ts = filepath.Clean(s)\n\ts = strings.Replace(s, \"\\\\\", \"/\", -1)\n\n\t// Duplicate clean for trailing slashes that were previously windows ones.\n\treturn filepath.Clean(s)\n}", "func TrimString(s string) string {\n\treturn replacer.Replace(s)\n}", "func NormalizePath(path string) (object string) {\n if strings.HasSuffix(path, \"/\") {\n path = path + \"index.html\"\n }\n return strings.TrimLeft(path, \"/\")\n}", "func (p *Parser) Trim(input string) string {\n\tt := strings.Replace(strings.Replace(input, \"<output>\", \"\", -1), \"</output>\", \"\", -1)\n\tt1 := strings.Replace(strings.Replace(t, \"<configuration-information>\", \"\", -1), \"</configuration-information>\", \"\", -1)\n\treturn strings.Replace(strings.Replace(t1, \"<configuration-output>\", \"\", -1), \"</configuration-output>\", \"\", -1)\n}", "func CleanPath(path string) string {\n\tparts := strings.Split(path, \"/\")\n\tvar out []string\n\tfor i := range parts {\n\t\tif parts[i] == \"\" || baseIdRegex.MatchString(parts[i]) {\n\t\t\tcontinue // assume it's a moov/base.ID() value\n\t\t}\n\t\tout = append(out, parts[i])\n\t}\n\treturn strings.Join(out, \"-\")\n}", "func TrimRight(cutset string, operand string) string { return strings.TrimRight(operand, cutset) }", "func addSlash(s string) string {\n\tif s != \"\" && !strings.HasSuffix(s, \"/\") {\n\t\ts += \"/\"\n\t}\n\treturn s\n}", "func sanitisePath(path string) string {\n\t// re := regexp.MustCompile(`\\s+`)\n\t// return re.ReplaceAllString(path, ``)\n\treturn path\n}", "func Trim(str string, characterMask ...string) string {\n\ttrimChars := DefaultTrimChars\n\tif len(characterMask) > 0 {\n\t\ttrimChars += characterMask[0]\n\t}\n\treturn strings.Trim(str, trimChars)\n}", "func trimDot(s string) string {\n\treturn strings.Trim(s, \".\")\n}", "func EscapeSlash(s string) string {\n\treturn strings.Replace(s, \"/\", \"_\", -1)\n}", "func CleanUrl(p string) string {\n\t// Turn empty string into \"/\"\n\tif p == \"\" {\n\t\treturn \"/\"\n\t}\n\n\tn := len(p)\n\tvar buf []byte\n\n\t// Invariants:\n\t// reading from path; r is index of next byte to process.\n\t// writing to buf; w is index of next byte to write.\n\n\t// path must start with '/'\n\tr := 1\n\tw := 1\n\n\tif p[0] != '/' {\n\t\tr = 0\n\t\tbuf = make([]byte, n+1)\n\t\tbuf[0] = '/'\n\t}\n\n\ttrailing := n > 2 && p[n-1] == '/'\n\n\t// A bit more clunky without a 'lazybuf' like the path package, but the loop\n\t// gets completely inlined (bufApp). So in contrast to the path package this\n\t// loop has no expensive function calls (except 1x make)\n\n\tfor r < n {\n\t\tswitch {\n\t\tcase p[r] == '/':\n\t\t\t// empty path element, trailing slash is added after the end\n\t\t\tr++\n\n\t\tcase p[r] == '.' && r+1 == n:\n\t\t\ttrailing = true\n\t\t\tr++\n\n\t\tcase p[r] == '.' && p[r+1] == '/':\n\t\t\t// . element\n\t\t\tr++\n\n\t\tcase p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):\n\t\t\t// .. element: remove to last /\n\t\t\tr += 2\n\n\t\t\tif w > 1 {\n\t\t\t\t// can backtrack\n\t\t\t\tw--\n\n\t\t\t\tif buf == nil {\n\t\t\t\t\tfor w > 1 && p[w] != '/' {\n\t\t\t\t\t\tw--\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tfor w > 1 && buf[w] != '/' {\n\t\t\t\t\t\tw--\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\tdefault:\n\t\t\t// real path element.\n\t\t\t// add slash if needed\n\t\t\tif w > 1 {\n\t\t\t\tbufApp(&buf, p, w, '/')\n\t\t\t\tw++\n\t\t\t}\n\n\t\t\t// copy element\n\t\t\tfor r < n && p[r] != '/' {\n\t\t\t\tbufApp(&buf, p, w, p[r])\n\t\t\t\tw++\n\t\t\t\tr++\n\t\t\t}\n\t\t}\n\t}\n\n\t// re-append trailing slash\n\tif trailing && w > 1 {\n\t\tbufApp(&buf, p, w, '/')\n\t\tw++\n\t}\n\n\tif buf == nil {\n\t\treturn p[:w]\n\t}\n\treturn string(buf[:w])\n}", "func CleanPath(path string) string {\n\tresult := path\n\n\tif IsWindows() {\n\t\tresult = strings.Replace(result, \"/\", string(filepath.Separator), -1)\n\t} else {\n\t\tresult = strings.Replace(result, \"\\\\\", string(filepath.Separator), -1)\n\t}\n\n\tp := strings.Index(result, \"~\")\n\n\tif p != -1 {\n\t\tuserHomeDir := \"\"\n\n\t\tusr, err := user.Current()\n\t\tif !Error(err) {\n\t\t\tuserHomeDir = usr.HomeDir\n\t\t}\n\n\t\tresult = strings.Replace(result, \"~\", userHomeDir, -1)\n\t}\n\n\tresult = filepath.Clean(result)\n\n\tif !filepath.IsAbs(result) && !strings.HasPrefix(result, string(filepath.Separator)) {\n\t\tvar dir string\n\t\tvar err error\n\n\t\tif IsRunningInteractive() || strings.HasPrefix(path, \".\"+string(filepath.Separator)) {\n\t\t\tdir, err = os.Getwd()\n\t\t} else {\n\t\t\tdir, err = os.Executable()\n\t\t\tif err == nil {\n\t\t\t\tdir = filepath.Dir(dir)\n\t\t\t}\n\t\t}\n\n\t\tif !Error(err) {\n\t\t\tresult = filepath.Join(dir, result)\n\t\t}\n\t}\n\n\tr := strings.NewReplacer(\"\\\"\", \"\")\n\tresult = r.Replace(result)\n\n\tDebugFunc(\"%s -> %s\", path, result)\n\n\treturn result\n}", "func RightTrim(str, chars string) string {\n\tif chars == \"\" {\n\t\treturn strings.TrimRightFunc(str, unicode.IsSpace)\n\t}\n\tr, _ := regexp.Compile(\"[\" + chars + \"]+$\")\n\treturn r.ReplaceAllString(str, \"\")\n}", "func ensureFinalSlash(s string) string {\n\tif s[len(s)-1] != '/' {\n\t\treturn s + \"/\"\n\t} else {\n\t\treturn s\n\t}\n}", "func trimOutPrefix(str, prefix string) string {\n\ti := strings.Index(str, prefix)\n\tif i < 0 {\n\t\treturn str\n\t}\n\treturn str[i+len(prefix):]\n}", "func uniformPathSeparator(path string) string {\n\treturn strings.Replace(path, string(os.PathSeparator), \"/\", -1)\n}", "func chopPath(original string) string {\n\ti := strings.LastIndex(original, \"/\")\n\tif i == -1 {\n\t\treturn original\n\t} else {\n\t\treturn original[i+1:]\n\t}\n}", "func chopPath(original string) string {\n\ti := strings.LastIndex(original, \"/\")\n\tif i == -1 {\n\t\treturn original\n\t} else {\n\t\treturn original[i+1:]\n\t}\n}", "func chopPath(original string) string {\n\ti := strings.LastIndex(original, \"/\")\n\tif i == -1 {\n\t\treturn original\n\t} else {\n\t\treturn original[i+1:]\n\t}\n}", "func cleanGlobPath(path string) string {\n\tswitch path {\n\tcase \"\":\n\t\treturn \".\"\n\tcase string(os.PathSeparator):\n\t\t// do nothing to the path\n\t\treturn path\n\tdefault:\n\t\treturn path[0 : len(path)-1] // chop off trailing separator\n\t}\n}", "func trimChar(s string, r byte) string {\n\tsz := len(s)\n\n\tif sz > 0 && s[sz-1] == r {\n\t\ts = s[:sz-1]\n\t}\n\tsz = len(s)\n\tif sz > 0 && s[0] == r {\n\t\ts = s[1:sz]\n\t}\n\treturn s\n}", "func trimChar(s string, r byte) string {\n\tsz := len(s)\n\n\tif sz > 0 && s[sz-1] == r {\n\t\ts = s[:sz-1]\n\t}\n\tsz = len(s)\n\tif sz > 0 && s[0] == r {\n\t\ts = s[1:sz]\n\t}\n\treturn s\n}" ]
[ "0.83036447", "0.7541993", "0.72058094", "0.6963537", "0.66912746", "0.6626891", "0.6591766", "0.6483731", "0.6461355", "0.62691474", "0.62558085", "0.6188878", "0.6101457", "0.61000466", "0.60843986", "0.6016302", "0.5976401", "0.58540845", "0.57638466", "0.5760629", "0.5757308", "0.5745602", "0.57444036", "0.57186997", "0.5716802", "0.5710182", "0.5700604", "0.56906736", "0.5677207", "0.5671469", "0.5654065", "0.5592588", "0.55696905", "0.5566244", "0.5557872", "0.5542088", "0.5518696", "0.5513573", "0.5488203", "0.5488203", "0.5487648", "0.54717016", "0.5452613", "0.54501706", "0.54501706", "0.54501706", "0.54501706", "0.54501706", "0.54501706", "0.54501706", "0.54447657", "0.5423406", "0.54066277", "0.5339828", "0.53371155", "0.53346926", "0.5313339", "0.53038526", "0.5275384", "0.5270533", "0.5227899", "0.52203906", "0.5201264", "0.52005714", "0.5184035", "0.51827306", "0.51825726", "0.5180897", "0.5180559", "0.51704526", "0.5159263", "0.5135727", "0.51272064", "0.5125876", "0.5116805", "0.5108364", "0.5089642", "0.50841045", "0.5079493", "0.5061779", "0.50606644", "0.50602806", "0.50546664", "0.50543153", "0.505285", "0.50506693", "0.5046281", "0.5044619", "0.5041806", "0.5033194", "0.5022799", "0.5020996", "0.5007507", "0.5001256", "0.4990108", "0.4990108", "0.4990108", "0.49862668", "0.4982873", "0.4982873" ]
0.86231494
0
Call with: printring []
func main () { if len(os.Args) < 2 { fmt.Println("To few args") os.Exit(1) } rem := os.Args[1] port := "1075" if len(os.Args) == 3 { port = os.Args[2] } address, err := exec.Command("hostname", "-I").Output() checkError(err, 901) adres := strings.Fields(string(address)) addr := "" for i:=0; i < len(adres); i++ { if adres[i][0:3] == "172" { addr = adres[i] } } fmt.Println("My IP: ", addr) service := addr + ":12500" src, err := net.ResolveUDPAddr("udp", service) checkError(err, 902) service = rem + ":" + port nod, err := net.ResolveUDPAddr("udp", service) checkError(err, 903) var msg Message msg.Idx = 04 msg.Key = "" msg.Src = src msg.Dst = nod conn, err := net.DialUDP("udp", nil, nod) checkError(err, 904) defer conn.Close() buffer, err := json.Marshal(msg) checkError(err, 905) // fmt.Println("Sending: ", buffer[0:]) _, err = conn.Write(buffer) checkError(err, 906) localAddr, err := net.ResolveUDPAddr("udp", ":12500") checkError(err, 907) conn, err = net.ListenUDP("udp", localAddr) checkError(err, 908) for { answ := waitForRec(conn) if answ.Key == "" { conn.Close() break } nBigInt := big.Int{} nBigInt.SetString(answ.Key, 16) // fmt.Printf("%s %s\n", answ.Key, nBigInt.String()) fmt.Printf("%s ", answ.Key) fmt.Println(" ", answ.Src) } conn.Close() }
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "func myFunction1(param [10]int){\n\tfmt.Println(param)\n}", "func argsFn(args ...OBJ) OBJ {\n\tl := len(os.Args[1:])\n\tresult := make([]OBJ, l)\n\tfor i, txt := range os.Args[1:] {\n\t\tresult[i] = &object.String{Value: txt}\n\t}\n\treturn &object.Array{Elements: result}\n}", "func (s *BaseAspidaListener) EnterStr_array(ctx *Str_arrayContext) {}", "func main() {\n\tfmt.Println(\"this is the one: \", list(10))\n}", "func (a *Array) Literal() {}", "func (p *printer) Array(element string) {\n\tp.Formatter.Array(element)\n}", "func main() {\n\n\tvar a [10]string // the element is initialized with zero value\n\ta[0] = \"hello\"\n\ta[1] = \"world\"\n\tfmt.Println(a)\n\tfmt.Println(a[0])\n\tfmt.Println(a[1])\n}", "func createList(arg string) []string {\n\tvar retObject = []string{arg}\n\treturn retObject\n}", "func (c *Center) CallWithStrings(name string, args []string) (interface{}, error) {\n\ta := \"\"\n\tlast := len(args) - 1\n\tfor i, v := range args {\n\t\tif i == last {\n\t\t\ta += v\n\t\t\tbreak\n\t\t}\n\t\ta += v + \",\"\n\t}\n\tv := fmt.Sprintf(`{\"Name\":\"%s\",\"Args\":[%s]}`, name, a)\n\treturn c.CallWithJson([]byte(v))\n}", "func stringList(args ...interface{}) []string {\n\tvar x []string\n\tfor _, arg := range args {\n\t\tswitch arg := arg.(type) {\n\t\tcase []string:\n\t\t\tx = append(x, arg...)\n\t\tcase string:\n\t\t\tx = append(x, arg)\n\t\tdefault:\n\t\t\tpanic(\"stringList: invalid argument\")\n\t\t}\n\t}\n\treturn x\n}", "func execNewSlice(_ int, p *gop.Context) {\n\targs := p.GetArgs(1)\n\tret := types.NewSlice(args[0].(types.Type))\n\tp.Ret(1, ret)\n}", "func test(s []string) { // Passing by pointer\n\ts[2] = \"c\"\n}", "func Arr(args ...interface{}) []interface{} {\n\treturn args\n}", "func ctySliceToStringSlice(args []cty.Value) ([]string, error) {\n\tvar out []string\n\tfor _, arg := range args {\n\t\tif arg.Type() != cty.String {\n\t\t\treturn nil, errors.WithStackTrace(InvalidParameterType{Expected: \"string\", Actual: arg.Type().FriendlyName()})\n\t\t}\n\t\tout = append(out, arg.AsString())\n\t}\n\treturn out, nil\n}", "func Array(args ...interface{}) []interface{} {\n\treturn []interface{}{args}\n}", "func (s *BaseSyslParserListener) EnterArray_of_strings(ctx *Array_of_stringsContext) {}", "func (arg StringArg) Compile() []string {\n\treturn []string{fmt.Sprintf(\"%s=%s\", arg.Name, quote(arg.Default))}\n}", "func (p appendStringInstr) Call(pkg *Package, args []*Element, flags InstrFlags, src ast.Node) (ret *Element, err error) {\n\tif len(args) == 2 && flags != 0 {\n\t\tif t, ok := args[0].Type.(*types.Slice); ok {\n\t\t\tif elem, ok := t.Elem().(*types.Basic); ok && elem.Kind() == types.Byte {\n\t\t\t\tif v, ok := args[1].Type.(*types.Basic); ok {\n\t\t\t\t\tif v.Kind() == types.String || v.Kind() == types.UntypedString {\n\t\t\t\t\t\treturn &Element{\n\t\t\t\t\t\t\tVal: &ast.CallExpr{\n\t\t\t\t\t\t\t\tFun: identAppend,\n\t\t\t\t\t\t\t\tArgs: []ast.Expr{args[0].Val, args[1].Val},\n\t\t\t\t\t\t\t\tEllipsis: 1,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tType: t,\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, syscall.EINVAL\n}", "func addName(z []string) {\n\tz[0] = \"John\"\n\tfmt.Println(z) //[John]\n}", "func statStr(a [][]string, args ...interface{}) [][]string {\n\ts := make([]string, 0)\n\tfor _, arg := range args {\n\t\ts = append(s, fmt.Sprintf(\"%v\", arg))\n\t}\n\treturn append(a, s)\n}", "func Nop(_ string, _ ...interface{}) {}", "func arglist(s, n int) string {\n\tvar l string\n\tfor i := 0; i < n; i++ {\n\t\tif i > 0 {\n\t\t\tl += fmt.Sprintf(\", $%d\", s+i)\n\t\t} else {\n\t\t\tl += fmt.Sprintf(\"$%d\", s+i)\n\t\t}\n\t}\n\treturn l\n}", "func (l Line) ArgumentsAsSlice() []string {\n\t// TODO Implement ArgumentsAsSlice\n\treturn nil\n}", "func severalStrings(strings ...string) {\n\tfmt.Println(strings)\n}", "func args(s *scanner, token string) []string {\n\ttoken = strings.TrimSpace(token)\n\n\tvar parts []string\n\tfor {\n\t\tif !strings.ContainsAny(token, \"[]\") {\n\t\t\tfor _, part := range strings.Split(token, \",\") {\n\t\t\t\tif part == \"\" || part == \" \" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tparts = append(parts, part)\n\t\t\t}\n\t\t\tbreak\n\t\t}\n\n\t\tstart := strings.Index(token, \"[\")\n\t\tend := strings.Index(token, \"]\")\n\t\tif end < start {\n\t\t\ts.Fatalf(\"malformed input: ']' appearing before '[' in %q\", token)\n\t\t}\n\n\t\tif len(token[:start]) > 0 { // capture elems before array\n\t\t\ttoken = strings.TrimSuffix(token, \",\")\n\t\t\tfor _, part := range strings.Split(token[:start], \",\") {\n\t\t\t\tif part == \"\" || part == \" \" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tparts = append(parts, part)\n\t\t\t}\n\t\t}\n\t\tparts = append(parts, token[start:end+1]) // capture array\n\t\ttoken = token[end+1:] // trim processed prefix\n\t}\n\n\tfor i := range parts {\n\t\tparts[i] = strings.TrimSpace(parts[i])\n\t}\n\treturn parts\n}", "func printMessage(message string, arr []string) {\n\tvar nameString = strings.Join(arr, \" \")\n\tfmt.Println(message, nameString)\n}", "func updateSlice(s []string){\n\ts[0] = \"Bye!\"\n\tfmt.Println(s)\n}", "func main() {\n\tflag.Parse() // should be executed into \"main\" method\n\tfmt.Println(stringParam)\n\tfmt.Println(intParam)\n\tfmt.Printf(\"%#v\\n\", listParam)\n}", "func programe01() {\n\t// COMPOSITE LITERAL\n\tx := []int{4, 5, 7, 8, 42}\n\tfmt.Println(x)\n}", "func newStringSliceGNMIPath(s []string) *gnmiPath {\n\tif s == nil {\n\t\ts = []string{}\n\t}\n\treturn &gnmiPath{stringSlicePath: s}\n}", "func (_Strings *StringsRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {\n\treturn _Strings.Contract.StringsCaller.contract.Call(opts, result, method, params...)\n}", "func call(method string, argsArray []string) {\n\tfmt.Println(\"------ start ------ \", method)\n\t// all args\n\tvar args [][]byte\n\targs = append(args, []byte(method))\n\tfmt.Printf(\"- args=[\")\n\tfmt.Printf(\"p0=%s\", method)\n\tif argsArray != nil {\n\t\tfor i := 0; i < len(argsArray); i++ {\n\t\t\targs = append(args, []byte(argsArray[i]))\n\t\t\tfmt.Printf(\",p%d=%s\", i+1, argsArray[i])\n\t\t}\n\t}\n\tfmt.Printf(\"]\")\n\tfmt.Println(\"\")\n\t// invoke\n\tresponse := stub.MockInvoke(\"uuid\", args)\n\tfmt.Printf(\"- status=\")\n\tfmt.Println(response.GetStatus())\n\tfmt.Printf(\"- error message=\")\n\tfmt.Println(response.GetMessage())\n\tfmt.Printf(\"- payload=\")\n\tfmt.Println(string(response.GetPayload()))\n\tfmt.Println(\"------ end ------ \")\n\tfmt.Println(\"\")\n}", "func Barr() {}", "func main() {\n\tGoArray() // Array is rarely used in Go. Slices are used instead. Array is an underlying function for Slices.\n\tGoSlice()\n}", "func myfun(element []string) {\n\n\t// Modifying the given slice\n\telement[2] = \"Java\"\n\tfmt.Println(\"Modified slice: \", element)\n}", "func printArr(strs []string, title string) {\n\tif len(strs) == 0 {\n\t\tfmt.Fprintf(os.Stdout, \"No addresses were found.\\n\")\n\t} else {\n\t\tif isLong {\n\t\t\tfmt.Fprintf(os.Stdout, \"%s: \", bold(title))\n\t\t\tfor _, local := range strs {\n\t\t\t\tfmt.Fprintf(os.Stdout, \"%s \", local)\n\t\t\t}\n\t\t\tfmt.Fprintf(os.Stdout, \"\\n\")\n\t\t} else {\n\t\t\tfmt.Fprintf(os.Stdout, \"%s\\n\", strings.Join(strs, \" \"))\n\t\t}\n\t}\n}", "func execNewArray(_ int, p *gop.Context) {\n\targs := p.GetArgs(2)\n\tret := types.NewArray(args[0].(types.Type), args[1].(int64))\n\tp.Ret(2, ret)\n}", "func main() {\n\tfmt.Println(foo(1, 2))\n\tfmt.Println(foo(1, 2, 3))\n\taSlice := []int{1, 2, 3}\n\tfmt.Println(foo(aSlice...))\n\tfmt.Println(foo())\n}", "func StrArrSpecin(mess string, sep, ex rune) []string {\n\tif sep == ex {\n\t\treturn StrArrin(string(mess), string(sep))\n\t}\n\ttext := Strin(mess)\n\t// s := strings.Split(text, sep)\n\ts := strings.FieldsFunc(text, formatter(sep, ex))\n\treturn s\n}", "func setlist(s int, p string, a []string) string {\n\tvar l string\n\tfor i, e := range a {\n\t\tif i > 0 {\n\t\t\tl += \", \"\n\t\t}\n\t\tif p != \"\" {\n\t\t\tl += p + \".\"\n\t\t}\n\t\tl += fmt.Sprintf(\"%s = $%d\", e, s+i)\n\t}\n\treturn l\n}", "func (_Strings *StringsCallerRaw) Call(opts *bind.CallOpts, result *[]interface{}, method string, params ...interface{}) error {\n\treturn _Strings.Contract.contract.Call(opts, result, method, params...)\n}", "func testSliceNotPointer(tempStudent []string) {\n\ttempStudent[0] = \"zoro\"\n\ttempStudent = append(tempStudent, \"dona\")\n\n\tfmt.Println(tempStudent)\n}", "func main() {\n\n\tdata := []string {\"a\", \"b\", \"c\", \"d\", \"e\"}\n\tfmt.Println(data[0])\n\tfmt.Println(data[0:3])\n\tfmt.Println(data[3:4])\n\tfmt.Println(data[:])\n\n\t/* will print\n\ta\n\t[a b c]\n\t[d]\n\t[a b c d e]\n\t */\n\t\n}", "func testSlice(tempStudent *[]string) {\n\t(*tempStudent)[0] = \"bams\"\n\t(*tempStudent) = append((*tempStudent), \"prince\")\n\n\tfmt.Println(tempStudent)\n}", "func (f *Add) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {\n\tlist, ok := arguments[0].(List)\n\tif !ok {\n\t\treturn nil, &executionError{line, \"'len' is only defined for lists\"}\n\t}\n\n\treturn list.Add(arguments[1]), nil\n}", "func createSliceByShorthand() {\n\tprintln(\"----Shorthand----\")\n\tstudent := []string{}\n\tstudents := [][]string{}\n\n\t// Index out of range\n\t// student[0] = \"Yuta\"\n\t// Don't have space yet, need use append\n\tstudent = append(student, \"Yuta\")\n\tfmt.Println(student)\n\tfmt.Println(students)\n\tfmt.Println(student == nil)\n\tprintln(\"----Shorthand----\")\n}", "func main(){\n\tstarter()\n\n\taddition_answer := addition(5,9)\n\tfmt.Println(\"Answer = \",addition_answer)\n\n\tfmt.Println(get_me_a_quiz_question(2))\n\n\tstudents_id := make([]string, 10)\n\tslice_me(students_id)\n\tfmt.Println(students_id)\n\n}", "func (m MethodData) ArgCallList() string {\n\tparams := make([]string, len(m.Params))\n\tfor i, p := range m.Params {\n\t\tparams[i] = p.CallName()\n\t}\n\treturn strings.Join(params, \", \")\n}", "func StringSliceToN1QLArray(values []string, quote string) string {\n\tif len(values) == 0 {\n\t\treturn \"\"\n\t}\n\tasString := fmt.Sprintf(\"%s%s%s\", quote, values[0], quote)\n\tfor i := 1; i < len(values); i++ {\n\t\tasString = fmt.Sprintf(\"%s,%s%s%s\", asString, quote, values[i], quote)\n\t}\n\treturn asString\n}", "func SliceTest() {\n\tvar a []int\n\tappSlice(a, 1)\n\n}", "func callStackTrace() {\n\tslice := make([]string, 2, 4)\n\tStackTrace(slice, \"hello\", 10)\n}", "func Array() []string {\n\tvar products []string\n\tfor i := 1; i <= 10; i++ {\n\t\tproducts = append(products, \"Products \"+strconv.Itoa(i))\n\t}\n\t// fmt.Printf(\"len of products is %d, capaicty is %d %v\\n\", len(products), cap(products), products)\n\treturn products\n}", "func modify(fooarr []string) {\n\tfooarr[1] = \"c\"\n\tfmt.Println(\"modify fooarr: \", fooarr)\n}", "func (s *BaseAspidaListener) ExitStr_array(ctx *Str_arrayContext) {}", "func (m *StringCollectionResponse) SetValue(value []string)() {\n m.value = value\n}", "func list(s string) []string {\n\ta := []string{} // resulting array\n\tfor i := 0; i < len(s); i++ {\n\t\ta = append(a, string(s[i])) // append character as string, to result\n\t}\n\treturn a\n}", "func concat(args ...[]string) []string {\n\tvar buf []string\n\tfor _, arg := range args {\n\t\tbuf = append(buf, arg...)\n\t}\n\n\treturn buf\n}", "func Slice(typCode int) *CXArgument {\n\targ := Param(typCode)\n\targ.IsSlice = true\n\targ.DeclarationSpecifiers = append(arg.DeclarationSpecifiers, DECL_SLICE)\n\treturn arg\n}", "func main(){\n fmt.Println(`Hello World`) // using Backtick\n // invalid character literal (more than one character)\n // fmt.Println('Hello World') // using single quote\n gh := [...]int{1, 2, 3, 4, 5, 6, 7}\n\n fmt.Println(gh)\n fmt.Println(\"length :- \", len(gh[1:3]))\n fmt.Println(\"capacity :-\", cap(gh[1:3]))\n ph := &gh\n fmt.Println(\"Pointer :- \", type(3 ))\n}", "func handleAllowedKeywordsToString(allowed []string) string {\n\tbldr := \"'\" + strings.Join(allowed, \"', '\") + \"'\"\n\treturn \"[\" + bldr + \"]\"\n}", "func quotedStringInteraces(strs ...string) []interface{} {\n\tinterfaces := []interface{}{}\n\tfor _, str := range strs {\n\t\tif str[0:1] != \"\\\"\" {\n\t\t\tstr = \"\\\"\" + str + \"\\\"\"\n\t\t}\n\t\tinterfaces = append(interfaces, str)\n\t}\n\treturn interfaces\n}", "func (f *Rest) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {\n\tlist, ok := arguments[0].(List)\n\tif !ok {\n\t\treturn nil, &executionError{line, \"'rest' is only defined for lists\"}\n\t}\n\n\tif list.Len() == 0 {\n\t\treturn nil, nil\n\t}\n\n\treturn list.Rest(), nil\n}", "func Test0(par0 rune) {\n}", "func testAppendStringToByteSlice() {\n\tfmt.Println(\"testAppendStringToByteSlice\")\n\ts := []byte(\"hello\")\n\ts = append(s, \" world\"...)\n\tfmt.Println(s)\n\tfmt.Println()\n}", "func f(a [3]int){ fmt.Println(a) }", "func main() {\n\n\tjim := people{firstName: \"Colobos\", lastName: \"Escorial\"}\n\tmySlice := []string{\"Hi\", \"There\", \"How\", \"Are\", \"You\"}\n\n\tupdateSlice(mySlice)\n\tfmt.Println(mySlice)\n\n\tjim.updatePeople(\"Altamira\")\n\tnicePrint(jim.firstName)\n\n}", "func (Array) expressionNode() {}", "func StrArrin(mess, sep string) []string {\n\ttext := Strin(mess)\n\ts := strings.Split(text, sep)\n\treturn s\n}", "func main() {\n\ts := make([]string, 3)\n\ts[0] = \"a\"\n\ts[1] = \"b\"\n\n\t// show results before making changes via function\n\tfmt.Println(\"emp:\", s)\n\n\ttest(s) // update slice; s is pointer\n\n\tfmt.Println(\"apd:\", s) // show results\n}", "func bar(s string) {\n\tfmt.Println(\"hello,\", s)\n}", "func StringSliceVar(p *[]string, name string, value ...string) {\n\t*p = value\n\tfuncs = append(funcs, func() bool {\n\t\tif s := os.Getenv(name); s != \"\" {\n\t\t\ta := strings.Split(s, \",\")\n\t\t\t*p = a\n\t\t}\n\t\treturn true\n\t})\n}", "func (c JobNameFuncCall) Args() []interface{} {\n\treturn []interface{}{}\n}", "func (f *Len) Call(line int, i *Interpreter, arguments []interface{}) (interface{}, error) {\n\tlist, ok := arguments[0].(List)\n\tif !ok {\n\t\treturn nil, &executionError{line, \"'len' is only defined for lists\"}\n\t}\n\n\treturn list.Len(), nil\n}", "func (dc *DriverCall) Append(arg string) {\n\tdc.args = append(dc.args, arg)\n}", "func (s *BaseSyslParserListener) ExitArray_of_strings(ctx *Array_of_stringsContext) {}", "func add(i string) error {\n\treturn nil\n}", "func (p unsafeSliceInstr) Call(pkg *Package, args []*Element, flags InstrFlags, src ast.Node) (ret *Element, err error) {\n\tcheckArgsCount(pkg, \"unsafe.Slice\", 2, len(args), src)\n\n\tt0, ok := args[0].Type.(*types.Pointer)\n\tif !ok {\n\t\t_, pos := pkg.cb.loadExpr(src)\n\t\tpos.Column += len(\"unsafe.Slice\")\n\t\tpkg.cb.panicCodeErrorf(&pos, \"first argument to unsafe.Slice must be pointer; have %v\", args[0].Type)\n\t}\n\tif t := args[1].Type; !ninteger.Match(pkg, t) {\n\t\t_, pos := pkg.cb.loadExpr(src)\n\t\tpos.Column += len(\"unsafe.Slice\")\n\t\tpkg.cb.panicCodeErrorf(&pos, \"non-integer len argument in unsafe.Slice - %v\", t)\n\t}\n\tfn := toObjectExpr(pkg, pkg.unsafe().Ref(\"Sizeof\")).(*ast.SelectorExpr)\n\tfn.Sel.Name = \"Slice\" // only in go v1.7+\n\tret = &Element{\n\t\tVal: &ast.CallExpr{Fun: fn, Args: []ast.Expr{args[0].Val, args[1].Val}},\n\t\tType: types.NewSlice(t0.Elem()),\n\t}\n\treturn\n}", "func (c *CurlCommand) append(newSlice ...string) {\n\t*c = append(*c, newSlice...)\n}", "func StringSlice(name string, value ...string) *[]string {\n\tp := new([]string)\n\tStringSliceVar(p, name, value...)\n\treturn p\n}", "func list() (r []Output) {\n\t//r := []Output{}\n\tr = append(r, Output{Message: fmt.Sprint(\"one\")})\n\tr = append(r, Output{Message: fmt.Sprint(\"two\")})\n\tr = append(r, Output{Message: fmt.Sprint(\"three\")})\n\tr = append(r, Output{Message: fmt.Sprint(\"four\")})\n\n\treturn\n}", "func main() {\n\n\t// This is a nil slice\n\tvar data []string\n\n\t// This literal construction returns an empty slice\n\t// data := []string{}\n\t// If this is an empty slice, where is it pointing to?\n\t// Go has an inbuilt structure which is a zero allocation struct.\n\t// var es struct{}\n\t\n\t// Create a slice with a length of 5 elements.\n\tfruits := make([]string, 5)\n\n\t// Create a slice with len5, cap8\n\tvegetables := make([]string, 5, 8)\n\n}", "func Array(slice []interface{}, buf []byte) ([]byte, error) {\n\tvar comma bool\n\tbuf = append(buf, '[')\n\tvar err error\n\tfor i := 0; i < len(slice); i++ {\n\t\tif comma {\n\t\t\tbuf = append(buf, ',')\n\t\t}\n\t\tcomma = true\n\t\tbuf, err = Value(slice[i], buf)\n\t\tif err != nil {\n\t\t\treturn buf, err\n\t\t}\n\t}\n\treturn append(buf, ']'), nil\n}", "func addStrings(s *scope, name string, obj pyObject, f func(string)) {\n\tif obj != nil && obj != None {\n\t\tl, ok := asList(obj)\n\t\tif !ok {\n\t\t\ts.Error(\"Argument %s must be a list, not %s\", name, obj.Type())\n\t\t}\n\t\tfor _, li := range l {\n\t\t\tstr, ok := li.(pyString)\n\t\t\tif !ok && li != None {\n\t\t\t\ts.Error(\"%s must be strings\", name)\n\t\t\t}\n\t\t\tif str != \"\" && li != None {\n\t\t\t\tf(string(str))\n\t\t\t}\n\t\t}\n\t}\n}", "func GetArgsArray(cList CommandList) (cmdArray []String){\n\n\t//var i uint32\n\tvar nArgs uint32\n\tnArgs = uint32(len(cList))\n\n\tcmdArray = make([]String, nArgs)\n\n\tfor i, arg := range cList {\n\n\t\tcmdArray[i] = String(arg)\n\n\t}\n\n\treturn\n\n}", "func main() {\n\tvar strings [5]string\n\n\tvar fruits [5]string\n\tfruits[0] = \"Apple\"\n\tfruits[1] = \"Orange\"\n\tfruits[2] = \"Banana\"\n\tfruits[3] = \"Grape\"\n\tfruits[4] = \"Plum\"\n\n\tstrings = fruits\n\n\t// Assign the populated array to the array of zero values.\t\t\n\n\t// Iterate over the first array declared.\n\t\n\tfor i, str := range strings {\n\t\tfmt.Println(i, str, &strings[i])\n\t}\n\t\n\t// Display the string value and address of each element.\n}", "func main() {\n\n\t// We will create a []int then implement the two functions we created below\n\txi := []int{2, 4, 6, 8, 10}\n\n\t//To send a slice through variadic param, we need ot \"unfurl\" it first\n\tf := foo(xi...)\n\tfmt.Println(\"foo sum:\", f)\n\n\t//Since bar was defined to take []int, we don't need to unfurl the values\n\tb := bar(xi)\n\tfmt.Println(\"bar sum:\", b)\n\n}", "func ArrayOfFunction(env *Zlisp, name string,\n\targs []Sexp) (Sexp, error) {\n\n\tif len(args) != 2 {\n\t\treturn SexpNull, fmt.Errorf(\"insufficient arguments to ([size] regtype) array constructor. use: \" +\n\t\t\t\"([size...] a-regtype)\\n\")\n\t}\n\tsz := 0\n\t//Q(\"args = %#v in ArrayOfFunction\", args)\n\tswitch ar := args[1].(type) {\n\tcase *SexpArray:\n\t\tif len(ar.Val) == 0 {\n\t\t\treturn SexpNull, fmt.Errorf(\"at least one size must be specified in array constructor; e.g. ([size ...] regtype)\")\n\t\t}\n\t\tasInt, isInt := ar.Val[0].(*SexpInt)\n\t\tif !isInt {\n\t\t\treturn SexpNull, fmt.Errorf(\"size must be an int (not %T) in array constructor; e.g. ([size ...] regtype)\", ar.Val[0])\n\t\t}\n\t\tsz = int(asInt.Val)\n\t\t// TODO: implement multiple dimensional arrays (matrixes etc).\n\tdefault:\n\t\treturn SexpNull, fmt.Errorf(\"at least one size must be specified in array constructor; e.g. ([size ...] regtype)\")\n\t}\n\n\tvar rt *RegisteredType\n\tswitch arg := args[0].(type) {\n\tcase *RegisteredType:\n\t\trt = arg\n\tcase *SexpHash:\n\t\trt = arg.GoStructFactory\n\tdefault:\n\t\treturn SexpNull, fmt.Errorf(\"argument tx in (%s x) was not regtype, \"+\n\t\t\t\"instead type %T displaying as '%v' \",\n\t\t\tname, arg, arg.SexpString(nil))\n\t}\n\n\t//Q(\"arrayOf arg = '%s' with type %T\", args[0].SexpString(nil), args[0])\n\n\tderivedType := reflect.ArrayOf(sz, rt.TypeCache)\n\tarrayRt := NewRegisteredType(func(env *Zlisp, h *SexpHash) (interface{}, error) {\n\t\treturn reflect.New(derivedType), nil\n\t})\n\tarrayRt.DisplayAs = fmt.Sprintf(\"(%s %s)\", name, rt.DisplayAs)\n\tarrayName := \"arrayOf\" + rt.RegisteredName\n\tGoStructRegistry.RegisterUserdef(arrayRt, false, arrayName)\n\treturn arrayRt, nil\n}", "func rs(r ...rune) []rune {\n\treturn r\n}", "func PrintStringArray(stringArray []string) {\n\tfor _, array := range stringArray {\n\t\tfmt.Println(array)\n\t}\n\n}", "func returnArgs(a, b string ){\n\tfmt.Println(a + \" \" + b)\n}", "func paramsToStrSlice(params []interface{}) []string {\n\tif slice, ok := params[0].([]string); len(params) == 1 && ok {\n\t\treturn slice\n\t}\n\n\tslice := make([]string, 0)\n\tfor _, param := range params {\n\t\tslice = append(slice, param.(string))\n\t}\n\treturn slice\n}", "func buildCmd(args [][]byte) []byte {\n buf := bytes.NewBuffer(nil)\n\n buf.WriteByte(star)\n buf.WriteString(strconv.Itoa(len(args)))\n buf.Write(delim)\n\n for _, arg := range args {\n buf.WriteByte(dollar)\n buf.WriteString(strconv.Itoa(len(arg)))\n buf.Write(delim)\n buf.Write(arg)\n buf.Write(delim)\n }\n\n if debug {\n log.Printf(\"GODIS: %q\", string(buf.Bytes()))\n }\n\n return buf.Bytes()\n}", "func printSlice(in []string) string {\n\tn := len(in)\n\tswitch n {\n\tcase 0:\n\t\treturn \"\"\n\tcase 1:\n\t\treturn in[0]\n\tcase 2:\n\t\treturn strings.Join(in, \" & \")\n\tdefault:\n\t\treturn printSlice([]string{strings.Join(in[:n-1], \", \"), in[n-1]})\n\t}\n}", "func trimFirstArg(args []string) []string {\n\tl := len(args)\n\tif l > 1 {\n\t\treturn args[1:]\n\t}\n\treturn []string(nil)\n}", "func RepeatMe(words ...string) {\n\tfmt.Println(words)\n}", "func Forlooptest(){\n\ta := os.Args\n\tfor i:=1; i<len(a); i++{\n\t\t//fmt.Printf(\"%s\\n\", a[i])\n\t\tfor j:=0; j<len(a[i]);j++{\n\t\t\tfmt.Println(string(a[i][j]))\n\t\t}\n\t}\n}", "func proplist(p string, a []string) string {\n\tvar l string\n\tfor i, e := range a {\n\t\tif i > 0 {\n\t\t\tl += \", \"\n\t\t}\n\t\tif p != \"\" {\n\t\t\tl += p + \".\" + e\n\t\t} else {\n\t\t\tl += e\n\t\t}\n\t}\n\treturn l\n}", "func StringSlice(s []string, err error) []string {\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\n\treturn s\n}", "func main() {\n\n flag.Parse()\n fmt.Printf(\"Can build A0 paper ? : Input papers -> %v\\n\",*inputPapers)\n\n s := strings.Replace(*inputPapers, \" \", \"\", -1)\n s = strings.Replace(s, \"{\", \"\", -1)\n s = strings.Replace(s, \"}\", \"\", -1)\n\n inputlist := strings.Split(s, \",\")\n var papers []int\n for _, v := range inputlist {\n sheets, _ := strconv.Atoi(v)\n papers = append(papers, sheets)\n }\n\n // check\n var a0 A0Paper\n judge := a0.canBuild(papers)\n fmt.Println(judge)\n}", "func interfacesToStringSlice(args []interface{}, startIndex int) []string {\n\tvar str []string\n\tfor k, v := range args {\n\t\tif k < startIndex {\n\t\t\tcontinue\n\t\t}\n\t\tstr = append(str, v.(string))\n\t}\n\treturn str\n}", "func (a *api) Call(name string, args ...interface{}) {\n\tformat := a.Name(name) + \"(%s\" + strings.Repeat(\", %s\", len(args)-1) + \")\"\n\ta.Linef(format, args...)\n}" ]
[ "0.58119607", "0.56760335", "0.55741525", "0.5551811", "0.5540314", "0.55145967", "0.55011255", "0.5417521", "0.53895044", "0.5353373", "0.5327466", "0.5322369", "0.5283115", "0.52759963", "0.5259119", "0.52212644", "0.5218769", "0.5201288", "0.51961386", "0.5170183", "0.51499015", "0.51044947", "0.5097426", "0.50771487", "0.507119", "0.5062638", "0.50424737", "0.50138277", "0.5007688", "0.50016576", "0.49944198", "0.49745876", "0.4970288", "0.49690452", "0.4960056", "0.49533865", "0.4947342", "0.4941758", "0.4929195", "0.49291646", "0.49269977", "0.49217704", "0.49043176", "0.48948935", "0.4873207", "0.4868569", "0.48553026", "0.4849607", "0.48281136", "0.48271048", "0.48270145", "0.4826975", "0.4814088", "0.48092332", "0.4781801", "0.47656628", "0.47647312", "0.4760769", "0.4758939", "0.47551167", "0.47533193", "0.4734164", "0.47297403", "0.47265106", "0.47181898", "0.4713307", "0.47082856", "0.47071925", "0.47043404", "0.46959743", "0.46803492", "0.46794885", "0.4678522", "0.46713907", "0.46705732", "0.46656296", "0.46656254", "0.4664509", "0.4659603", "0.46587288", "0.46490496", "0.46488285", "0.46476334", "0.46475", "0.4646734", "0.46422723", "0.46419165", "0.46412715", "0.46385646", "0.46330106", "0.46250862", "0.4623707", "0.46223506", "0.46185786", "0.46177927", "0.46087512", "0.46054816", "0.46053362", "0.46037748", "0.45952225", "0.45927528" ]
0.0
-1