query
stringlengths 8
6.75k
| document
stringlengths 9
1.89M
| negatives
listlengths 19
19
| metadata
dict |
---|---|---|---|
////////////////////////////////////////////////////////////////////////////////// // printCompletion prints completion for given shell
|
func printCompletion() int {
info := genUsage()
switch options.GetS(OPT_COMPLETION) {
case "bash":
fmt.Printf(bash.Generate(info, "rbinstall-clone"))
case "fish":
fmt.Printf(fish.Generate(info, "rbinstall-clone"))
case "zsh":
fmt.Printf(zsh.Generate(info, optMap, "rbinstall-clone"))
default:
return 1
}
return 0
}
|
[
"func printCompletion() int {\n\tinfo := genUsage()\n\n\tswitch options.GetS(OPT_COMPLETION) {\n\tcase \"bash\":\n\t\tfmt.Printf(bash.Generate(info, \"init-exporter\"))\n\tcase \"fish\":\n\t\tfmt.Printf(fish.Generate(info, \"init-exporter\"))\n\tcase \"zsh\":\n\t\tfmt.Printf(zsh.Generate(info, optMap, \"init-exporter\"))\n\tdefault:\n\t\treturn 1\n\t}\n\n\treturn 0\n}",
"func genCompletion() {\n\tinfo := genUsage()\n\n\tswitch options.GetS(OPT_COMPLETION) {\n\tcase \"bash\":\n\t\tfmt.Printf(bash.Generate(info, \"shdoc\"))\n\tcase \"fish\":\n\t\tfmt.Printf(fish.Generate(info, \"shdoc\"))\n\tcase \"zsh\":\n\t\tfmt.Printf(zsh.Generate(info, optMap, \"shdoc\"))\n\tdefault:\n\t\tos.Exit(1)\n\t}\n\n\tos.Exit(0)\n}",
"func RunCompletion(out io.Writer, cmd *cobra.Command, args []string) {\n\tshell := args[0]\n\tswitch shell {\n\tcase \"bash\":\n\t\t_ = runCompletionBash(out, cmd.Parent())\n\tcase \"zsh\":\n\t\t_ = runCompletionZsh(out, cmd.Parent())\n\tdefault:\n\t\tlog.Fatal(\"UnExpected shell type.\")\n\t}\n}",
"func Completion(cmd *cobra.Command, args []string) {\n\terr := cmd.Root().GenBashCompletionFile(completionTarget)\n\tcompletion(err, args...)\n}",
"func (c *Command) GenBashCompletion(w io.Writer) error {\n\treturn c.genBashCompletion(w, false)\n}",
"func (c Carapace) DashCompletion(action ...Action) {\n\tstorage.get(c.cmd).dash = action\n}",
"func readCompletionOutput(err error, args ...string) string {\n\toldStdout := os.Stdout // keep backup of the real stdout\n\tread, write, _ := os.Pipe()\n\tos.Stdout = write\n\tcompletion(err, args...) // completion(...) output to be captured\n\twrite.Close()\n\tout, _ := ioutil.ReadAll(read)\n\tos.Stdout = oldStdout\n\tgot := strings.TrimSpace(string(out))\n\treturn got\n}",
"func getCompletion(sh string, parent *cobra.Command) (string, error) {\n\tvar err error\n\tvar buf bytes.Buffer\n\n\tswitch sh {\n\tcase \"bash\":\n\t\terr = parent.GenBashCompletion(&buf)\n\tcase \"zsh\":\n\t\terr = parent.GenZshCompletion(&buf)\n\tcase \"fish\":\n\t\terr = parent.GenFishCompletion(&buf, true)\n\n\tdefault:\n\t\terr = errors.New(\"unsupported shell type (must be bash, zsh or fish): \" + sh)\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn buf.String(), nil\n}",
"func (c *Command) GenBashCompletionWithDesc(w io.Writer) error {\n\treturn c.genBashCompletion(w, true)\n}",
"func (c *Command) GenZshCompletion(w io.Writer) error {\n\treturn c.genZshCompletion(w, true)\n}",
"func Complete() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"complete\",\n\t\tAliases: []string{\"completion\"},\n\t\tHidden: true,\n\t\tShort: \"Generate script for auto-completion\",\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tif name, _ := cmd.Flags().GetString(\"executable\"); name != \"\" {\n\t\t\t\tcmd.Root().Use = name\n\t\t\t}\n\t\t\tswitch shell, _ := cmd.Flags().GetString(\"shell\"); shell {\n\t\t\tcase \"bash\":\n\t\t\t\treturn cmd.Root().GenBashCompletion(os.Stdout)\n\t\t\tcase \"zsh\":\n\t\t\t\treturn cmd.Root().GenZshCompletion(os.Stdout)\n\t\t\tcase \"fish\":\n\t\t\t\t// Fish does not accept `-` in variable names\n\t\t\t\tbuf := new(bytes.Buffer)\n\t\t\t\tif err := cmd.Root().GenFishCompletion(buf, true); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tscript := strings.Replace(buf.String(), \"__ttn-lw-\", \"__ttn_lw_\", -1)\n\t\t\t\t_, err := fmt.Print(script)\n\t\t\t\treturn err\n\t\t\tcase \"powershell\":\n\t\t\t\treturn cmd.Root().GenPowerShellCompletion(os.Stdout)\n\t\t\tdefault:\n\t\t\t\treturn errInvalidShell.WithAttributes(\"shell\", shell)\n\t\t\t}\n\t\t},\n\t}\n\tcmd.Flags().String(\"shell\", \"bash\", \"bash|zsh|fish|powershell\")\n\tcmd.Flags().String(\"executable\", \"\", \"Executable name to create generate auto completion script for\")\n\treturn cmd\n}",
"func newCmdCompletion() *cobra.Command {\n\texample := ` # bash <= 3.2:\n # To load shell completion into your current shell session\n source /dev/stdin <<< \"$(linkerd completion bash)\"\n\n # bash >= 4.0:\n source <(linkerd completion bash)\n\n # To load shell completion for every shell session\n # bash <= 3.2 on osx:\n brew install bash-completion # ensure you have bash-completion 1.3+\n linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd\n\n # bash >= 4.0 on osx:\n brew install bash-completion@2\n linkerd completion bash > $(brew --prefix)/etc/bash_completion.d/linkerd\n\n # bash >= 4.0 on linux:\n linkerd completion bash > /etc/bash_completion.d/linkerd\n\n # You will need to start a new shell for this setup to take effect.\n\n # zsh:\n # If shell completion is not already enabled in your environment you will need\n # to enable it. You can execute the following once:\n\n echo \"autoload -U compinit && compinit\" >> ~/.zshrc\n\n # create a linkerd 'plugins' folder and add it to your $fpath\n mkdir $ZSH/plugins/linkerd && echo \"fpath=($ZSH/plugins/linkerd $fpath)\" >> ~/.zshrc\n\n # To load completions for each session, execute once:\n linkerd completion zsh > \"${fpath[1]}/_linkerd\" && exec $SHELL\n\n # You will need to start a new shell for this setup to take effect.\n\n # fish:\n linkerd completion fish | source\n\n # To load fish shell completions for each session, execute once:\n linkerd completion fish > ~/.config/fish/completions/linkerd.fish`\n\n\tcmd := &cobra.Command{\n\t\tUse: \"completion [bash|zsh|fish]\",\n\t\tShort: \"Output shell completion code for the specified shell (bash, zsh or fish)\",\n\t\tLong: \"Output shell completion code for the specified shell (bash, zsh or fish).\",\n\t\tExample: example,\n\t\tArgs: cobra.ExactArgs(1),\n\t\tValidArgs: []string{\"bash\", \"zsh\", \"fish\"},\n\t\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\t\tout, err := getCompletion(args[0], cmd.Parent())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tfmt.Print(out)\n\t\t\treturn nil\n\t\t},\n\t}\n\n\treturn cmd\n}",
"func InstallBashCompletion(ctx context.Context) error {\n\toutput, err := exec.Command(neco.SabactlBin, \"completion\").Output()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.WriteFile(neco.SabactlBashCompletionFile, output, 0644)\n}",
"func completionColorizer(completed bool) string {\n\tif completed {\n\t\treturn color.HiGreenString(\"pwnd\")\n\t}\n\n\treturn color.HiYellowString(\"incomplete\")\n}",
"func mainComplete() error {\n\t// Recursively register all commands and subcommands\n\t// along with global and local flags\n\tvar complCmds = make(complete.Commands)\n\tfor _, cmd := range appCmds {\n\t\tcomplCmds[cmd.Name] = cmdToCompleteCmd(cmd, \"\")\n\t}\n\tcomplFlags := flagsToCompleteFlags(globalFlags)\n\tmcComplete := complete.Command{\n\t\tSub: complCmds,\n\t\tGlobalFlags: complFlags,\n\t}\n\t// Answer to bash completion call\n\tcomplete.New(filepath.Base(os.Args[0]), mcComplete).Run()\n\treturn nil\n}",
"func TabCompleter(line []rune, pos int) (lastWord string, completions []*readline.CompletionGroup) {\n\n\t// Format and sanitize input\n\targs, last, lastWord := FormatInput(line)\n\n\t// Detect base command automatically\n\tvar command = detectedCommand(args, \"\") // add *commands.Context.Menu in the string here\n\n\t// Propose commands\n\tif noCommandOrEmpty(args, last, command) {\n\t\treturn CompleteMenuCommands(last, pos)\n\t}\n\n\t// Check environment variables\n\tif envVarAsked(args, last) {\n\n\t}\n\n\t// Base command has been identified\n\tif commandFound(command) {\n\n\t\t// If user asks for completions with \"-\" / \"--\", show command options\n\t\tif optionsAsked(args, last, command) {\n\n\t\t}\n\n\t\t// Check environment variables again\n\t\tif envVarAsked(args, last) {\n\n\t\t}\n\n\t\t// Propose argument completion before anything, and if needed\n\t\tif _, yes := argumentRequired(last, args, \"\", command, false); yes { // add *commands.Context.Menu in the string here\n\n\t\t}\n\n\t\t// Then propose subcommands\n\t\tif hasSubCommands(command, args) {\n\n\t\t}\n\n\t\t// Handle subcommand if found (maybe we should rewrite this function and use it also for base command)\n\t\tif _, ok := subCommandFound(last, args, command); ok {\n\n\t\t}\n\t}\n\n\t// -------------------- IMPORTANT ------------------------\n\t// WE NEED TO PASS A DEEP COPY OF THE OBJECTS: OTHERWISE THE COMPLETION SEARCH FUNCTION WILL MESS UP WITH THEM.\n\n\treturn\n}",
"func (cli *Application) handleBashCompletion() {\n\tcli.Log.Debugf(\"CLI:handleBashCompletion - is bash completion call (%t)\",\n\t\tcli.flag(\"show-bash-completion\").Present())\n\n\tif cli.flag(\"show-bash-completion\").Present() {\n\t\t// TODO(mkungla): https://github.com/howi-ce/howi/issues/15\n\t\tcli.Log.Error(\"bash completion not implemented\")\n\t\tos.Exit(0)\n\t}\n}",
"func getBashCompletions() string {\n\tcompletions := []string{\n\t\tconfig.GetBashCompletion(),\n\t}\n\treturn strings.Join(completions, \"\\n\")\n}",
"func createDefaultComplete(app *cli.App) func(c *cli.Context) {\n\treturn func(c *cli.Context) {\n\t\tif c.NArg() > 0 {\n\t\t\treturn\n\t\t}\n\n\t\ttrailingArg := os.Args[len(os.Args)-2]\n\t\tisCompleting := isCompletingArg(app.Flags, trailingArg)\n\t\tif !isCompleting {\n\t\t\tfmt.Println(\"normal\")\n\t\t\tfor _, command := range app.Commands {\n\t\t\t\tprintCommand(command)\n\t\t\t}\n\t\t\tfor _, flag := range app.Flags {\n\t\t\t\tprintFlag(c, flag)\n\t\t\t}\n\t\t\treturn\n\t\t}\n\n\t\t// Default to file completion\n\t\tfmt.Println(\"file\")\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
printMan prints man page
|
func printMan() {
fmt.Println(
man.Generate(
genUsage(),
genAbout(""),
),
)
}
|
[
"func printHelp(h helper, pp parentParser) {\n\thelpWriter.Write([]byte(h.help(pp)))\n}",
"func showManual(manual string) error {\n\tmanBinary, err := exec.LookPath(\"man\")\n\tif err != nil {\n\t\tif errors.Is(err, exec.ErrNotFound) {\n\t\t\tfmt.Printf(\"toolbox - Tool for containerized command line environments on Linux\\n\")\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tfmt.Printf(\"Common commands are:\\n\")\n\n\t\t\tusage := getUsageForCommonCommands()\n\t\t\tfmt.Printf(\"%s\", usage)\n\n\t\t\tfmt.Printf(\"\\n\")\n\t\t\tfmt.Printf(\"Go to https://github.com/containers/toolbox for further information.\\n\")\n\t\t\treturn nil\n\t\t}\n\n\t\treturn errors.New(\"failed to look up man(1)\")\n\t}\n\n\tmanualArgs := []string{\"man\", manual}\n\tenv := os.Environ()\n\n\tstderrFd := os.Stderr.Fd()\n\tstderrFdInt := int(stderrFd)\n\tstdoutFd := os.Stdout.Fd()\n\tstdoutFdInt := int(stdoutFd)\n\tif err := syscall.Dup3(stdoutFdInt, stderrFdInt, 0); err != nil {\n\t\treturn errors.New(\"failed to redirect standard error to standard output\")\n\t}\n\n\tif err := syscall.Exec(manBinary, manualArgs, env); err != nil {\n\t\treturn errors.New(\"failed to invoke man(1)\")\n\t}\n\n\treturn nil\n}",
"func printHelp() {\n\tfmt.Println(\"Movie and TV Show Lookup (version \" + version + \")\")\n\tfmt.Println(\"Available commands:\")\n\tfmt.Println(\"* -h | --help Prints the list of available commands\")\n\tfmt.Println(\"* -v | --version Prints the version of the program\")\n\tfmt.Println(\"\\n* -m | --movie `movie title` [(YEAR)] Search for a movie (e.g. go-movie-lookup -m Avengers)\")\n\tfmt.Println(\"In case you want the movie from a specific year, you can add the year in front of the movie title (e.g. go-movie-lookup -m Ghostbusters (1984)\")\n\tfmt.Println(\"\\n* -s | --show `show title` [S1 | S1 E1] Search for a TV show (e.g. go-movie-lookup -s Game of Thrones)\")\n\tfmt.Println(\"You can also search for a TV show season (e.g. go-movie-lookup -s Game of Thrones S3) or a TV show episode (e.g. go-movie-lookup -s Game of Thrones S3 E9)\")\n\tfmt.Println(\"In case you want the TV show from a specific year, you can add the year in front of the show title (e.g. go-movie-lookup -s House of Cards (1990)\")\n}",
"func (status *Status) PrintHelp(writer io.Writer) {\n\tfmt.Fprintf(writer, statusDocumentation, statusToString(status.session.State.Settings.Status))\n}",
"func PrintHelp() {\n\tfmt.Print(usage)\n}",
"func printHelp(w io.Writer) {\n\twr := bufio.NewWriter(w)\n\twr.WriteString(fmt.Sprintf(\"%s - password generator\\n\", appName))\n\n\twr.WriteString(fmt.Sprint(\"Usage:\\n\"))\n\twr.WriteString(fmt.Sprintf(\" %s [options] (<username> <sitename>)\\n\", os.Args[0]))\n\twr.WriteString(fmt.Sprintf(\" %s -h | --help\\n\", os.Args[0]))\n\twr.WriteString(fmt.Sprintf(\" %s --version\\n\\n\", os.Args[0]))\n\n\t//fmt.Fprint(os.Stderr, \"Example:\\n\")\n\t//fmt.Fprintf(os.Stderr, \" %s --length 4 --digit \\\"Cold Bishop\\\" \\\"example.com\\\"\\n\", appName)\n\t//fmt.Fprint(os.Stderr, \" Set the length to 4 and enable only numeric characters\\n\\n\")\n\n\twr.WriteString(fmt.Sprint(\"Options:\\n\"))\n\twr.Flush()\n\n\tpflag.PrintDefaults()\n\n\twr.WriteString(fmt.Sprint(\"\\nIf none of the -dlpU options are passed, they are all enabled by default.\\n\"))\n\twr.Flush()\n}",
"func (c *cmdDef) PrintHelp(w io.Writer) {\n\t// Don't explode.\n\tif c.Help == nil {\n\t\tfmt.Fprintln(w, \"No help found for command:\", c.Name)\n\t\treturn\n\t}\n\n\tvar msg string\n\tswitch h := c.Help.(type) {\n\tcase string:\n\t\tmsg = h\n\tdefault:\n\t\tmsg = \"Warning: unable to interpret help for command: \" + c.Name\n\t}\n\n\tif msg[0] == '\\n' {\n\t\tmsg = msg[1:]\n\t}\n\tfmt.Fprintln(w, msg)\n}",
"func PrintHelp() {\n\tcmdPrefix := config.Config.General.CmdPrefix\n\tfmt.Fprintln(textView, \"[-::u]Keys:[-::-]\")\n\tfmt.Fprintln(textView, \"\")\n\tfmt.Fprintln(textView, \"Global\")\n\tfmt.Fprintln(textView, \"[::b] Up/Down[::-] = Scroll history/chats\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.SwitchPanels, \"[::-] = Switch input/chats\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.FocusMessages, \"[::-] = Focus message panel\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.CommandQuit, \"[::-] = Exit app\")\n\tfmt.Fprintln(textView, \"\")\n\tfmt.Fprintln(textView, \"[-::-]Message panel[-::-]\")\n\tfmt.Fprintln(textView, \"[::b] Up/Down[::-] = select message\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageDownload, \"[::-] = Download attachment\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageOpen, \"[::-] = Download & open attachment\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageShow, \"[::-] = Download & show image using\", config.Config.General.ShowCommand)\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageUrl, \"[::-] = Find URL in message and open it\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageRevoke, \"[::-] = Revoke message\")\n\tfmt.Fprintln(textView, \"[::b]\", config.Config.Keymap.MessageInfo, \"[::-] = Info about message\")\n\tfmt.Fprintln(textView, \"\")\n\tfmt.Fprintln(textView, \"Config file in ->\", config.GetConfigFilePath())\n\tfmt.Fprintln(textView, \"\")\n\tfmt.Fprintln(textView, \"Type [::b]\"+cmdPrefix+\"commands[::-] to see all commands\")\n\tfmt.Fprintln(textView, \"\")\n}",
"func PrintCmdHelp(toolName string, command Command) {\n\tbw := bufio.NewWriter(os.Stdout)\n\n\tdata := struct {\n\t\tToolName string\n\t\tCmdUsageLine string\n\t\tCmdLong string\n\t}{\n\t\ttoolName,\n\t\tcommand.OptionInfo().UsageLine,\n\t\tcommand.OptionInfo().Long,\n\t}\n\n\tfgutil.RenderTemplate(bw, tplCmdHelp, data)\n\tbw.Flush()\n}",
"func Manual(req []string, s *dg.Session, msg *dg.MessageCreate) string {\n\tif len(req) < 2 {\n\t\thelpMsg := fmt.Sprintf(\"Usage: `<prefix>man command`\")\n\t\treturn helpMsg\n\t}\n\n\tswitch req[1] {\n\tcase \"gif\":\n\t\treturn gif\n\tcase \"man\":\n\t\treturn man\n\tcase \"meme\":\n\t\treturn meme\n\tcase \"ping\":\n\t\treturn ping\n\tcase \"rule34\":\n\t\treturn rule34\n\t}\n\treturn \"Sorry, I don't have a manual for that :confused:\"\n}",
"func main() {\n\tflag.Parse()\n\n\tinfof(os.Stderr, \"Converting man pages into code...\\n\")\n\trootDir, fs := readManDir()\n\tmanDir := filepath.Join(rootDir, \"docs\", \"man\")\n\tout, err := os.Create(filepath.Join(rootDir, \"commands\", \"mancontent_gen.go\"))\n\tif err != nil {\n\t\twarnf(os.Stderr, \"Failed to create go file: %v\\n\", err)\n\t\tos.Exit(2)\n\t}\n\tout.WriteString(\"package commands\\n\\nfunc init() {\\n\")\n\tout.WriteString(\"\\t// THIS FILE IS GENERATED, DO NOT EDIT\\n\")\n\tout.WriteString(\"\\t// Use 'go generate ./commands' to update\\n\")\n\tfileregex := regexp.MustCompile(`git-lfs(?:-([A-Za-z\\-]+))?.\\d.ronn`)\n\theaderregex := regexp.MustCompile(`^###?\\s+([A-Za-z0-9\\(\\) ]+)`)\n\t// only pick up caps in links to avoid matching optional args\n\tlinkregex := regexp.MustCompile(`\\[([A-Z\\-\\(\\) ]+)\\]`)\n\t// man links\n\tmanlinkregex := regexp.MustCompile(`(git)(?:-(lfs))?-([a-z\\-]+)\\(\\d\\)`)\n\tcount := 0\n\tfor _, f := range fs {\n\t\tif match := fileregex.FindStringSubmatch(f.Name()); match != nil {\n\t\t\tinfof(os.Stderr, \"%v\\n\", f.Name())\n\t\t\tcmd := match[1]\n\t\t\tif len(cmd) == 0 {\n\t\t\t\t// This is git-lfs.1.ronn\n\t\t\t\tcmd = \"git-lfs\"\n\t\t\t}\n\t\t\tout.WriteString(\"\\tManPages[\\\"\" + cmd + \"\\\"] = `\")\n\t\t\tcontentf, err := os.Open(filepath.Join(manDir, f.Name()))\n\t\t\tif err != nil {\n\t\t\t\twarnf(os.Stderr, \"Failed to open %v: %v\\n\", f.Name(), err)\n\t\t\t\tos.Exit(2)\n\t\t\t}\n\t\t\t// Process the ronn to make it nicer as help text\n\t\t\tscanner := bufio.NewScanner(contentf)\n\t\t\tfirstHeaderDone := false\n\t\t\tskipNextLineIfBlank := false\n\t\t\tlastLineWasBullet := false\n\t\tscanloop:\n\t\t\tfor scanner.Scan() {\n\t\t\t\tline := scanner.Text()\n\t\t\t\ttrimmedline := strings.TrimSpace(line)\n\t\t\t\tif skipNextLineIfBlank && len(trimmedline) == 0 {\n\t\t\t\t\tskipNextLineIfBlank = false\n\t\t\t\t\tlastLineWasBullet = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\t// Special case headers\n\t\t\t\tif hmatch := headerregex.FindStringSubmatch(line); hmatch != nil {\n\t\t\t\t\theader := strings.ToLower(hmatch[1])\n\t\t\t\t\tswitch header {\n\t\t\t\t\tcase \"synopsis\":\n\t\t\t\t\t\t// Ignore this, just go direct to command\n\n\t\t\t\t\tcase \"description\":\n\t\t\t\t\t\t// Just skip the header & newline\n\t\t\t\t\t\tskipNextLineIfBlank = true\n\t\t\t\t\tcase \"options\":\n\t\t\t\t\t\tout.WriteString(\"Options:\" + \"\\n\")\n\t\t\t\t\tcase \"see also\":\n\t\t\t\t\t\t// don't include any content after this\n\t\t\t\t\t\tbreak scanloop\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tout.WriteString(strings.ToUpper(header[:1]) + header[1:] + \"\\n\")\n\t\t\t\t\t\tout.WriteString(strings.Repeat(\"-\", len(header)) + \"\\n\")\n\t\t\t\t\t}\n\t\t\t\t\tfirstHeaderDone = true\n\t\t\t\t\tlastLineWasBullet = false\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\tif lmatches := linkregex.FindAllStringSubmatch(line, -1); lmatches != nil {\n\t\t\t\t\tfor _, lmatch := range lmatches {\n\t\t\t\t\t\tlinktext := strings.ToLower(lmatch[1])\n\t\t\t\t\t\tline = strings.Replace(line, lmatch[0], `\"`+strings.ToUpper(linktext[:1])+linktext[1:]+`\"`, 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif manmatches := manlinkregex.FindAllStringSubmatch(line, -1); manmatches != nil {\n\t\t\t\t\tfor _, manmatch := range manmatches {\n\t\t\t\t\t\tline = strings.Replace(line, manmatch[0], strings.Join(manmatch[1:], \" \"), 1)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Skip content until after first header\n\t\t\t\tif !firstHeaderDone {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// OK, content here\n\n\t\t\t\t// remove characters that markdown would render invisible in a text env.\n\t\t\t\tfor _, invis := range []string{\"`\", \"<br>\"} {\n\t\t\t\t\tline = strings.Replace(line, invis, \"\", -1)\n\t\t\t\t}\n\n\t\t\t\t// indent bullets\n\t\t\t\tif strings.HasPrefix(line, \"*\") {\n\t\t\t\t\tlastLineWasBullet = true\n\t\t\t\t} else if lastLineWasBullet && !strings.HasPrefix(line, \" \") {\n\t\t\t\t\t// indent paragraphs under bullets if not already done\n\t\t\t\t\tline = \" \" + line\n\t\t\t\t}\n\n\t\t\t\tout.WriteString(line + \"\\n\")\n\t\t\t}\n\t\t\tout.WriteString(\"`\\n\")\n\t\t\tcontentf.Close()\n\t\t\tcount++\n\t\t}\n\t}\n\tout.WriteString(\"}\\n\")\n\tinfof(os.Stderr, \"Successfully processed %d man pages.\\n\", count)\n\n}",
"func printHelp(err int) {\n\n\tfmt.Printf(\"\\n Description, \\n\")\n\tfmt.Printf(\" - This is a small (< 600 line of go) pastebing with\")\n\tfmt.Printf(\" support for syntax highlightnig (trough python-pygments).\\n\")\n\tfmt.Printf(\" No more no less.\\n\\n\")\n\n\tfmt.Printf(\" Usage, \\n\")\n\tfmt.Printf(\" - %s [--help] [--debug]\\n\\n\", os.Args[0])\n\n\tfmt.Printf(\" Where, \\n\")\n\tfmt.Printf(\" - help shows this incredibly useful help.\\n\")\n\tfmt.Printf(\" - debug shows quite detailed information about whats\")\n\tfmt.Printf(\" going on.\\n\\n\")\n\n\tos.Exit(err)\n}",
"func PrintCmd(options *printOptions, args []string) error {\n\tname := wstring.Reversible(args[0])\n\tif options.Reverse {\n\t\tname = name.Reverse()\n\t}\n\tfmt.Printf(\"Hello %q\\n\", name)\n\treturn nil\n}",
"func PrintCommandUsage(cms string) {\n\tswitch cms {\n\tcase \"monitor\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- switches the given interface in to MONITOR mode\")\n\t\tfmt.Println(\"- example: \\\\monitor\")\n\t\tprintDashes()\n\t\tbreak\n\tcase \"managed\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- switches the given interface in to MANAGED mode\")\n\t\tfmt.Println(\"- example: \\\\managed\")\n\t\tprintDashes()\n\t\tbreak\n\tcase \"listen\":\n\t\tprintDashes()\n\t\tfmt.Println(\"- listen all or specific bssid traffic\")\n\t\tfmt.Println(\"- example (listen all): \\\\listen \")\n\t\tfmt.Println(\"- example (listen bssid only): \\\\listen bssid\")\n\t\tprintDashes()\n\tdefault:\n\t\tprintDashes()\n\t\tfmt.Println(\"- no help found for arg \" + cms)\n\t\tprintDashes()\n\t}\n}",
"func helpPrinter(out io.Writer, templ string, data interface{}) {\n\tw := tabwriter.NewWriter(out, 0, 8, 1, '\\t', 0)\n\tt := template.Must(template.New(\"help\").Parse(templ))\n\terr := t.Execute(w, data)\n\tcheck(err)\n\n\tw.Flush()\n\tos.Exit(0)\n}",
"func (s *Server) PrintHelp(writer io.Writer) {\n\tfmt.Fprintln(writer, serverDocumentation)\n}",
"func printHelp() {\n\tfmt.Printf(helpMessage)\n\tos.Exit(0)\n}",
"func Print(app, ver, gitRev string, gomod []byte) {\n\tfmtutil.SeparatorTitleColorTag = \"{s-}\"\n\tfmtutil.SeparatorFullscreen = false\n\tfmtutil.SeparatorColorTag = \"{s-}\"\n\tfmtutil.SeparatorSize = 80\n\n\tshowApplicationInfo(app, ver, gitRev)\n\tshowOSInfo()\n\tshowDepsInfo(gomod)\n\n\tfmtutil.Separator(false)\n}",
"func PrintCmdUsage(w io.Writer, toolName string, command Command) {\n\tbw := bufio.NewWriter(w)\n\n\tdata := struct {\n\t\tToolName string\n\t\tCmdUsageLine string\n\t}{\n\t\ttoolName,\n\t\tcommand.OptionInfo().UsageLine,\n\t}\n\n\tfgutil.RenderTemplate(bw, tplCmdUsage, data)\n\tbw.Flush()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
genUsage generates usage info
|
func genUsage() *usage.Info {
info := usage.NewInfo("", "url", "path")
info.AppNameColorTag = "{*}" + colorTagApp
info.AddOption(OPT_YES, `Answer "yes" to all questions`)
info.AddOption(OPT_NO_COLOR, "Disable colors in output")
info.AddOption(OPT_HELP, "Show this help message")
info.AddOption(OPT_VER, "Show version")
info.AddExample(
"https://rbinstall.kaos.st /path/to/clone",
"Clone EK repository to /path/to/clone",
)
return info
}
|
[
"func genUsage(w io.Writer, cmdName string) error {\n\t// Capture output from running:\n\t// foo -help\n\tbuf := new(bytes.Buffer)\n\tcmd := exec.Command(cmdName, \"-help\")\n\tcmd.Stderr = buf\n\tcmd.Run()\n\n\t// Add DO NOT EDIT notice.\n\tout := new(bytes.Buffer)\n\tfmt.Fprintf(out, \"// Generated by `usagen %s`; DO NOT EDIT.\\n\\n\", cmdName)\n\n\t// Prefix each line with \"// \".\n\tlines := strings.Split(buf.String(), \"\\n\")\n\tfor i, line := range lines {\n\t\tprefix := \"// \"\n\t\tif len(line) == 0 {\n\t\t\tif i == len(lines)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprefix = \"//\"\n\t\t}\n\t\tfmt.Fprintf(out, \"%s%s\\n\", prefix, line)\n\t}\n\tout.WriteString(\"package main\\n\")\n\n\t// Write usage info to w.\n\tif _, err := w.Write(out.Bytes()); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}",
"func showUsage() {\n\tgenUsage().Render()\n}",
"func usage() {\n\tlog.Print(createUsage)\n\tlog.Print(deleteUsgage)\n}",
"func usageGenerate(cmd string) string {\n\treturn \"Generates the Kubernetes manifests which allow a Bridge to be deployed \" +\n\t\t\"to TriggerMesh, and writes them to standard output.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE [OPTION]...\\n\" +\n\t\t\"\\n\" +\n\t\t\"OPTIONS:\\n\" +\n\t\t\" --bridge Output a Bridge object instead of a List-manifest.\\n\" +\n\t\t\" --yaml Output generated manifests in YAML format.\\n\"\n}",
"func getUsageTemplate() string {\n\treturn `Usage:{{if .Runnable}}\n {{.UseLine}}{{end}}{{if gt (len .Aliases) 0}}{{printf \"\\n\" }}\nAliases:\n {{.NameAndAliases}}{{end}}{{if .HasExample}}{{printf \"\\n\" }}\nExamples:\n{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nAvailable Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}{{printf \"\\n\"}}\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}{{printf \"\\n\"}}\nGlobal Flags:\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}{{printf \"\\n\"}}\nAdditional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}\n {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nUse \"{{.CommandPath}} [command] --help\" for more information about a command.{{end}}\"\n{{printf \"\\n\"}}`\n}",
"func getUsageTemplate() string {\n\treturn `{{printf \"\\n\"}}Usage:{{if .Runnable}}\n {{.UseLine}}{{end}}{{if gt (len .Aliases) 0}}{{printf \"\\n\" }}\nAliases:\n {{.NameAndAliases}}{{end}}{{if .HasExample}}{{printf \"\\n\" }}\nExamples:\n{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nAvailable Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}{{printf \"\\n\"}}\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}{{printf \"\\n\"}}\nGlobal Flags:\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}{{printf \"\\n\"}}\nAdditional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}\n {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}{{printf \"\\n\"}}\nUse \"{{.CommandPath}} [command] --help\" for more information about a command.{{end}}\"\n{{printf \"\\n\"}}`\n}",
"func (p *stats) Usage() string {\n\treturn \"admin stats\"\n}",
"func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"FunBox\",\n\t\tLicense: \"MIT License\",\n\t\tUpdateChecker: usage.UpdateChecker{\"funbox/init-exporter\", update.GitHubChecker},\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}",
"func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"ESSENTIAL KAOS\",\n\t\tLicense: \"Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>\",\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}",
"func (app *Application) Usage() string { return \"\" }",
"func PrintUsage(w io.Writer) { getopt.PrintUsage(w) }",
"func makeUsage(msg string) {\n\tusage := flag.Usage\n\tflag.Usage = func() {\n\t\tfmt.Fprintln(os.Stderr, msg)\n\t\tusage()\n\t}\n}",
"func (app *application) Usage() string { return \"package...\" }",
"func usageGraph(cmd string) string {\n\treturn \"Generates a DOT representation of a Bridge and writes it to standard \" +\n\t\t\"output.\\n\" +\n\t\t\"\\n\" +\n\t\t\"USAGE:\\n\" +\n\t\t\" \" + cmd + \" FILE\\n\"\n}",
"func setupUsage(fs *flag.FlagSet) {\n printNonEmpty := func(s string) {\n if s != \"\" {\n fmt.Fprintf(os.Stderr, \"%s\\n\", s)\n }\n }\n tmpUsage := fs.Usage\n fs.Usage = func() {\n printNonEmpty(CommandLineHelpUsage)\n tmpUsage()\n printNonEmpty(CommandLineHelpFooter)\n }\n}",
"func (cli *CLI) printUsage() {\n\tfmt.Println(\"Usage:\")\n\tfmt.Printf(\" getbal -address ADDRESS\\t Gets the balance for an address.\\n\")\n\tfmt.Printf(\" create -address ADDRESS\\t Creates a blockchain and sends genesis reward to address.\\n\")\n\tfmt.Printf(\" print\\t Prints the blocks in the chain.\\n\")\n\tfmt.Printf(\" send -from FROM -to TO -amount AMOUNT\\t Sends amount of coins from one address to another.\\n\")\n\tfmt.Printf(\" createwallet\\t Creates a new Wallet.\\n\")\n\tfmt.Printf(\" listaddresses\\t List the addresses in the wallets file.\\n\")\n}",
"func (m *Manager) Usage() string {\n\tbuf := bytes.NewBufferString(\"\\n\")\n\n\tfor _, c := range m.commands {\n\t\tfmt.Fprintln(buf, c.Usage)\n\t}\n\n\treturn buf.String()\n}",
"func UsageTemplate() string {\n\treturn `Usage:{{if .Runnable}}\n {{prepare .UseLine}}{{end}}{{if .HasAvailableSubCommands}}\n {{prepare .CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}\n\nAliases:\n {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{prepare .Example}}{{end}}{{if .HasAvailableSubCommands}}\n\nAvailable Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n {{rpad .Name .NamePadding }} {{prepare .Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}\n\nFlags:\n{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}\n\nUse \"{{ProgramName}} options\" for a list of global command-line options (applies to all commands).{{end}}\n`\n}",
"func UsageFunc(usageTemplate string) func() {\n\treturn func() {\n\t\tvar t *template.Template\n\t\tvar err error\n\t\tif t, err = template.New(\"usage\").Parse(usageTemplate); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif err := t.Execute(os.Stdout, os.Args[0]); err != nil {\n\t\t\tfmt.Fprintln(os.Stderr, err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\t// TODO(aoeu): Print default flags before printing usage examples.\n\t\tflag.PrintDefaults()\n\t\tos.Exit(2)\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
genAbout generates info about version
|
func genAbout(gitRev string) *usage.About {
about := &usage.About{
App: APP,
Version: VER,
Desc: DESC,
Year: 2006,
Owner: "ESSENTIAL KAOS",
License: "Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>",
AppNameColorTag: "{*}" + colorTagApp,
VersionColorTag: colorTagVer,
}
if gitRev != "" {
about.Build = "git:" + gitRev
}
return about
}
|
[
"func genAbout(gitRev string) *usage.About {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2006,\n\t\tOwner: \"FunBox\",\n\t\tLicense: \"MIT License\",\n\t\tUpdateChecker: usage.UpdateChecker{\"funbox/init-exporter\", update.GitHubChecker},\n\n\t\tAppNameColorTag: \"{*}\" + colorTagApp,\n\t\tVersionColorTag: colorTagVer,\n\t}\n\n\tif gitRev != \"\" {\n\t\tabout.Build = \"git:\" + gitRev\n\t}\n\n\treturn about\n}",
"func genUsage() *usage.Info {\n\tinfo := usage.NewInfo(\"\", \"url\", \"path\")\n\n\tinfo.AppNameColorTag = \"{*}\" + colorTagApp\n\n\tinfo.AddOption(OPT_YES, `Answer \"yes\" to all questions`)\n\tinfo.AddOption(OPT_NO_COLOR, \"Disable colors in output\")\n\tinfo.AddOption(OPT_HELP, \"Show this help message\")\n\tinfo.AddOption(OPT_VER, \"Show version\")\n\n\tinfo.AddExample(\n\t\t\"https://rbinstall.kaos.st /path/to/clone\",\n\t\t\"Clone EK repository to /path/to/clone\",\n\t)\n\n\treturn info\n}",
"func showAbout() {\n\tabout := &usage.About{\n\t\tApp: APP,\n\t\tVersion: VER,\n\t\tDesc: DESC,\n\t\tYear: 2009,\n\t\tOwner: \"ESSENTIAL KAOS\",\n\t\tLicense: \"Apache License, Version 2.0 <https://www.apache.org/licenses/LICENSE-2.0>\",\n\t\tUpdateChecker: usage.UpdateChecker{\"essentialkaos/shdoc\", update.GitHubChecker},\n\t}\n\n\tabout.Render()\n}",
"func (*SousVersion) Help() string { return sousVersionHelp }",
"func (app *application) about(w http.ResponseWriter, r *http.Request) {\n\n\tapp.renderAbout(w, r, \"about.page.tmpl\", &templateDataAbout{})\n}",
"func BuildDetails() string {\n\tlicenseInfo := `Licensed under the MIT License`\n\treturn fmt.Sprintf(`\ngitcomm version : %v\ngitcomm SHA-256 : %x\nCommit SHA-1 : %v\nCommit timestamp : %v\nBranch : %v\nGo version : %v\n%s.\nCopyright 2019-2020 @karantin2020.\n`,\n\t\tversion, ExecutableChecksum(), lastCommitSHA, lastCommitTime, gitBranch,\n\t\truntime.Version(), licenseInfo)\n}",
"func Info() string {\n\treturn fmt.Sprintf(\"%s %s git commit %s go version %s build date %s\", Application, Version, Revision, GoVersion, BuildRFC3339)\n}",
"func generate(p *models.Project) string {\n\tvar builder strings.Builder\n\tbuilder.WriteString(fmt.Sprintf(\"# %s\\n\", p.Name))\n\tplugins := []Plugin{description}\n\tif len(p.Badges) > 0 {\n\t\tplugins = append(plugins, addBadges)\n\t\tfor _, plugin := range plugins {\n\t\t\tplugin(&builder, p)\n\t\t}\n\t}\n\tbuilder.WriteString(fmt.Sprintf(\"### Author\\n\"))\n\tbuilder.WriteString(fmt.Sprintf(\"%s\\n\", p.Author))\n\tbuilder.WriteString(fmt.Sprintf(\"### LICENCE\\n\"))\n\treturn builder.String()\n}",
"func genUsage(w io.Writer, cmdName string) error {\n\t// Capture output from running:\n\t// foo -help\n\tbuf := new(bytes.Buffer)\n\tcmd := exec.Command(cmdName, \"-help\")\n\tcmd.Stderr = buf\n\tcmd.Run()\n\n\t// Add DO NOT EDIT notice.\n\tout := new(bytes.Buffer)\n\tfmt.Fprintf(out, \"// Generated by `usagen %s`; DO NOT EDIT.\\n\\n\", cmdName)\n\n\t// Prefix each line with \"// \".\n\tlines := strings.Split(buf.String(), \"\\n\")\n\tfor i, line := range lines {\n\t\tprefix := \"// \"\n\t\tif len(line) == 0 {\n\t\t\tif i == len(lines)-1 {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tprefix = \"//\"\n\t\t}\n\t\tfmt.Fprintf(out, \"%s%s\\n\", prefix, line)\n\t}\n\tout.WriteString(\"package main\\n\")\n\n\t// Write usage info to w.\n\tif _, err := w.Write(out.Bytes()); err != nil {\n\t\treturn errors.WithStack(err)\n\t}\n\treturn nil\n}",
"func initVersionInfo() {\n\tversion.Version = pmmVersion.Version\n\tversion.Revision = pmmVersion.FullCommit\n\tversion.Branch = pmmVersion.Branch\n\n\tif buildDate, err := strconv.ParseInt(pmmVersion.Timestamp, 10, 64); err != nil {\n\t\tversion.BuildDate = time.Unix(0, 0).Format(versionDataFormat)\n\t} else {\n\t\tversion.BuildDate = time.Unix(buildDate, 0).Format(versionDataFormat)\n\t}\n\n\tif pmmVersion.PMMVersion != \"\" {\n\t\tversion.Version += \"-pmm-\" + pmmVersion.PMMVersion\n\t\tkingpin.Version(pmmVersion.FullInfo())\n\t} else {\n\t\tkingpin.Version(version.Print(program))\n\t}\n\n\tkingpin.HelpFlag.Short('h')\n\tkingpin.CommandLine.Help = fmt.Sprintf(\"%s exports various MongoDB metrics in Prometheus format.\\n\", pmmVersion.ShortInfo())\n}",
"func (g *Generator) SetInfo(title, description, term, version string) *Generator {\n\tg.mu.Lock()\n\tdefer g.mu.Unlock()\n\n\tg.doc.Info = InfoObj{\n\t\tTitle: title,\n\t\tDescription: description,\n\t\tTermsOfService: term,\n\t\tVersion: version,\n\t}\n\n\tif g.oas3Proxy != nil {\n\t\tg.oas3Proxy.SpecEns().Info.Title = title\n\n\t\tif description != \"\" {\n\t\t\tg.oas3Proxy.SpecEns().Info.Description = &description\n\t\t}\n\n\t\tg.oas3Proxy.SpecEns().Info.Version = version\n\n\t\tif term != \"\" {\n\t\t\tg.oas3Proxy.SpecEns().Info.TermsOfService = &term\n\t\t}\n\t}\n\n\treturn g\n}",
"func version(w io.Writer, set *flag.FlagSet) error {\n\tfmt.Fprintf(w, \"GlobalSign EST Client %s\\n\", versionString)\n\treturn nil\n}",
"func (i Info) Generator() template.HTML {\n\treturn template.HTML(fmt.Sprintf(`<meta name=\"generator\" content=\"Hugo %s\" />`, CurrentVersion.String()))\n}",
"func PrintVersionInfo() {\n\tfmt.Println(\"Release Version:\", ShortVersion)\n\tfmt.Println(\"Git Commit Hash:\", GitSha1Version)\n\tfmt.Println(\"Build Time:\", BuildDate)\n}",
"func ShowVersion() {\n\tfmt.Printf(\"%s\", GetVersion())\n}",
"func printVersionInfo(version bool) {\n\tif version {\n\t\tfmt.Printf(\"Version : %s\\nBuildTime: %s\\n\", Version, BuildTime)\n\t\tos.Exit(0)\n\t}\n}",
"func showVersion() {\n\tfmt.Print(versionString())\n\tfmt.Print(releaseString())\n\tif devBuild && gitShortStat != \"\" {\n\t\tfmt.Printf(\"%s\\n%s\\n\", gitShortStat, gitFilesModified)\n\t}\n}",
"func BuildInfos() {\n\tfmt.Println(\"Program started at: \" + time.Now().String())\n\tfmt.Println(\"Build Time : \" + BuildTime)\n\tfmt.Println(\"Build Git Branch : \" + BuildGitBranch)\n\tfmt.Println(\"Build Git Rev : \" + BuildGitRev)\n\tfmt.Println(\"Build Git Commit : \" + BuildGitCommit)\n\tfmt.Println(\"Submarine Version : \" + VERSION)\n}",
"func (o *Options) BuildInfoString() string {\n\treturn fmt.Sprintf(\"(%v v%v, Release: %s)\", o.BinaryName, o.Version, o.Release)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
TestExecute feeds input to the CLI and validates results. scan() is implicitly tested here.
|
func TestExecute(t *testing.T) {
fmt.Println("TestExecute start")
var inputSource *bytes.Buffer
ipTest := []IPTest{
{"127.0.0.1", "9999", 1, 1},
{"8.8.8.8", "443", 1, 0},
{"::1", "9999", 1, 1},
{"127.0.0.1 ::1", "9999", 2, 2}}
for _, v := range ipTest {
inputSource = bytes.NewBuffer([]byte(fmt.Sprintf("setport %s\n", v.port)))
runCLI(inputSource)
inputSource = bytes.NewBuffer([]byte("setips " + v.ips + "\n"))
runCLI(inputSource)
inputSource = bytes.NewBuffer([]byte("execute\n"))
runCLI(inputSource)
inputSource = bytes.NewBuffer([]byte("results\n"))
runCLI(inputSource)
errors := 0
for j := 0; j < len(results); j++ {
if results[j].Error != nil && *results[j].Error != scan.NoError {
errors++
}
}
if len(results) != v.expectedResults || errors != v.expectedErrors {
t.Errorf("Unexpected scan results for IPs: %s, results: %+v", v.ips, results)
}
}
fmt.Println("TestExecute done")
}
|
[
"func TestExecute(t *testing.T) {\n\tif status, err := testCmd.Execute([]string{\"test\", \"-top\", \"19\"}); err != nil {\n\t\tt.Error(\"Command.Execute: got error:\\n\", err)\n\t} else if status != ExitUsage {\n\t\tt.Errorf(\"Command.Execute: got ExitStatus '%d' expected '%d'\", status, ExitUsage)\n\t} else if !strings.Contains(output.String(), \"${name} ${shortFlags}:\\n\\nExecute\") {\n\t\tt.Error(\"Command.Execute: expected output to contain Usage with ExitUsage, got:\\n\", output.String())\n\t}\n\n\tif status, err := testCmd.SubCommands[0].Execute([]string{\"test\", \"secondary\"}); err != nil {\n\t\tt.Error(\"Command.Execute: got error:\\n\", err)\n\t} else if status != ExitCmd {\n\t\tt.Errorf(\"Command.Execute: got ExitStatus '%d' expected '%d'\", status, ExitCmd)\n\t}\n\n\tif _, err := testCmd.Execute([]string{\"test\", \"---hello\"}); err == nil {\n\t\tt.Error(\"Command.Execute: expected error with invalid flags\")\n\t} else if _, ok := err.(*ErrParseFlags); !ok {\n\t\tt.Error(\"Command.Execute: expected error of type *ErrParseFlags with invalid flags:\\n\", err)\n\t}\n}",
"func (c *testComamnd) Execute() {\n\n\t// Parse subcommand args first.\n\tif len(os.Args) < 4 {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\n\tserviceRef := os.Args[2]\n\ttestEndpoint := os.Args[3]\n\trunnerType := os.Args[4]\n\n\t// Validate presence and values of args.\n\tif &serviceRef == nil || strings.HasPrefix(serviceRef, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif &testEndpoint == nil || strings.HasPrefix(testEndpoint, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif &runnerType == nil || strings.HasPrefix(runnerType, \"-\") {\n\t\tfmt.Println(\"test command require <apiName:apiVersion> <testEndpoint> <runner> args\")\n\t\tos.Exit(1)\n\t}\n\tif _, validChoice := runnerChoices[runnerType]; !validChoice {\n\t\tfmt.Println(\"<runner> should be one of: HTTP, SOAP, SOAP_UI, POSTMAN, OPEN_API_SCHEMA, ASYNC_API_SCHEMA, GRPC_PROTOBUF, GRAPHQL_SCHEMA\")\n\t\tos.Exit(1)\n\t}\n\n\t// Then parse flags.\n\ttestCmd := flag.NewFlagSet(\"test\", flag.ExitOnError)\n\n\tvar microcksURL string\n\tvar keycloakURL string\n\tvar keycloakClientID string\n\tvar keycloakClientSecret string\n\tvar waitFor string\n\tvar secretName string\n\tvar filteredOperations string\n\tvar operationsHeaders string\n\tvar insecureTLS bool\n\tvar caCertPaths string\n\tvar verbose bool\n\n\ttestCmd.StringVar(µcksURL, \"microcksURL\", \"\", \"Microcks API URL\")\n\ttestCmd.StringVar(&keycloakClientID, \"keycloakClientId\", \"\", \"Keycloak Realm Service Account ClientId\")\n\ttestCmd.StringVar(&keycloakClientSecret, \"keycloakClientSecret\", \"\", \"Keycloak Realm Service Account ClientSecret\")\n\ttestCmd.StringVar(&waitFor, \"waitFor\", \"5sec\", \"Time to wait for test to finish\")\n\ttestCmd.StringVar(&secretName, \"secretName\", \"\", \"Secret to use for connecting test endpoint\")\n\ttestCmd.StringVar(&filteredOperations, \"filteredOperations\", \"\", \"List of operations to launch a test for\")\n\ttestCmd.StringVar(&operationsHeaders, \"operationsHeaders\", \"\", \"Override of operations headers as JSON string\")\n\ttestCmd.BoolVar(&insecureTLS, \"insecure\", false, \"Whether to accept insecure HTTPS connection\")\n\ttestCmd.StringVar(&caCertPaths, \"caCerts\", \"\", \"Comma separated paths of CRT files to add to Root CAs\")\n\ttestCmd.BoolVar(&verbose, \"verbose\", false, \"Produce dumps of HTTP exchanges\")\n\ttestCmd.Parse(os.Args[5:])\n\n\t// Validate presence and values of flags.\n\tif len(microcksURL) == 0 {\n\t\tfmt.Println(\"--microcksURL flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif len(keycloakClientID) == 0 {\n\t\tfmt.Println(\"--keycloakClientId flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif len(keycloakClientSecret) == 0 {\n\t\tfmt.Println(\"--keycloakClientSecret flag is mandatory. Check Usage.\")\n\t\tos.Exit(1)\n\t}\n\tif &waitFor == nil || (!strings.HasSuffix(waitFor, \"milli\") && !strings.HasSuffix(waitFor, \"sec\") && !strings.HasSuffix(waitFor, \"min\")) {\n\t\tfmt.Println(\"--waitFor format is wrong. Applying default 5sec\")\n\t\twaitFor = \"5sec\"\n\t}\n\n\t// Collect optional HTTPS transport flags.\n\tif insecureTLS {\n\t\tconfig.InsecureTLS = true\n\t}\n\tif len(caCertPaths) > 0 {\n\t\tconfig.CaCertPaths = caCertPaths\n\t}\n\tif verbose {\n\t\tconfig.Verbose = true\n\t}\n\n\t// Compute time to wait in milliseconds.\n\tvar waitForMilliseconds int64 = 5000\n\tif strings.HasSuffix(waitFor, \"milli\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-5], 0, 64)\n\t} else if strings.HasSuffix(waitFor, \"sec\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64)\n\t\twaitForMilliseconds = waitForMilliseconds * 1000\n\t} else if strings.HasSuffix(waitFor, \"min\") {\n\t\twaitForMilliseconds, _ = strconv.ParseInt(waitFor[:len(waitFor)-3], 0, 64)\n\t\twaitForMilliseconds = waitForMilliseconds * 60 * 1000\n\t}\n\n\t// Now we seems to be good ...\n\t// First - retrieve the Keycloak URL from Microcks configuration.\n\tmc := connectors.NewMicrocksClient(microcksURL)\n\tkeycloakURL, err := mc.GetKeycloakURL()\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when invoking Microcks client retrieving config: %s\", err)\n\t\tos.Exit(1)\n\t}\n\n\tvar oauthToken string = \"unauthentifed-token\"\n\tif keycloakURL != \"null\" {\n\t\t// If Keycloak is enabled, retrieve an OAuth token using Keycloak Client.\n\t\tkc := connectors.NewKeycloakClient(keycloakURL, keycloakClientID, keycloakClientSecret)\n\n\t\toauthToken, err = kc.ConnectAndGetToken()\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Got error when invoking Keycloack client: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\t//fmt.Printf(\"Retrieve OAuthToken: %s\", oauthToken)\n\t}\n\n\t// Then - launch the test on Microcks Server.\n\tmc.SetOAuthToken(oauthToken)\n\n\tvar testResultID string\n\ttestResultID, err = mc.CreateTestResult(serviceRef, testEndpoint, runnerType, secretName, waitForMilliseconds, filteredOperations, operationsHeaders)\n\tif err != nil {\n\t\tfmt.Printf(\"Got error when invoking Microcks client creating Test: %s\", err)\n\t\tos.Exit(1)\n\t}\n\t//fmt.Printf(\"Retrieve TestResult ID: %s\", testResultID)\n\n\t// Finally - wait before checking and loop for some time\n\ttime.Sleep(1 * time.Second)\n\n\t// Add 10.000ms to wait time as it's now representing the server timeout.\n\tnow := nowInMilliseconds()\n\tfuture := now + waitForMilliseconds + 10000\n\n\tvar success = false\n\tfor nowInMilliseconds() < future {\n\t\ttestResultSummary, err := mc.GetTestResult(testResultID)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Got error when invoking Microcks client check TestResult: %s\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tsuccess = testResultSummary.Success\n\t\tinProgress := testResultSummary.InProgress\n\t\tfmt.Printf(\"MicrocksClient got status for test \\\"%s\\\" - success: %s, inProgress: %s \\n\", testResultID, fmt.Sprint(success), fmt.Sprint(inProgress))\n\n\t\tif !inProgress {\n\t\t\tbreak\n\t\t}\n\n\t\tfmt.Println(\"MicrocksTester waiting for 2 seconds before checking again or exiting.\")\n\t\ttime.Sleep(2 * time.Second)\n\t}\n\n\tfmt.Printf(\"Full TestResult details are available here: %s/#/tests/%s \\n\", strings.Split(microcksURL, \"/api\")[0], testResultID)\n\n\tif !success {\n\t\tos.Exit(1)\n\t}\n}",
"func TestPrepForExecute(t *testing.T) {\n\n\t// Start by messing things up so that we can tell that PrepForExecute(..) did something\n\tunitTesting = false\n\texecuteError = errors.New(\"this error should get cleared\")\n\n\t// Call our target function with some parameters that nothing else uses\n\tbuf := PrepForExecute(\"TestPrepForExecute\")\n\n\t// Execute the command, collecting output in our buffer\n\tExecute()\n\n\t// Convert the buffer to a string\n\toutput := buf.String()\n\n\t// Check everything out\n\trequire.NotNil(t, executeError, \"there should have been an error\")\n\trequire.Condition(t, func() bool {\n\t\treturn checkForExpectedSTSCallFailure(executeError)\n\t}, \"Error should have complained about nonexistent credentials file or invalid MFA token length\")\n\trequire.Empty(t, output, \"Output for an error condition should have been empty\")\n}",
"func Test(t *testing.T, p prog.Program, cases ...Case) {\n\tt.Helper()\n\tfor _, c := range cases {\n\t\tt.Run(strings.Join(c.args, \" \"), func(t *testing.T) {\n\t\t\tt.Helper()\n\t\t\tr := run(p, c.args, c.stdin)\n\t\t\tif r.exitCode != c.want.exitCode {\n\t\t\t\tt.Errorf(\"got exit code %v, want %v\", r.exitCode, c.want.exitCode)\n\t\t\t}\n\t\t\tif !matchOutput(r.stdout, c.want.stdout) {\n\t\t\t\tt.Errorf(\"got stdout %v, want %v\", r.stdout, c.want.stdout)\n\t\t\t}\n\t\t\tif !matchOutput(r.stderr, c.want.stderr) {\n\t\t\t\tt.Errorf(\"got stderr %v, want %v\", r.stderr, c.want.stderr)\n\t\t\t}\n\t\t})\n\t}\n}",
"func TestTestComand_Exec_Value(t *testing.T) {\n\t// com := NewTestCommand()\n\n}",
"func TestCLI(t *testing.T) {\n\t// parse configuration file 'solar-conf.yaml' in local directory\n\t_, err := util.ReadConfiguration()\n\tif err != nil {\n\t\tfmt.Println(\"unable to read the configuration file\")\n\t\tfmt.Println(err)\n\t}\n\n\t// initialise command line options\n\tutil.ParseCommandLineOptions()\n\n\t// create model\n\tm := model.GetModel()\n \n\t// start the main event loop\n\tengine.StartDispatcher(m)\n\n\t// get the command line interface\n\tshell := cli.Shell(m)\n\n\t// load commands from a file\n\tcmds, err := LoadCommands()\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tt.Errorf(\"%s\", err)\n\t}\n\n\tfmt.Println(\"Executing tests:\")\n\tfmt.Println(\"Nr. Command\")\n\tfmt.Println(\"------------------------------------------------------------\")\n\tfor index, cmd := range cmds {\n\t\t// skip empty command lines\n\t\tif cmd[0] == \"\" {\n\t\t\tcontinue\n\t\t}\n\n\t\t// construct command line string\n\t\tcmdline := strings.Join(cmd, \" \")\n\n\t\t// log the command line\n\t\tfmt.Printf(\"%03d %s\\n\", index, cmdline)\n\n\t\t// process\n\t\terr = shell.Process(cmd...)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Command failed: %s\\n%s\", cmdline, err)\n\t\t}\n\t}\n}",
"func TestExecuteCmdReader(t *testing.T) {\n\tshell := CmdShell{}\n\tif invalidOutput, _, err := shell.ExecuteCmdReader(invalidCmd); invalidOutput != nil && err == nil {\n\t\tt.Errorf(\"CmdReader didn't error on invalid cmd\")\n\t}\n\n\toutput, _, err := shell.ExecuteCmdReader(validReaderCmd)\n\tif err != nil {\n\t\tt.Errorf(\"Valid CmdReader cmd error'd out %v\", err)\n\t}\n\n\tstdout, stderr := output[0], output[1]\n\n\tstdoutScanner := bufio.NewScanner(stdout)\n\tgo func() {\n\t\tfor stdoutScanner.Scan() {\n\t\t\tif line := stdoutScanner.Text(); line != \"stdout\" {\n\t\t\t\tt.Errorf(\"CmdReader failed, expected %v, got %v\", \"stdout\", line)\n\t\t\t}\n\t\t}\n\t}()\n\n\tstderrScanner := bufio.NewScanner(stderr)\n\tgo func() {\n\t\tfor stderrScanner.Scan() {\n\t\t\tif line := stderrScanner.Text(); line != \"stderr\" {\n\t\t\t\tt.Errorf(\"CmdReader failed, expected %v, got %v\", \"stderr\", line)\n\t\t\t}\n\t\t}\n\t}()\n}",
"func TestExecuteFile(t *testing.T) {\n\tvar inputfile = \"samples/file_input.txt\"\n\n\tExecuteFile(inputfile)\n\n}",
"func TestExecuteCmd(t *testing.T) {\n\tshell := CmdShell{}\n\tif _, err := shell.ExecuteCmd(invalidCmd); err == nil {\n\t\tt.Errorf(\"Cmd didn't error on invalid cmd\")\n\t}\n\n\tif validOutput, err := shell.ExecuteCmd(validCmd); validOutput == nil || err != nil || bytes.Equal(validOutput, []byte(\"hello\")) {\n\t\tt.Errorf(\"Cmd failed, expected %v, got %v\", \"hello\", string(validOutput))\n\t}\n}",
"func TestRunCommand(t *testing.T) {\n\t// Override execCommand with our fake version\n\texecCommand = fakeExecCommand\n\tdefer func() { execCommand = origExec }()\n\n\t// Define our test command and arguments\n\ttestCommand := \"echo\"\n\ttestArgs := []string{\"pizza\", \"sushi\"}\n\ttestCmd := append([]string{testCommand}, testArgs...)\n\texpectedCmd := fmt.Sprint(testCmd)\n\n\tactualCmd, _ := runCommand(testCommand, testArgs)\n\n\t// Compare the result with our expectations\n\tstructsMatch := reflect.DeepEqual(expectedCmd, actualCmd)\n\n\tif !structsMatch {\n\t\tt.Errorf(\"\\nExpected: %#v\\nReceived: %#v\", expectedCmd, actualCmd)\n\t}\n}",
"func TestExecute(t *testing.T) {\n\t// execute := RootCmd.Execute\n\texited := false\n\t// RootCmd.Execute = func(*cobra.Command) error {\n\t// \treturn errors.New(\"mock\")\n\t// }\n\tosExit = func(int) {\n\t\texited = true\n\t}\n\n\tdefer func() {\n\t\t// RootCmd.Execute = execute\n\t\tosExit = os.Exit\n\t}()\n\n\toutErr := new(bytes.Buffer)\n\tRootCmd.SetErr(outErr)\n\tRootCmd.SetArgs([]string{\"--option-that-will-never-be-used\"})\n\tExecute()\n\n\tif !exited {\n\t\tt.Errorf(`Would not have exited on RootCmd execution error`)\n\t}\n}",
"func (t *Test) Exec() (err error) {\n\ts, e, err := Exec(t.Command)\n\tif err != nil {\n\t\tt.Result.Error(err)\n\t\treturn err\n\t}\n\tt.stdOut = s\n\tt.stdErr = e\n\tt.Result.Success()\n\treturn nil\n}",
"func (s *Spec) ExecuteTest(testPath string) []Test {\n\tvar tests []Test\n\n\tswitch s.Entry {\n\tcase \"argv\":\n\t\tif testPath == \"\" {\n\t\t\tpanic(\"Test path is empty\")\n\t\t}\n\t\ttests = s.execArgv(testPath)\n\tcase \"http\":\n\t\ttests = s.execHTTP()\n\tdefault:\n\t\tpanic(fmt.Errorf(\"cannot run test entry through: '%v'\", s.Entry))\n\t}\n\n\treturn tests\n}",
"func TestExecuteCommand(t *testing.T) {\n\n\tcases := []testCase{\n\t\t{\"message to bee replaced\", \"s/bee/be\", \"\", `message to be replaced`, false},\n\t\t{\"message to bee replaced\", \"s/bee/be\", \"123\", `message to be replaced`, false},\n\t\t{\"what if I typ the word typical\", \"s/typ/type\", \"\", `what if I type the word typical`, true},\n\t\t{\"baaad input\", \"s/bad\", \"\", usage, true},\n\t\t{\"more baaad input\", \"s/baaad/\", \"\", usage, true},\n\t}\n\n\tfor _, tc := range cases {\n\t\tt.Run(tc.command, func(t *testing.T) {\n\n\t\t\tc := &plugin.Context{}\n\t\t\tpost := &model.Post{\n\t\t\t\tUserId: \"testUserId\",\n\t\t\t\tMessage: tc.command,\n\t\t\t\tChannelId: \"testChannelId\",\n\t\t\t}\n\n\t\t\tapi := &plugintest.API{}\n\n\t\t\tdefer api.AssertExpectations(t)\n\n\t\t\tconfig := &testAPIConfig{\n\t\t\t\tUser: &model.User{},\n\t\t\t\tPosts: []*model.Post{&model.Post{}},\n\t\t\t\tPost: &model.Post{},\n\t\t\t\tChannel: &model.Channel{},\n\t\t\t}\n\n\t\t\t//needs to test input before setting API expectations\n\t\t\tif _, err := splitAndValidateInput(tc.command); err != nil && tc.shouldFail {\n\t\t\t\tassert.NotNil(t, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tsetupAPI(api, config)\n\n\t\t\tp := setupTestPlugin(t, api)\n\n\t\t\tp.OnActivate()\n\n\t\t\treturnedPost, err := p.MessageWillBePosted(c, post)\n\t\t\tassert.Nil(t, returnedPost)\n\t\t\tassert.Equal(t, err, \"plugin.message_will_be_posted.dismiss_post\")\n\t\t})\n\t\tt.Run(tc.command+\" - Replace\", func(t *testing.T) {\n\t\t\toldAndNew, err := splitAndValidateInput(tc.command)\n\t\t\tif err != nil && tc.shouldFail {\n\t\t\t\tassert.NotNil(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.Equal(t, tc.expectedMessage, replace(tc.message, oldAndNew[0], oldAndNew[1]))\n\t\t})\n\t}\n}",
"func TestExecute(t *testing.T) {\n\tctx := context.Background()\n\n\t// Clear pre-existing golden files to avoid leaving stale ones around.\n\tif *updateGoldens {\n\t\tfiles, err := filepath.Glob(filepath.Join(*goldensDir, \"*.golden.json\"))\n\t\tif err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfor _, f := range files {\n\t\t\tif err := os.Remove(f); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t}\n\n\ttestCases := []struct {\n\t\tname string\n\t\tflags testsharderFlags\n\t\ttestSpecs []build.TestSpec\n\t\ttestDurations []build.TestDuration\n\t\ttestList []build.TestListEntry\n\t\tmodifiers []testsharder.TestModifier\n\t\tpackageRepos []build.PackageRepo\n\t\taffectedTests []string\n\t}{\n\t\t{\n\t\t\tname: \"no tests\",\n\t\t},\n\t\t{\n\t\t\tname: \"mixed device types\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\thostTestSpec(\"bar\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: 5,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tTotalRuns: 50,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Millisecond,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"affected tests\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic\"),\n\t\t\t\tfuchsiaTestSpec(\"not-affected\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic\", true),\n\t\t\t\ttestListEntry(\"not-affected\", false),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected-hermetic\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"affected nonhermetic tests\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic\"),\n\t\t\t\tfuchsiaTestSpec(\"not-affected\"),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected-nonhermetic\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"target test count\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetTestCount: 2,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo1\"),\n\t\t\t\tfuchsiaTestSpec(\"foo2\"),\n\t\t\t\tfuchsiaTestSpec(\"foo3\"),\n\t\t\t\tfuchsiaTestSpec(\"foo4\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"sharding by time\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: int((4 * time.Minute).Seconds()),\n\t\t\t\tperTestTimeoutSecs: int((10 * time.Minute).Seconds()),\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"slow\"),\n\t\t\t\tfuchsiaTestSpec(\"fast1\"),\n\t\t\t\tfuchsiaTestSpec(\"fast2\"),\n\t\t\t\tfuchsiaTestSpec(\"fast3\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: 2 * time.Second,\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tName: packageURL(\"slow\"),\n\t\t\t\t\tMedianDuration: 5 * time.Minute,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"max shards per env\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\t// Given expected test durations of 4 minutes for each test it's\n\t\t\t\t// impossible to satisfy both the target shard duration and the\n\t\t\t\t// max shards per environment, so the target shard duration\n\t\t\t\t// should effectively be ignored.\n\t\t\t\ttargetDurationSecs: int((5 * time.Minute).Seconds()),\n\t\t\t\tmaxShardsPerEnvironment: 2,\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected1\"),\n\t\t\t\tfuchsiaTestSpec(\"affected2\"),\n\t\t\t\tfuchsiaTestSpec(\"affected3\"),\n\t\t\t\tfuchsiaTestSpec(\"affected4\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected1\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected2\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic1\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic2\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: 4 * time.Minute,\n\t\t\t\t},\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"affected1\"),\n\t\t\t\tpackageURL(\"affected2\"),\n\t\t\t\tpackageURL(\"affected3\"),\n\t\t\t\tpackageURL(\"affected4\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected1\", true),\n\t\t\t\ttestListEntry(\"affected2\", true),\n\t\t\t\ttestListEntry(\"affected3\", true),\n\t\t\t\ttestListEntry(\"affected4\", true),\n\t\t\t\ttestListEntry(\"unaffected1\", true),\n\t\t\t\ttestListEntry(\"unaffected2\", true),\n\t\t\t\ttestListEntry(\"nonhermetic1\", false),\n\t\t\t\ttestListEntry(\"nonhermetic2\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"hermetic deps\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\thermeticDeps: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t\tpackageRepos: []build.PackageRepo{\n\t\t\t\t{\n\t\t\t\t\tPath: \"pkg_repo1\",\n\t\t\t\t\tBlobs: filepath.Join(\"pkg_repo1\", \"blobs\"),\n\t\t\t\t\tTargets: filepath.Join(\"pkg_repo1\", \"targets.json\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ffx deps\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tffxDeps: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply affected test\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\taffectedTestsMultiplyThreshold: 3,\n\t\t\t\ttargetDurationSecs: int(2 * time.Minute.Seconds()),\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"multiplied-affected-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-test\"),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Second,\n\t\t\t\t},\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tpackageURL(\"multiplied-affected-test\"),\n\t\t\t\tpackageURL(\"affected-test\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"multiplied-affected-test\",\n\t\t\t\t\tTotalRuns: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"test list with tags\",\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"hermetic-test\", true),\n\t\t\t\ttestListEntry(\"nonhermetic-test\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"skip unaffected tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-nonhermetic-test\", false),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\").Name,\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\").Name,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"run all tests if no affected tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"affected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-nonhermetic-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"affected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-nonhermetic-test\", false),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multiply unaffected hermetic tests\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\tskipUnaffected: true,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\"),\n\t\t\t\tfuchsiaTestSpec(\"unaffected-hermetic-multiplied-test\"),\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"unaffected-hermetic-test\", true),\n\t\t\t\ttestListEntry(\"affected-nonhermetic-test\", false),\n\t\t\t\ttestListEntry(\"unaffected-hermetic-multiplied-test\", true),\n\t\t\t},\n\t\t\taffectedTests: []string{\n\t\t\t\tfuchsiaTestSpec(\"affected-nonhermetic-test\").Name,\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t{\n\t\t\t\t\tName: \"unaffected-hermetic-multiplied-test\",\n\t\t\t\t\tTotalRuns: 100,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"various modifiers\",\n\t\t\tflags: testsharderFlags{\n\t\t\t\ttargetDurationSecs: 5,\n\t\t\t},\n\t\t\ttestSpecs: []build.TestSpec{\n\t\t\t\tfuchsiaTestSpec(\"foo\"),\n\t\t\t\tfuchsiaTestSpec(\"bar\"),\n\t\t\t\tfuchsiaTestSpec(\"baz\"),\n\t\t\t},\n\t\t\tmodifiers: []testsharder.TestModifier{\n\t\t\t\t// default modifier\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 2,\n\t\t\t\t},\n\t\t\t\t// multiplier\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t\t// change maxAttempts (but multiplier takes precedence)\n\t\t\t\t{\n\t\t\t\t\tName: \"foo\",\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t\t// change maxAttempts, set affected\n\t\t\t\t{\n\t\t\t\t\tName: \"bar\",\n\t\t\t\t\tAffected: true,\n\t\t\t\t\tTotalRuns: -1,\n\t\t\t\t\tMaxAttempts: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\ttestList: []build.TestListEntry{\n\t\t\t\ttestListEntry(\"foo\", false),\n\t\t\t\ttestListEntry(\"bar\", true),\n\t\t\t\ttestListEntry(\"baz\", false),\n\t\t\t},\n\t\t\ttestDurations: []build.TestDuration{\n\t\t\t\t{\n\t\t\t\t\tName: \"*\",\n\t\t\t\t\tMedianDuration: time.Millisecond,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tgoldenBasename := strings.ReplaceAll(tc.name, \" \", \"_\") + \".golden.json\"\n\t\t\tgoldenFile := filepath.Join(*goldensDir, goldenBasename)\n\n\t\t\tif *updateGoldens {\n\t\t\t\ttc.flags.outputFile = goldenFile\n\t\t\t} else {\n\t\t\t\ttc.flags.outputFile = filepath.Join(t.TempDir(), goldenBasename)\n\t\t\t}\n\n\t\t\ttc.flags.buildDir = t.TempDir()\n\t\t\tif len(tc.modifiers) > 0 {\n\t\t\t\ttc.flags.modifiersPath = writeTempJSONFile(t, tc.modifiers)\n\t\t\t}\n\t\t\tif len(tc.affectedTests) > 0 {\n\t\t\t\t// Add a newline to the end of the file to test that it still calculates the\n\t\t\t\t// correct number of affected tests even with extra whitespace.\n\t\t\t\ttc.flags.affectedTestsPath = writeTempFile(t, strings.Join(tc.affectedTests, \"\\n\")+\"\\n\")\n\t\t\t}\n\t\t\tif tc.flags.ffxDeps {\n\t\t\t\tsdkManifest := map[string]interface{}{\n\t\t\t\t\t\"atoms\": []interface{}{},\n\t\t\t\t}\n\t\t\t\tsdkManifestPath := filepath.Join(tc.flags.buildDir, \"sdk\", \"manifest\", \"core\")\n\t\t\t\tif err := os.MkdirAll(filepath.Dir(sdkManifestPath), os.ModePerm); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t\tif err := jsonutil.WriteToFile(sdkManifestPath, sdkManifest); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Write test-list.json.\n\t\t\tif err := jsonutil.WriteToFile(\n\t\t\t\tfilepath.Join(tc.flags.buildDir, testListPath),\n\t\t\t\tbuild.TestList{Data: tc.testList, SchemaID: \"experimental\"},\n\t\t\t); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t\twriteDepFiles(t, tc.flags.buildDir, tc.testSpecs)\n\t\t\tfor _, repo := range tc.packageRepos {\n\t\t\t\tif err := os.MkdirAll(filepath.Join(tc.flags.buildDir, repo.Path), 0o700); err != nil {\n\t\t\t\t\tt.Fatal(err)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tm := &fakeModules{\n\t\t\t\ttestSpecs: tc.testSpecs,\n\t\t\t\ttestDurations: tc.testDurations,\n\t\t\t\tpackageRepositories: tc.packageRepos,\n\t\t\t}\n\t\t\tif err := execute(ctx, tc.flags, m); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\n\t\t\tif !*updateGoldens {\n\t\t\t\twant := readShards(t, goldenFile)\n\t\t\t\tgot := readShards(t, tc.flags.outputFile)\n\t\t\t\tif diff := cmp.Diff(want, got); diff != \"\" {\n\t\t\t\t\tt.Errorf(strings.Join([]string{\n\t\t\t\t\t\t\"Golden file mismatch!\",\n\t\t\t\t\t\t\"To fix, run `tools/integration/testsharder/update_goldens.sh\",\n\t\t\t\t\t\tdiff,\n\t\t\t\t\t}, \"\\n\"))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}",
"func TestExecute(t *testing.T) {\n\t/*\n\t\tFirst part of the test - check to ensure that the application force-stops in\n\t\tcase the root command returns an error while running - also check the error\n\t\tcode being returned.\n\n\t\tPatch the `Execute()` method of the root command to always throw an error.\n\t*/\n\n\t// Generate a root command\n\tcmd := *cmd // use a copy\n\n\tmonkey.PatchInstanceMethod(\n\t\treflect.TypeOf(&cmd),\n\t\t\"Execute\",\n\t\tfunc(command *cobra.Command) error {\n\t\t\treturn errors.New(\"temporary error\")\n\t\t},\n\t)\n\n\tdefer monkey.UnpatchInstanceMethod(\n\t\treflect.TypeOf(&cmd),\n\t\t\"Execute\",\n\t)\n\n\t// Patch the exit method to fail in case of an unexpected error code\n\tdefer monkey.Unpatch(os.Exit)\n\tmonkey.Patch(os.Exit, func(code int) {\n\t\tif code != commons.UnexpectedError {\n\t\t\tt.Errorf(\n\t\t\t\t\"(entryPoint/Execute) unexpected exit code, expected %v found %v\",\n\t\t\t\tcommons.UnexpectedError,\n\t\t\t\tcode,\n\t\t\t)\n\t\t}\n\t})\n\n\t// Running the method.\n\tExecute()\n}",
"func Execute() {\n\n\texitCh := make(chan bool, 1)\n\terrCh := make(chan error)\n\tctx, cancel := context.WithCancel(context.Background())\n\tvar scanner *targetScanner\n\t//var opts options\n\n\t//opts.Parse()\n\n\t// Create directories if they dont exist\n\terr := createEchidnaDirs()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tgreeting()\n\tgo closeHandler(ctx, cancel, exitCh)\n\tgo errorHandler(ctx, errCh)\n\n\t// not used until i decide to add a web UI or themes scanner\n\t// Inject our target into the scanner based on the users choice (-p/--plugin or -t/--theme)\n\t// Select WordPress Plugins as a target if nothing is selected\n\t// if *opts.Plugins {\n\tfmt.Println(\"Preparing the scanner. Happy bug hunting!\")\n\tfmt.Println(\"Once the scanning has started check the inspect folder in this directory.\")\n\tplugins, err := wp.NewPlugins(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tscanner = newScanner(plugins)\n\t// }\n\t// if *opts.Themes {\n\t// \tlog.Fatal(\"This functionality isn't built yet. We only have WordPress Plugins for now.\")\n\t// }\n\n\t// Add the initial scanner information such as pages, # of objects to scan, etc\n\terr = scanner.Target.AddInfo(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// not used until I decide to add web UI or theme scanner\n\t// if the user selected web (-w or --web) from the commandline then start\n\t// // the webserver, otherwise kick off the cli version.\n\t// if *opts.Web {\n\t// \tgo webStart(ctx, errCh, scanner)\n\t// } else {\n\t// \tscanner.Started = true\n\t// \tgo scanner.Target.Scan(ctx, errCh)\n\t// }\n\tscanner.Started = true\n\tgo scanner.Target.Scan(ctx, errCh)\n\n\t// block here until we are finished or have received a cancel()\n\tselect {\n\tcase <-ctx.Done():\n\t\tfmt.Printf(\"\\nExecution canceled. Waiting for close handler to perform cleanup.\")\n\t\t<-exitCh\n\t\tfmt.Println(\"Cleanup complete.\")\n\t\tos.Exit(0)\n\tcase <-exitCh:\n\t\tos.Exit(0)\n\t}\n\n}",
"func (t TestCases) Run(fn func(string) (string, string), hideInput bool) {\n\tfor _, test := range t {\n\t\tpart1, part2 := fn(test.Input)\n\t\tpassedPart1 := part1 == test.ExpectedPart1 || test.ExpectedPart1 == \"\"\n\t\tpassedPart2 := part2 == test.ExpectedPart2 || test.ExpectedPart2 == \"\"\n\t\tpassed := passedPart1 && passedPart2\n\n\t\tif !passed && !hideInput {\n\t\t\tfmt.Println(\"Input \", test.Input)\n\t\t}\n\t\tif !passedPart1 {\n\t\t\tfmt.Println(\" - PART1: \", part1, \" but expected \", test.ExpectedPart1)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tif !passedPart2 {\n\t\t\tfmt.Println(\" - PART2: \", part2, \" but expected \", test.ExpectedPart2)\n\t\t\tos.Exit(1)\n\t\t}\n\t}\n}",
"func (s *Stack) Execute() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\n\tfor scanner.Scan() {\n\t\tstrs := strings.Split(scanner.Text(), \" \")\n\n\t\tswitch strings.ToLower(strs[0]) {\n\t\tcase \"new\":\n\t\t\ts.New()\n\t\tcase \"check\":\n\t\t\ts.Check()\n\t\tcase \"length\":\n\t\t\ts.Length()\n\t\tcase \"print\":\n\t\t\ts.Print()\n\t\tcase \"add\":\n\t\t\tif len(strs[1]) > 0 {\n\t\t\t\tinteger, _ := strconv.Atoi(strs[1])\n\t\t\t\ts.Add(integer)\n\t\t\t} else {\n\t\t\t\tfmt.Println(\"Please enter an integer!\")\n\t\t\t}\n\t\tcase \"pop\":\n\t\t\ts.Pop()\n\t\tcase \"quit\":\n\t\t\tos.Exit(3)\n\t\tcase \"help\":\n\t\t\tprintHelp()\n\t\tdefault:\n\t\t\tfmt.Println(\"Invalid entry. Please type 'help' for valid entries.\")\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\tfmt.Fprintln(os.Stderr, \"error: \", err)\n\t\tos.Exit(1)\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CreateTilesetSource creates a new tileset source. This function simply calls PutTilesetSource. The provided JSON path should point to a file containing one GeoJSON feature object per line.
|
func (c *Client) CreateTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {
return c.PutTilesetSource(ctx, tilesetID, jsonReader)
}
|
[
"func (c *Client) PutTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {\n\turl := baseURL +\n\t\t\"/tilesets/v1/sources/\" + c.username + \"/\" + tilesetID +\n\t\t\"?access_token=\" + c.accessToken\n\n\tvar jsonResp NewTilesetSourceResponse\n\tresp, err := putMultipart(ctx, c.httpClient, url, \"filenamedoesntmatter\", jsonReader)\n\tif err != nil {\n\t\treturn jsonResp, fmt.Errorf(\"upload %w failed, %v\", ErrOperation, err)\n\t}\n\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn jsonResp, fmt.Errorf(\"upload %w failed, non-200 response: %v\", ErrOperation, resp.StatusCode)\n\t}\n\n\tif err = json.NewDecoder(resp.Body).Decode(&jsonResp); err != nil {\n\t\treturn jsonResp, fmt.Errorf(\"%w failed, err: %v\", ErrParse, err)\n\t}\n\n\treturn jsonResp, nil\n}",
"func (t *Tileset) UploadGeoJSON(pathToFile string) (*UploadResponse, error) {\n\tpostURL := fmt.Sprintf(\"%s/%s/sources/%s/%s\", apiName, apiVersion, t.username, t.tilesetID)\n\tuploadResponse := &UploadResponse{}\n\tres, err := t.base.PostUploadFileRequest(postURL, pathToFile, \"file\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(res, uploadResponse)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn uploadResponse, nil\n\n}",
"func NewJSONSource(b []byte) (*MapSource, error) {\n\tv := make(map[string]interface{})\n\terr := json.Unmarshal(b, &v)\n\treturn NewMapSource(v), err\n}",
"func (t *Tileset) CreateTileset(pathToFile string) (*base.MapboxAPIMessage, error) {\n\tmaboxAPIMessage := &base.MapboxAPIMessage{}\n\trecipeJSON, err := os.Open(pathToFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer recipeJSON.Close()\n\n\tdata, _ := ioutil.ReadAll(recipeJSON)\n\tres, err := t.base.PostRequest(t.postURL(), data)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tjson.Unmarshal(res, &maboxAPIMessage)\n\n\treturn maboxAPIMessage, nil\n\n}",
"func NewTileSet(ctx context.Context, path string) (t *pb.TileSet, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tt = &pb.TileSet{}\n\td := tsx.NewDecoder(f)\n\terr = d.Decode(t)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"marshal\")\n\t\treturn\n\t}\n\treturn\n}",
"func CreateOSMSource(uri string, cachePath string) Source {\n\n\t/*\n\t * Create OSM tile source.\n\t */\n\tsrc := osmSourceStruct{\n\t\tcachePath: cachePath,\n\t\turi: uri,\n\t}\n\n\treturn &src\n}",
"func (s *Service) CreateSource(ctx context.Context, src *influxdb.Source) error {\n\terr := s.kv.Update(ctx, func(tx Tx) error {\n\t\tsrc.ID = s.IDGenerator.ID()\n\n\t\t// Generating an organization id if it missing or invalid\n\t\tif !src.OrganizationID.Valid() {\n\t\t\tsrc.OrganizationID = s.IDGenerator.ID()\n\t\t}\n\n\t\treturn s.putSource(ctx, tx, src)\n\t})\n\tif err != nil {\n\t\treturn &influxdb.Error{\n\t\t\tErr: err,\n\t\t}\n\t}\n\treturn nil\n}",
"func (client FeatureStateClient) CreateStatesetPreparer(ctx context.Context, datasetID string, statesetCreateRequestBody StylesObject, description string) (*http.Request, error) {\n urlParameters := map[string]interface{} {\n \"geography\": autorest.Encode(\"path\",client.Geography),\n }\n\n const APIVersion = \"2.0\"\n queryParameters := map[string]interface{} {\n \"api-version\": APIVersion,\n \"datasetId\": autorest.Encode(\"query\",datasetID),\n }\n if len(description) > 0 {\n queryParameters[\"description\"] = autorest.Encode(\"query\",description)\n }\n\n preparer := autorest.CreatePreparer(\nautorest.AsContentType(\"application/json; charset=utf-8\"),\nautorest.AsPost(),\nautorest.WithCustomBaseURL(\"https://{geography}.atlas.microsoft.com\", urlParameters),\nautorest.WithPath(\"/featureStateSets\"),\nautorest.WithJSON(statesetCreateRequestBody),\nautorest.WithQueryParameters(queryParameters))\n return preparer.Prepare((&http.Request{}).WithContext(ctx))\n }",
"func NewSource(r io.Reader) (conf.Sourcer, error) {\n\treturn sourcers.From(json.Unmarshal, r)\n}",
"func TileFromJson(r io.Reader, traceExample Trace) (*Tile, error) {\n\t// Figure out the type of trace.\n\tvar factory func() Trace\n\tswitch traceExample.(type) {\n\tcase *GoldenTrace:\n\t\tfactory = func() Trace { return NewGoldenTrace() }\n\tcase *PerfTrace:\n\t\tfactory = func() Trace { return NewPerfTrace() }\n\t}\n\n\t// Decode everything, but the traces.\n\tdec := json.NewDecoder(r)\n\tvar rawTile TileWithRawTraces\n\terr := dec.Decode(&rawTile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Parse the traces.\n\ttraces := map[string]Trace{}\n\tfor k, rawJson := range rawTile.Traces {\n\t\tnewTrace := factory()\n\t\tif err = json.Unmarshal(rawJson, newTrace); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttraces[k] = newTrace.(Trace)\n\t}\n\n\treturn &Tile{\n\t\tTraces: traces,\n\t\tParamSet: rawTile.ParamSet,\n\t\tCommits: rawTile.Commits,\n\t\tScale: rawTile.Scale,\n\t\tTileIndex: rawTile.Scale,\n\t}, nil\n}",
"func (s *SourceService) CreateSource(ctx context.Context, src *influxdb.Source) error {\n\tif _, _, err := AuthorizeCreate(ctx, influxdb.SourcesResourceType, src.OrganizationID); err != nil {\n\t\treturn err\n\t}\n\treturn s.s.CreateSource(ctx, src)\n}",
"func NewFileSource(path string) (*MapSource, error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// changed how we handled a deferred file closure due to go lint security check https://github.com/securego/gosec/issues/512#issuecomment-675286833\n\tdefer func() {\n\t\tif cerr := f.Close(); cerr != nil {\n\t\t\tfmt.Printf(\"Error closing file: %s\\n\", cerr)\n\t\t}\n\t}()\n\tb, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tm, err := NewJSONSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\tm, err = NewYAMLSource(b)\n\tif err == nil {\n\t\treturn m, nil\n\t}\n\treturn nil, fmt.Errorf(\"could not determine file format for %s\", path)\n}",
"func WithJSONFile(filename string) *JSONSource {\n\treturn &JSONSource{\n\t\tfilename: filename,\n\t}\n}",
"func (a *SourcesApiService) CreateSource(ctx context.Context, workspace string, collection string) ApiCreateSourceRequest {\n\treturn ApiCreateSourceRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t\tworkspace: workspace,\n\t\tcollection: collection,\n\t}\n}",
"func NewCreateanewCFSourceSetRequestWithBody(server string, contentType string, body io.Reader) (*http.Request, error) {\n\tvar err error\n\n\tqueryUrl, err := url.Parse(server)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tbasePath := fmt.Sprintf(\"/cfsourcesets\")\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(\"POST\", queryUrl.String(), body)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(\"Content-Type\", contentType)\n\treturn req, nil\n}",
"func (c *FromURICreator) CreateSource(ctx *core.Context,\n\tioParams *bql.IOParams, params data.Map) (core.Source, error) {\n\n\tcs, err := c.createCaptureFromURI(ctx, ioParams, params)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\trewindFlag := false\n\tif rf, err := params.Get(rewindablePath); err == nil {\n\t\tif rewindFlag, err = data.AsBool(rf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t} else if rf, err := params.Get(rewindPath); err == nil {\n\t\tctx.Log().Warnln(`\"rewind\" is deprecated and not supported in later releases in favor of \"rewindable\"`)\n\t\tif rewindFlag, err = data.AsBool(rf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// Use Rewindable and ImplementSourceStop helpers that can enable this\n\t// source to stop thread-safe.\n\tif rewindFlag {\n\t\treturn core.NewRewindableSource(cs), nil\n\t}\n\treturn core.ImplementSourceStop(cs), nil\n}",
"func (this *osmSourceStruct) tilePath(template string, zoom uint8, x uint32, y uint32) string {\n\tzoom64 := uint64(zoom)\n\tzoomString := strconv.FormatUint(zoom64, BASE_DECIMAL)\n\tx64 := uint64(x)\n\txString := strconv.FormatUint(x64, BASE_DECIMAL)\n\ty64 := uint64(y)\n\tyString := strconv.FormatUint(y64, BASE_DECIMAL)\n\ttemplate = strings.Replace(template, TEMPLATE_ZOOM, zoomString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_X, xString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_Y, yString, ALL)\n\treturn template\n}",
"func NewJSONSource(opts ...JSONSourceOption) (*JSONSource, error) {\n\tj := &JSONSource{\n\t\trecords: make(chan record, 3),\n\t}\n\tfor _, opt := range opts {\n\t\topt(j)\n\t}\n\n\tif j.listener == nil {\n\t\tvar err error\n\t\tj.listener, err = net.Listen(\"tcp\", j.addr)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tj.listener = tcpKeepAliveListener{j.listener.(*net.TCPListener)}\n\n\tj.server = &http.Server{\n\t\tAddr: j.addr,\n\t\tHandler: j,\n\t}\n\tgo func() {\n\t\terr := j.server.Serve(j.listener)\n\t\tif err != nil {\n\t\t\tj.records <- record{err: errors.Wrap(err, \"starting server\")}\n\t\t\tclose(j.records)\n\t\t}\n\t}()\n\treturn j, nil\n}",
"func NewSource(\n\tfset *token.FileSet, path string,\n\tfilter func(fs.FileInfo) bool, mode parser.Mode) (doc NodeSet, err error) {\n\n\tpkgs, err := parser.ParseDir(fset, path, filter, mode)\n\tif err != nil {\n\t\treturn\n\t}\n\treturn NodeSet{Data: &oneNode{astPackages(pkgs)}}, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PutTilesetSource replaces a tileset source with new data, or creates a new tileset source if it does not already exist. The provided path should point to a file containing one GeoJSON feature object per line.
|
func (c *Client) PutTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {
url := baseURL +
"/tilesets/v1/sources/" + c.username + "/" + tilesetID +
"?access_token=" + c.accessToken
var jsonResp NewTilesetSourceResponse
resp, err := putMultipart(ctx, c.httpClient, url, "filenamedoesntmatter", jsonReader)
if err != nil {
return jsonResp, fmt.Errorf("upload %w failed, %v", ErrOperation, err)
}
if resp.StatusCode != http.StatusOK {
return jsonResp, fmt.Errorf("upload %w failed, non-200 response: %v", ErrOperation, resp.StatusCode)
}
if err = json.NewDecoder(resp.Body).Decode(&jsonResp); err != nil {
return jsonResp, fmt.Errorf("%w failed, err: %v", ErrParse, err)
}
return jsonResp, nil
}
|
[
"func (c *Client) CreateTilesetSource(ctx context.Context, tilesetID string, jsonReader io.Reader) (NewTilesetSourceResponse, error) {\n\treturn c.PutTilesetSource(ctx, tilesetID, jsonReader)\n}",
"func (f *File) SetSource(source []string) {\n\tf.mutex.Lock()\n\tf.source = source\n\tf.mutex.Unlock()\n}",
"func (this *osmSourceStruct) tilePath(template string, zoom uint8, x uint32, y uint32) string {\n\tzoom64 := uint64(zoom)\n\tzoomString := strconv.FormatUint(zoom64, BASE_DECIMAL)\n\tx64 := uint64(x)\n\txString := strconv.FormatUint(x64, BASE_DECIMAL)\n\ty64 := uint64(y)\n\tyString := strconv.FormatUint(y64, BASE_DECIMAL)\n\ttemplate = strings.Replace(template, TEMPLATE_ZOOM, zoomString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_X, xString, ALL)\n\ttemplate = strings.Replace(template, TEMPLATE_Y, yString, ALL)\n\treturn template\n}",
"func (m *ItemFacet) SetSource(value PersonDataSourcesable)() {\n err := m.GetBackingStore().Set(\"source\", value)\n if err != nil {\n panic(err)\n }\n}",
"func SetSource(theMap core.Element, newSource core.Element, attributeName core.AttributeName, trans *core.Transaction) error {\n\tref := theMap.GetFirstOwnedReferenceRefinedFromURI(CrlMapSourceURI, trans)\n\tif ref == nil {\n\t\treturn errors.New(\"CrlMaps.SetSource called with map that does not have a source reference\")\n\t}\n\treturn ref.SetReferencedConcept(newSource, attributeName, trans)\n}",
"func NewTileSet(ctx context.Context, path string) (t *pb.TileSet, err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer f.Close()\n\tt = &pb.TileSet{}\n\td := tsx.NewDecoder(f)\n\terr = d.Decode(t)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"marshal\")\n\t\treturn\n\t}\n\treturn\n}",
"func (s *Service) PutSource(ctx context.Context, src *influxdb.Source) error {\n\treturn s.kv.Update(ctx, func(tx Tx) error {\n\t\treturn s.putSource(ctx, tx, src)\n\t})\n}",
"func (t *Tileset) UploadGeoJSON(pathToFile string) (*UploadResponse, error) {\n\tpostURL := fmt.Sprintf(\"%s/%s/sources/%s/%s\", apiName, apiVersion, t.username, t.tilesetID)\n\tuploadResponse := &UploadResponse{}\n\tres, err := t.base.PostUploadFileRequest(postURL, pathToFile, \"file\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = json.Unmarshal(res, uploadResponse)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn uploadResponse, nil\n\n}",
"func (c *CSV) SetSource(s string) {\n\tc.source = NewResource(s, FmtCSV, File)\n}",
"func (h *Hop) SetSource(src string) {\n\tif h == nil || len(h.Errors) == 0 {\n\t\treturn\n\t}\n\n\th.Errors[0].Source = src\n}",
"func SetSourceRow(cols []*ColName, sr SourceRow) error {\n\tfor _, col := range cols {\n\t\tif col.Metadata.TableName == \"\" {\n\t\t\treturn fmt.Errorf(\"col missing metadata: %#v\", col)\n\t\t}\n\t\tif col.Metadata.ColIndex > len(sr[col.Metadata.TableName])-1 {\n\t\t\treturn fmt.Errorf(\"index out of range to set column value: %s.%d\", col.Metadata.TableName, col.Metadata.ColIndex)\n\t\t}\n\t\tcol.Value = sr[col.Metadata.TableName][col.Metadata.ColIndex]\n\t}\n\treturn nil\n}",
"func (d *Database) SetTile(height, level, offset int, hashes []byte) error {\n\t_, err := d.db.Exec(\"INSERT INTO tiles (height, level, offset, hashes) VALUES (?, ?, ?, ?)\", height, level, offset, hashes)\n\treturn err\n}",
"func SetFromSourceToFile(src source.Source, dst, name string) error {\n\tif dst == \"\" {\n\t\treturn errors.New(\"dst file path is empty\")\n\t}\n\n\td, err := destination.NewFile(dst)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn SetFromSourceToDestination(src, d, name)\n}",
"func (m *Metric) SetSource(source string) {\n\tm.Lock()\n\tdefer m.Unlock()\n\tm.Source = source\n}",
"func (d *Dir) Set(path string, file reflow.File) {\n\tif d.contents == nil {\n\t\td.contents = make(map[string]reflow.File)\n\t}\n\td.contents[path] = file\n}",
"func (g *goldTryjobProcessor) upsertSourceFile(ctx context.Context, srcID schema.SourceFileID, fileName string, ingestedTime time.Time) interface{} {\n\tctx, span := trace.StartSpan(ctx, \"upsertSourceFile\")\n\tdefer span.End()\n\tconst statement = `UPSERT INTO SourceFiles (source_file_id, source_file, last_ingested)\nVALUES ($1, $2, $3)`\n\terr := crdbpgx.ExecuteTx(ctx, g.db, pgx.TxOptions{}, func(tx pgx.Tx) error {\n\t\t_, err := tx.Exec(ctx, statement, srcID, fileName, ingestedTime)\n\t\treturn err // Don't wrap - crdbpgx might retry\n\t})\n\treturn skerr.Wrap(err)\n}",
"func (s *Store) replacePluginCacheFileWithSource(pluginItem *PluginInfo, entityKey string) error {\n\tsourceFilePath := s.SourceFilePath(pluginItem, entityKey)\n\tcachedFilePath := s.cachedFilePath(pluginItem, entityKey)\n\treturn helpers.CopyFile(sourceFilePath, cachedFilePath)\n}",
"func (t *TransientDescriptor) SetSource(source *StableDescriptor) (*TransientDescriptor, error) {\n\tif t == nil {\n\t\treturn nil, errors.New(\"reference to transient descriptor is nil\")\n\t}\n\n\tif source == nil {\n\t\treturn nil, errors.New(\"nil pointer value for `source` parameter\")\n\t}\n\n\tt.Lock()\n\tdefer t.Unlock()\n\n\terr := source.IsStable()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tt.source = source\n\treturn t, nil\n}",
"func SetTemplate(t *template.Template, name, filename string) error {\n\n\t// Read template\n\tbuf, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Update if exists\n\tif tt := t.Lookup(name); tt != nil {\n\t\t_, err = tt.Parse(string(buf))\n\t\treturn err\n\t}\n\n\t// Allocate new name if not\n\t_, err = t.New(name).Parse(string(buf))\n\treturn err\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ParseHclInterface is used to convert an interface value representing a hcl2 body and return the interpolated value. Vars may be nil if there are no variables to interpolate.
|
func ParseHclInterface(val interface{}, spec hcldec.Spec, vars map[string]cty.Value) (cty.Value, hcl.Diagnostics, []error) {
evalCtx := &hcl.EvalContext{
Variables: vars,
Functions: GetStdlibFuncs(),
}
// Encode to json
var buf bytes.Buffer
enc := codec.NewEncoder(&buf, structs.JsonHandle)
err := enc.Encode(val)
if err != nil {
// Convert to a hcl diagnostics message
errorMessage := fmt.Sprintf("Label encoding failed: %v", err)
return cty.NilVal,
hcl.Diagnostics([]*hcl.Diagnostic{{
Severity: hcl.DiagError,
Summary: "Failed to encode label value",
Detail: errorMessage,
}}),
[]error{errors.New(errorMessage)}
}
// Parse the json as hcl2
hclFile, diag := hjson.Parse(buf.Bytes(), "")
if diag.HasErrors() {
return cty.NilVal, diag, formattedDiagnosticErrors(diag)
}
value, decDiag := hcldec.Decode(hclFile.Body, spec, evalCtx)
diag = diag.Extend(decDiag)
if diag.HasErrors() {
return cty.NilVal, diag, formattedDiagnosticErrors(diag)
}
return value, diag, nil
}
|
[
"func (cv *ConVar) Interface() (interface{}, error) {\n\treturn cv.value.Load(), nil\n}",
"func EvalInterface(infVitals map[string]cache.Vitals, inf tc.ServerInterfaceInfo) (bool, string) {\n\tif !inf.Monitor {\n\t\treturn true, \"\"\n\t}\n\n\tvitals, ok := infVitals[inf.Name]\n\tif !ok {\n\t\treturn false, \"not found in polled data\"\n\t}\n\n\tif inf.MaxBandwidth == nil {\n\t\treturn true, \"\"\n\t}\n\n\tif *inf.MaxBandwidth < uint64(vitals.KbpsOut) {\n\t\treturn false, \"maximum bandwidth exceeded\"\n\t}\n\n\treturn true, \"\"\n}",
"func (c *opticsCollector) ParseInterfaces(output string) ([]string, error) {\n\titems := []string{}\n\tifNameRegexp := regexp.MustCompile(`name=(.*) default-name`)\n\n\tmatches := ifNameRegexp.FindAllStringSubmatch(output, -1)\n\tfor _, match := range matches {\n\t\titems = append(items, match[1])\n\t}\n\treturn items, nil\n}",
"func ParseInterfaceData(myInterface interface{}) string {\n\tswitch v := myInterface.(type) {\n\tcase int:\n\t\treturn strconv.Itoa(v)\n\tcase float64:\n\t\treturn strconv.FormatFloat(v, 'f', -1, 64)\n\tcase string:\n\t\treturn string(v)\n\t}\n\treturn fmt.Sprintf(\"%s\", myInterface)\n}",
"func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterfaceInterfaceRef(ctx context.Context, interfaceId string, frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam FrinxOpenconfigInterfacesInterfacerefInterfaceRefRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\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-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/frinx-logging:interface-ref/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -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\t// body params\n\tlocalVarPostBody = &frinxOpenconfigInterfacesInterfacerefInterfaceRefBodyParam\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 (m *Message) unmarshalInterface(v interface{}) error {\n\tstrdata, err := stringMap(v)\n\tif err != nil {\n\t\treturn err\n\t}\n\tfor k, v := range strdata {\n\t\tswitch strings.ToLower(k) {\n\t\tcase \"id\":\n\t\t\tm.ID = v\n\t\tcase \"description\":\n\t\t\tm.Description = v\n\t\tcase \"hash\":\n\t\t\tm.Hash = v\n\t\tcase \"leftdelim\":\n\t\t\tm.LeftDelim = v\n\t\tcase \"rightdelim\":\n\t\t\tm.RightDelim = v\n\t\tcase \"zero\":\n\t\t\tm.Zero = v\n\t\tcase \"one\":\n\t\t\tm.One = v\n\t\tcase \"two\":\n\t\t\tm.Two = v\n\t\tcase \"few\":\n\t\t\tm.Few = v\n\t\tcase \"many\":\n\t\t\tm.Many = v\n\t\tcase \"other\":\n\t\t\tm.Other = v\n\t\t}\n\t}\n\treturn nil\n}",
"func (a *FrinxLoggingApiService) PutFrinxLoggingLoggingInterfacesInterface(ctx context.Context, interfaceId string, frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam FrinxLoggingLogginginterfacesstructuralInterfacesInterfaceRequest, nodeId string) (*http.Response, error) {\n\tvar (\n\t\tlocalVarHttpMethod = strings.ToUpper(\"Put\")\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-logging:logging/frinx-logging:interfaces/frinx-logging:interface/{interface-id}/\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"interface-id\"+\"}\", fmt.Sprintf(\"%v\", interfaceId), -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\t// body params\n\tlocalVarPostBody = &frinxLoggingLogginginterfacesstructuralInterfacesInterfaceBodyParam\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 ParseInterface(v interface{}) (map[string]interface{}, error) {\n\tb, err := json.Marshal(v)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Error marshalling value: %v\", err)\n\t}\n\tdecoder := json.NewDecoder(bytes.NewReader(b))\n\tdecoder.UseNumber()\n\n\tobj := map[string]interface{}{}\n\terr = decoder.Decode(&obj)\n\treturn obj, err\n}",
"func (d *MockDataResyncDSL) Interface(val *interfaces.Interfaces_Interface) vppclient.DataResyncDSL {\n\top := dsl.TxnOp{Key: interfaces.InterfaceKey(val.Name), Value: val}\n\td.Ops = append(d.Ops, op)\n\treturn d\n}",
"func (_Contract *ContractFilterer) ParseInterfaceChanged(log types.Log) (*ContractInterfaceChanged, error) {\n\tevent := new(ContractInterfaceChanged)\n\tif err := _Contract.contract.UnpackLog(event, \"InterfaceChanged\", log); err != nil {\n\t\treturn nil, err\n\t}\n\treturn event, nil\n}",
"func (rndr *Renderer) renderVppIPSecTunnelInterface(key string, tunnel *IPSecTunnelEndPoint) *vpp_interfaces.IPSecLink {\n\tvppIPSecTunnel := &vpp_interfaces.IPSecLink{}\n\treturn vppIPSecTunnel\n}",
"func (s *InterfaceStep) Interface() interface{} {\n\treturn s.value\n}",
"func LoadInterface(buf []byte, t interface{}) {\n\tbuffer := bytes.NewBuffer(buf)\n\tbinary.Read(buffer, binary.BigEndian, t)\n}",
"func ImportsInterface(pkg string, m *ir.Module) ([]byte, error) {\n\tasset, err := lookupTemplate(\"imports\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttmpl, err := template.New(\"imports\").Parse(string(asset))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdata := struct {\n\t\tPkg string\n\t\tImportedFuncs []importedFunc\n\t}{\n\t\tPkg: pkg,\n\t}\n\tfor _, f := range m.ImportedFunctions {\n\t\tdata.ImportedFuncs = append(data.ImportedFuncs, impFunc(f, true))\n\t}\n\tvar b bytes.Buffer\n\tif err := tmpl.Execute(&b, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn b.Bytes(), nil\n}",
"func intfFromTopoIF(t *topology.TopoIF) *Interface {\n\tintf := Interface{}\n\tintf.Id = spath.IntfID(t.IFID)\n\t// FIXME(kormat): to be changed when the topo format is updated.\n\tintf.LocAddrIdx = 0\n\tintf.IFAddr = overlay.NewUDP(t.Addr.IP, t.UdpPort)\n\tintf.RemoteAddr = &net.UDPAddr{IP: t.ToAddr.IP, Port: t.ToUdpPort}\n\tintf.RemoteIA = t.IA\n\tintf.BW = t.BW\n\tintf.MTU = t.MTU\n\tintf.Type = t.LinkType\n\treturn &intf\n}",
"func substituteInterface(ctx *Context, src interface{}, bs Bindings) (o interface{}, err error) {\n\tswitch src.(type) {\n\tcase string:\n\t\treturn substituteString(ctx, src.(string), bs)\n\tcase []interface{}:\n\t\tvs := make([]interface{}, len(src.([]interface{})))\n\t\tfor i, v := range src.([]interface{}) {\n\t\t\tswitch v.(type) {\n\t\t\tcase string:\n\t\t\t\tif vs[i], err = substituteString(ctx, v.(string), bs); nil != err {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\tif vs[i], err = substituteInterface(ctx, v, bs); nil != err {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn vs, nil\n\tcase map[string]interface{}:\n\t\tm := make(map[string]interface{})\n\t\tfor k, v := range src.(map[string]interface{}) {\n\t\t\t// A substitution of a map property could end\n\t\t\t// up being a non-string. If so, we protest.\n\t\t\tki, err := substituteString(ctx, k, bs)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tks, ok := ki.(string)\n\t\t\tif !ok {\n\t\t\t\terr = fmt.Errorf(\"substitution of %s was %#v, which isn't a string\", k, ki)\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tk = ks\n\t\t\tif m[k], err = substituteInterface(ctx, v, bs); nil != err {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t\treturn m, nil\n\tdefault:\n\t\treturn src, nil\n\t}\n}",
"func LoadValueIfFromInterface(val interface{}) (valIf ValueIf, err error) {\n\tswitch reflect.TypeOf(val).Kind() {\n\tcase reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8,\n\t\treflect.Uint16, reflect.Uint32, reflect.Uint64:\n\t\tvalIf, err = NewValueInt64(val)\n\tcase reflect.Bool:\n\t\tvalIf, err = NewValueBool(val)\n\tcase reflect.String:\n\t\tvalIf, err = NewValueString(val)\n\tcase reflect.Float32, reflect.Float64:\n\t\tvalIf, err = NewValueFloat64(val)\n\tdefault:\n\t\terr = powerr.New(powerr.ErrNotSupportValueType).StoreKV(\"Type\", reflect.TypeOf(val).Kind()).StoreStack()\n\t}\n\n\treturn valIf, err\n}",
"func (data *Data) Interface(s ...string) interface{} {\n\tx := *data\n\tvar y interface{}\n\n\tfor _, i := range s {\n\n\t\tif _, ok := x[i]; ok == false {\n\t\t\treturn nil\n\t\t}\n\n\t\tswitch x[i].(type) {\n\t\tdefault:\n\t\t\ty = x[i].(interface{})\n\n\t\tcase map[string]interface{}:\n\t\t\tx = x[i].(map[string]interface{})\n\t\t}\n\t}\n\treturn y\n}",
"func (d *Decoder) DecodeInterfaceLoose() (interface{}, error) {\n\tc, err := d.readCode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif msgpcode.IsFixedNum(c) {\n\t\treturn int64(int8(c)), nil\n\t}\n\tif msgpcode.IsFixedMap(c) {\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\t}\n\tif msgpcode.IsFixedArray(c) {\n\t\treturn d.decodeSlice(c)\n\t}\n\tif msgpcode.IsFixedString(c) {\n\t\treturn d.string(c)\n\t}\n\n\tswitch c {\n\tcase msgpcode.Nil:\n\t\treturn nil, nil\n\tcase msgpcode.False, msgpcode.True:\n\t\treturn d.bool(c)\n\tcase msgpcode.Float, msgpcode.Double:\n\t\treturn d.float64(c)\n\tcase msgpcode.Uint8, msgpcode.Uint16, msgpcode.Uint32, msgpcode.Uint64:\n\t\treturn d.uint(c)\n\tcase msgpcode.Int8, msgpcode.Int16, msgpcode.Int32, msgpcode.Int64:\n\t\treturn d.int(c)\n\tcase msgpcode.Bin8, msgpcode.Bin16, msgpcode.Bin32:\n\t\treturn d.bytes(c, nil)\n\tcase msgpcode.Str8, msgpcode.Str16, msgpcode.Str32:\n\t\treturn d.string(c)\n\tcase msgpcode.Array16, msgpcode.Array32:\n\t\treturn d.decodeSlice(c)\n\tcase msgpcode.Map16, msgpcode.Map32:\n\t\terr = d.s.UnreadByte()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn d.decodeMapDefault()\n\tcase msgpcode.FixExt1, msgpcode.FixExt2, msgpcode.FixExt4, msgpcode.FixExt8, msgpcode.FixExt16,\n\t\tmsgpcode.Ext8, msgpcode.Ext16, msgpcode.Ext32:\n\t\treturn d.decodeInterfaceExt(c)\n\t}\n\n\treturn 0, fmt.Errorf(\"msgpack: unknown code %x decoding interface{}\", c)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetStdlibFuncs returns the set of stdlib functions.
|
func GetStdlibFuncs() map[string]function.Function {
return map[string]function.Function{
"abs": stdlib.AbsoluteFunc,
"coalesce": stdlib.CoalesceFunc,
"concat": stdlib.ConcatFunc,
"hasindex": stdlib.HasIndexFunc,
"int": stdlib.IntFunc,
"jsondecode": stdlib.JSONDecodeFunc,
"jsonencode": stdlib.JSONEncodeFunc,
"length": stdlib.LengthFunc,
"lower": stdlib.LowerFunc,
"max": stdlib.MaxFunc,
"min": stdlib.MinFunc,
"reverse": stdlib.ReverseFunc,
"strlen": stdlib.StrlenFunc,
"substr": stdlib.SubstrFunc,
"upper": stdlib.UpperFunc,
}
}
|
[
"func GetAllBuiltinFunctions() []*BuiltinFunction {\n\treturn append([]*BuiltinFunction{}, builtinFuncs...)\n}",
"func Functions() []*decls.FunctionDecl {\n\treturn stdFunctions\n}",
"func GetFunctions() []string {\n\tout := make([]string, len(flist))\n\tcopy(out, flist)\n\treturn out\n}",
"func GetFuncs() template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"RandInt\": randInt,\n\t\t\"RandIntRange\": randIntRange,\n\t}\n}",
"func findFuncs(pkg *packages.Package) ([]string, error) {\n\tvar ret []string\n\tfor _, file := range pkg.GoFiles {\n\t\tcontent, err := ioutil.ReadFile(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tmatches := fuzzFuncRE.FindAllSubmatch(content, -1)\n\t\tfor _, match := range matches {\n\t\t\tret = append(ret, string(match[1]))\n\t\t}\n\t}\n\treturn ret, nil\n}",
"func getFns() map[string]*object.Builtin {\n\treturn map[string]*object.Builtin{\n\t\t// len(var:\"hello\")\n\t\t\"len\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.ARRAY_OBJ},\n\t\t\tFn: lenFn,\n\t\t},\n\t\t// rand(max:20)\n\t\t\"rand\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: randFn,\n\t\t},\n\t\t// exit(code:0)\n\t\t\"exit\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: exitFn,\n\t\t},\n\t\t// flag(\"my-flag\")\n\t\t\"flag\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: flagFn,\n\t\t},\n\t\t// pwd()\n\t\t\"pwd\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: pwdFn,\n\t\t},\n\t\t// camel(\"string\")\n\t\t\"camel\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: camelFn,\n\t\t},\n\t\t// snake(\"string\")\n\t\t\"snake\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: snakeFn,\n\t\t},\n\t\t// kebab(\"string\")\n\t\t\"kebab\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: kebabFn,\n\t\t},\n\t\t// cd() or cd(path)\n\t\t\"cd\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: cdFn,\n\t\t},\n\t\t// clamp(num, min, max)\n\t\t\"clamp\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: clampFn,\n\t\t},\n\t\t// echo(arg:\"hello\")\n\t\t\"echo\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: echoFn,\n\t\t},\n\t\t// int(string:\"123\")\n\t\t// int(number:\"123\")\n\t\t\"int\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: intFn,\n\t\t},\n\t\t// round(string:\"123.1\")\n\t\t// round(number:\"123.1\", 2)\n\t\t\"round\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: roundFn,\n\t\t},\n\t\t// floor(string:\"123.1\")\n\t\t// floor(number:123.1)\n\t\t\"floor\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: floorFn,\n\t\t},\n\t\t// ceil(string:\"123.1\")\n\t\t// ceil(number:123.1)\n\t\t\"ceil\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: ceilFn,\n\t\t},\n\t\t// number(string:\"1.23456\")\n\t\t\"number\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: numberFn,\n\t\t},\n\t\t// is_number(string:\"1.23456\")\n\t\t\"is_number\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ, object.NUMBER_OBJ},\n\t\t\tFn: isNumberFn,\n\t\t},\n\t\t// stdin()\n\t\t\"stdin\": &object.Builtin{\n\t\t\tNext: stdinNextFn,\n\t\t\tTypes: []string{},\n\t\t\tFn: stdinFn,\n\t\t},\n\t\t// env(variable:\"PWD\") or env(string:\"KEY\", string:\"VAL\")\n\t\t\"env\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: envFn,\n\t\t},\n\t\t// arg(position:1)\n\t\t\"arg\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: argFn,\n\t\t},\n\t\t// args()\n\t\t\"args\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: argsFn,\n\t\t},\n\t\t// type(variable:\"hello\")\n\t\t\"type\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: typeFn,\n\t\t},\n\t\t// fn.call(args_array)\n\t\t\"call\": &object.Builtin{\n\t\t\tTypes: []string{object.FUNCTION_OBJ, object.BUILTIN_OBJ},\n\t\t\tFn: callFn,\n\t\t},\n\t\t// chnk([...], int:2)\n\t\t\"chunk\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: chunkFn,\n\t\t},\n\t\t// split(string:\"hello\")\n\t\t\"split\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: splitFn,\n\t\t},\n\t\t// lines(string:\"a\\nb\")\n\t\t\"lines\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: linesFn,\n\t\t},\n\t\t// \"{}\".json()\n\t\t// Converts a valid JSON document to an ABS hash.\n\t\t\"json\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: jsonFn,\n\t\t},\n\t\t// \"a %s\".fmt(b)\n\t\t\"fmt\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: fmtFn,\n\t\t},\n\t\t// sum(array:[1, 2, 3])\n\t\t\"sum\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: sumFn,\n\t\t},\n\t\t// max(array:[1, 2, 3])\n\t\t\"max\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: maxFn,\n\t\t},\n\t\t// min(array:[1, 2, 3])\n\t\t\"min\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: minFn,\n\t\t},\n\t\t// reduce(array:[1, 2, 3], f(){}, accumulator)\n\t\t\"reduce\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: reduceFn,\n\t\t},\n\t\t// sort(array:[1, 2, 3])\n\t\t\"sort\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: sortFn,\n\t\t},\n\t\t// intersect(array:[1, 2, 3], array:[1, 2, 3])\n\t\t\"intersect\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: intersectFn,\n\t\t},\n\t\t// diff(array:[1, 2, 3], array:[1, 2, 3])\n\t\t\"diff\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: diffFn,\n\t\t},\n\t\t// union(array:[1, 2, 3], array:[1, 2, 3])\n\t\t\"union\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: unionFn,\n\t\t},\n\t\t// diff_symmetric(array:[1, 2, 3], array:[1, 2, 3])\n\t\t\"diff_symmetric\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: diffSymmetricFn,\n\t\t},\n\t\t// flatten(array:[1, 2, 3])\n\t\t\"flatten\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: flattenFn,\n\t\t},\n\t\t// flatten(array:[1, 2, 3])\n\t\t\"flatten_deep\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: flattenDeepFn,\n\t\t},\n\t\t// partition(array:[1, 2, 3])\n\t\t\"partition\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: partitionFn,\n\t\t},\n\t\t// map(array:[1, 2, 3], function:f(x) { x + 1 })\n\t\t\"map\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: mapFn,\n\t\t},\n\t\t// some(array:[1, 2, 3], function:f(x) { x == 2 })\n\t\t\"some\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: someFn,\n\t\t},\n\t\t// every(array:[1, 2, 3], function:f(x) { x == 2 })\n\t\t\"every\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: everyFn,\n\t\t},\n\t\t// find(array:[1, 2, 3], function:f(x) { x == 2 })\n\t\t\"find\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: findFn,\n\t\t},\n\t\t// filter(array:[1, 2, 3], function:f(x) { x == 2 })\n\t\t\"filter\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: filterFn,\n\t\t},\n\t\t// unique(array:[1, 2, 3])\n\t\t\"unique\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: uniqueFn,\n\t\t},\n\t\t// str(1)\n\t\t\"str\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: strFn,\n\t\t},\n\t\t// any(\"abc\", \"b\")\n\t\t\"any\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: anyFn,\n\t\t},\n\t\t// between(number, min, max)\n\t\t\"between\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: betweenFn,\n\t\t},\n\t\t// prefix(\"abc\", \"a\")\n\t\t\"prefix\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: prefixFn,\n\t\t},\n\t\t// suffix(\"abc\", \"a\")\n\t\t\"suffix\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: suffixFn,\n\t\t},\n\t\t// repeat(\"abc\", 3)\n\t\t\"repeat\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: repeatFn,\n\t\t},\n\t\t// replace(\"abc\", \"b\", \"f\", -1)\n\t\t\"replace\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: replaceFn,\n\t\t},\n\t\t// title(\"some thing\")\n\t\t\"title\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: titleFn,\n\t\t},\n\t\t// lower(\"ABC\")\n\t\t\"lower\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: lowerFn,\n\t\t},\n\t\t// upper(\"abc\")\n\t\t\"upper\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: upperFn,\n\t\t},\n\t\t// wait(`sleep 1 &`)\n\t\t\"wait\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: waitFn,\n\t\t},\n\t\t\"kill\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: killFn,\n\t\t},\n\t\t// trim(\"abc\")\n\t\t\"trim\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: trimFn,\n\t\t},\n\t\t// trim_by(\"abc\", \"c\")\n\t\t\"trim_by\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: trimByFn,\n\t\t},\n\t\t// index(\"abc\", \"c\")\n\t\t\"index\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: indexFn,\n\t\t},\n\t\t// last_index(\"abcc\", \"c\")\n\t\t\"last_index\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: lastIndexFn,\n\t\t},\n\t\t// shift([1,2,3])\n\t\t\"shift\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: shiftFn,\n\t\t},\n\t\t// reverse([1,2,3])\n\t\t\"reverse\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ, object.STRING_OBJ},\n\t\t\tFn: reverseFn,\n\t\t},\n\t\t// shuffle([1,2,3])\n\t\t\"shuffle\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: shuffleFn,\n\t\t},\n\t\t// push([1,2,3], 4)\n\t\t\"push\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: pushFn,\n\t\t},\n\t\t// pop([1,2,3], 4)\n\t\t\"pop\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ, object.HASH_OBJ},\n\t\t\tFn: popFn,\n\t\t},\n\t\t// keys([1,2,3]) returns array of indices\n\t\t// keys({\"a\": 1, \"b\": 2, \"c\": 3}) returns array of keys\n\t\t\"keys\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ, object.HASH_OBJ},\n\t\t\tFn: keysFn,\n\t\t},\n\t\t// values({\"a\": 1, \"b\": 2, \"c\": 3}) returns array of values\n\t\t\"values\": &object.Builtin{\n\t\t\tTypes: []string{object.HASH_OBJ},\n\t\t\tFn: valuesFn,\n\t\t},\n\t\t// items({\"a\": 1, \"b\": 2, \"c\": 3}) returns array of [key, value] tuples: [[a, 1], [b, 2] [c, 3]]\n\t\t\"items\": &object.Builtin{\n\t\t\tTypes: []string{object.HASH_OBJ},\n\t\t\tFn: itemsFn,\n\t\t},\n\t\t// join([1,2,3], \"-\")\n\t\t\"join\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: joinFn,\n\t\t},\n\t\t// sleep(3000)\n\t\t\"sleep\": &object.Builtin{\n\t\t\tTypes: []string{object.NUMBER_OBJ},\n\t\t\tFn: sleepFn,\n\t\t},\n\t\t// source(\"file.abs\") -- soure a file, with access to the global environment\n\t\t\"source\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: sourceFn,\n\t\t},\n\t\t// require(\"file.abs\") -- require a file without giving it access to the global environment\n\t\t\"require\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: requireFn,\n\t\t},\n\t\t// exec(command) -- execute command with interactive stdIO\n\t\t\"exec\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: execFn,\n\t\t},\n\t\t// eval(code) -- evaluates code in the context of the current ABS environment\n\t\t\"eval\": &object.Builtin{\n\t\t\tTypes: []string{object.STRING_OBJ},\n\t\t\tFn: evalFn,\n\t\t},\n\t\t// tsv([[1,2,3,4], [5,6,7,8]]) -- converts an array into a TSV string\n\t\t\"tsv\": &object.Builtin{\n\t\t\tTypes: []string{object.ARRAY_OBJ},\n\t\t\tFn: tsvFn,\n\t\t},\n\t\t// unix_ms() -- returns the current unix epoch, in milliseconds\n\t\t\"unix_ms\": &object.Builtin{\n\t\t\tTypes: []string{},\n\t\t\tFn: unixMsFn,\n\t\t},\n\t}\n}",
"func (l *AuthFuncListSafe) GetFuncs() []AuthFuncInstance {\n\tret := make([]AuthFuncInstance, len(l.funcList))\n\tl.listMutex.Lock()\n\tcopy(ret, l.funcList)\n\tl.listMutex.Unlock()\n\treturn ret\n}",
"func (s *Capabilities) GetSupportedFunctions() []byte {\n\tsupportedFunctions := []byte{}\n\n\tvar i byte\n\tfor i = 1; i < 255; i++ {\n\t\tif isBitSet(s.SupportedFunctions, i) {\n\t\t\tsupportedFunctions = append(supportedFunctions, i)\n\t\t}\n\t}\n\n\treturn supportedFunctions\n}",
"func StdLib() EnvOption {\n\treturn Lib(stdLibrary{})\n}",
"func getAllFuncs() template.FuncMap {\n\treturn template.FuncMap{\"markDown\": markDowner, \"date\": dater.FriendlyDater, \"holder\": holder}\n}",
"func isStdLib(pkg *packages.Package) bool {\n\tif pkg.Name == \"unsafe\" {\n\t\t// Special case unsafe stdlib, because it does not contain go files.\n\t\treturn true\n\t}\n\tif len(pkg.GoFiles) == 0 {\n\t\treturn false\n\t}\n\tprefix := build.Default.GOROOT\n\tsep := string(filepath.Separator)\n\tif !strings.HasSuffix(prefix, sep) {\n\t\tprefix += sep\n\t}\n\treturn strings.HasPrefix(pkg.GoFiles[0], prefix)\n}",
"func (p *PKGBUILD) GetFunctions() (out []string) {\n\tdone := make(map[string]bool)\n\tinfos := p.info.Variables()\n\tfor _, e := range infos {\n\t\tname := e.Name()\n\t\tif !done[name] {\n\t\t\tdone[name] = true\n\t\t\tout = append(out, name)\n\t\t}\n\t}\n\treturn\n}",
"func (t *TestCluster) ListNativeFunctions() []string {\n\treturn t.NativeFuncs\n}",
"func exportedFuncs(f *ast.File, fset *token.FileSet) []*ast.FuncDecl {\n\tfns := []*ast.FuncDecl{}\n\tfor _, decl := range f.Decls {\n\t\t// get all top level functions\n\t\tif fn, ok := decl.(*ast.FuncDecl); ok {\n\t\t\t// skip all methods\n\t\t\tif fn.Recv != nil {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tname := fn.Name.Name\n\t\t\t// look for exported functions only\n\t\t\tif unicode.IsUpper([]rune(name)[0]) {\n\t\t\t\tfns = append(fns, fn)\n\t\t\t}\n\t\t}\n\t}\n\treturn fns\n}",
"func initBuiltinFuncs(builtin *types.Package) {\n\tfns := [...]struct {\n\t\tname string\n\t\ttparams []typeTParam\n\t\tparams []typeXParam\n\t\tresult xType\n\t}{\n\t\t{\"copy\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"dst\", xtSlice}, {\"src\", xtSlice}}, types.Typ[types.Int]},\n\t\t// func [Type any] copy(dst, src []Type) int\n\n\t\t{\"close\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"c\", xtChanIn}}, nil},\n\t\t// func [Type any] close(c chan<- Type)\n\n\t\t{\"append\", []typeTParam{{\"Type\", any}}, []typeXParam{{\"slice\", xtSlice}, {\"elems\", xtEllipsis}}, xtSlice},\n\t\t// func [Type any] append(slice []Type, elems ...Type) []Type\n\n\t\t{\"delete\", []typeTParam{{\"Key\", comparable}, {\"Elem\", any}}, []typeXParam{{\"m\", xtMap}, {\"key\", 0}}, nil},\n\t\t// func [Key comparable, Elem any] delete(m map[Key]Elem, key Key)\n\t}\n\tgbl := builtin.Scope()\n\tfor _, fn := range fns {\n\t\ttparams := newTParams(fn.tparams)\n\t\tn := len(fn.params)\n\t\tparams := make([]*types.Var, n)\n\t\tfor i, param := range fn.params {\n\t\t\ttyp := newXParamType(tparams, param.typ)\n\t\t\tparams[i] = types.NewParam(token.NoPos, builtin, param.name, typ)\n\t\t}\n\t\tvar ellipsis bool\n\t\tif tidx, ok := fn.params[n-1].typ.(int); ok && (tidx&xtEllipsis) != 0 {\n\t\t\tellipsis = true\n\t\t}\n\t\tvar results *types.Tuple\n\t\tif fn.result != nil {\n\t\t\ttyp := newXParamType(tparams, fn.result)\n\t\t\tresults = types.NewTuple(types.NewParam(token.NoPos, builtin, \"\", typ))\n\t\t}\n\t\ttsig := NewTemplateSignature(tparams, nil, types.NewTuple(params...), results, ellipsis, tokFlagApproxType)\n\t\tvar tfn types.Object = NewTemplateFunc(token.NoPos, builtin, fn.name, tsig)\n\t\tif fn.name == \"append\" { // append is a special case\n\t\t\tappendString := NewInstruction(token.NoPos, builtin, \"append\", appendStringInstr{})\n\t\t\ttfn = NewOverloadFunc(token.NoPos, builtin, \"append\", appendString, tfn)\n\t\t} else if fn.name == \"copy\" {\n\t\t\t// func [S string] copy(dst []byte, src S) int\n\t\t\ttparams := newTParams([]typeTParam{{\"S\", tstring}})\n\t\t\tdst := types.NewParam(token.NoPos, builtin, \"dst\", types.NewSlice(types.Typ[types.Byte]))\n\t\t\tsrc := types.NewParam(token.NoPos, builtin, \"src\", tparams[0])\n\t\t\tret := types.NewParam(token.NoPos, builtin, \"\", types.Typ[types.Int])\n\t\t\ttsig := NewTemplateSignature(tparams, nil, types.NewTuple(dst, src), types.NewTuple(ret), false)\n\t\t\tcopyString := NewTemplateFunc(token.NoPos, builtin, \"copy\", tsig)\n\t\t\ttfn = NewOverloadFunc(token.NoPos, builtin, \"copy\", copyString, tfn)\n\t\t}\n\t\tgbl.Insert(tfn)\n\t}\n\toverloads := [...]struct {\n\t\tname string\n\t\tfns [3]typeBFunc\n\t}{\n\t\t{\"complex\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"r\", types.UntypedFloat}, {\"i\", types.UntypedFloat}}, types.UntypedComplex},\n\t\t\t{[]typeBParam{{\"r\", types.Float32}, {\"i\", types.Float32}}, types.Complex64},\n\t\t\t{[]typeBParam{{\"r\", types.Float64}, {\"i\", types.Float64}}, types.Complex128},\n\t\t}},\n\t\t// func complex(r, i untyped_float) untyped_complex\n\t\t// func complex(r, i float32) complex64\n\t\t// func complex(r, i float64) complex128\n\n\t\t{\"real\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"c\", types.UntypedComplex}}, types.UntypedFloat},\n\t\t\t{[]typeBParam{{\"c\", types.Complex64}}, types.Float32},\n\t\t\t{[]typeBParam{{\"c\", types.Complex128}}, types.Float64},\n\t\t}},\n\t\t// func real(c untyped_complex) untyped_float\n\t\t// func real(c complex64) float32\n\t\t// func real(c complex128) float64\n\n\t\t{\"imag\", [...]typeBFunc{\n\t\t\t{[]typeBParam{{\"c\", types.UntypedComplex}}, types.UntypedFloat},\n\t\t\t{[]typeBParam{{\"c\", types.Complex64}}, types.Float32},\n\t\t\t{[]typeBParam{{\"c\", types.Complex128}}, types.Float64},\n\t\t}},\n\t\t// func imag(c untyped_complex) untyped_float\n\t\t// func imag(c complex64) float32\n\t\t// func imag(c complex128) float64\n\t}\n\tfor _, overload := range overloads {\n\t\tfns := []types.Object{\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[0]),\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[1]),\n\t\t\tnewBFunc(builtin, overload.name, overload.fns[2]),\n\t\t}\n\t\tgbl.Insert(NewOverloadFunc(token.NoPos, builtin, overload.name, fns...))\n\t}\n\t// func panic(v interface{})\n\t// func recover() interface{}\n\t// func print(args ...interface{})\n\t// func println(args ...interface{})\n\temptyIntfVar := types.NewVar(token.NoPos, builtin, \"v\", TyEmptyInterface)\n\temptyIntfTuple := types.NewTuple(emptyIntfVar)\n\temptyIntfSlice := types.NewSlice(TyEmptyInterface)\n\temptyIntfSliceVar := types.NewVar(token.NoPos, builtin, \"args\", emptyIntfSlice)\n\temptyIntfSliceTuple := types.NewTuple(emptyIntfSliceVar)\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"panic\", types.NewSignature(nil, emptyIntfTuple, nil, false)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"recover\", types.NewSignature(nil, nil, emptyIntfTuple, false)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"print\", types.NewSignature(nil, emptyIntfSliceTuple, nil, true)))\n\tgbl.Insert(types.NewFunc(token.NoPos, builtin, \"println\", types.NewSignature(nil, emptyIntfSliceTuple, nil, true)))\n\n\t// new & make are special cases, they require to pass a type.\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"new\", newInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"make\", makeInstr{}))\n\n\t// len & cap are special cases, because they may return a constant value.\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"len\", lenInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, builtin, \"cap\", capInstr{}))\n\n\t// unsafe\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Sizeof\", unsafeSizeofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Alignof\", unsafeAlignofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Offsetof\", unsafeOffsetofInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Add\", unsafeAddInstr{}))\n\tgbl.Insert(NewInstruction(token.NoPos, types.Unsafe, \"Slice\", unsafeSliceInstr{}))\n}",
"func TypeFuncs(p *Pkg, t *Type) ([]*Func, error) {\n\tvar out []*Func\n\n\terr := p.EachDecl(func(fset *token.FileSet, d ast.Decl) error {\n\t\tfd, ok := d.(*ast.FuncDecl)\n\t\tif !ok {\n\t\t\treturn nil\n\t\t}\n\t\tif fd.Recv == nil {\n\t\t\treturn nil\n\t\t}\n\t\tswitch tp := fd.Recv.List[0].Type.(type) {\n\t\tcase *ast.Ident: // func (myType) Name() {...}\n\t\t\tif tp.Name == t.Name {\n\t\t\t\tout = append(out, &Func{Name: fd.Name.Name})\n\t\t\t}\n\t\tcase *ast.StarExpr: // func (*myType) Name() {...}\n\t\t\tif ident, ok := tp.X.(*ast.Ident); ok {\n\t\t\t\tif ident.Name == t.Name {\n\t\t\t\t\tout = append(out, &Func{Name: fd.Name.Name})\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error on each pkg\")\n\t}\n\n\treturn out, nil\n}",
"func Funcs(pkg *packages.Package, keep func(f Func) bool) []Func {\n\tvar r []Func\n\n\tfor _, def := range pkg.TypesInfo.Defs {\n\t\tif def == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tf, ok := def.(*types.Func)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tsig, ok := f.Type().(*types.Signature)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\trepr := Func{\n\t\t\tSig: sig,\n\t\t\tDecl: f,\n\t\t}\n\n\t\tif keep(repr) {\n\t\t\tr = append(r, repr)\n\t\t}\n\t}\n\n\treturn r\n}",
"func (dp *Dumper) getFunctions() ([]functionSchema, error) {\n\tquery := \"\" +\n\t\t\"SELECT n.nspname, p.proname, l.lanname, \" +\n\t\t\" CASE WHEN l.lanname = 'internal' THEN p.prosrc ELSE pg_get_functiondef(p.oid) END as definition, \" +\n\t\t\" pg_get_function_arguments(p.oid) \" +\n\t\t\"FROM pg_proc p \" +\n\t\t\"LEFT JOIN pg_namespace n ON p.pronamespace = n.oid \" +\n\t\t\"LEFT JOIN pg_language l ON p.prolang = l.oid \" +\n\t\t\"LEFT JOIN pg_type t ON t.oid = p.prorettype \" +\n\t\t\"WHERE n.nspname NOT IN ('pg_catalog', 'information_schema');\"\n\n\tvar fs []functionSchema\n\trows, err := dp.conn.DB.Query(query)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer rows.Close()\n\n\tfor rows.Next() {\n\t\tvar f functionSchema\n\t\tif err := rows.Scan(&f.schemaName, &f.name, &f.language, &f.statement, &f.arguments); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tf.schemaName, f.name = quoteIdentifier(f.schemaName), quoteIdentifier(f.name)\n\t\tfs = append(fs, f)\n\t}\n\n\treturn fs, nil\n}",
"func FlowBuiltInFunctions(impls FlowBuiltinImpls) StandardLibraryFunctions {\n\treturn StandardLibraryFunctions{\n\t\tNewStandardLibraryFunction(\n\t\t\t\"AuthAccount\",\n\t\t\tauthAccountFunctionType,\n\t\t\tauthAccountFunctionDocString,\n\t\t\timpls.CreateAccount,\n\t\t),\n\t\tNewStandardLibraryFunction(\n\t\t\t\"getAccount\",\n\t\t\tgetAccountFunctionType,\n\t\t\tgetAccountFunctionDocString,\n\t\t\timpls.GetAccount,\n\t\t),\n\t\tNewStandardLibraryFunction(\n\t\t\t\"log\",\n\t\t\tLogFunctionType,\n\t\t\tlogFunctionDocString,\n\t\t\timpls.Log,\n\t\t),\n\t\tNewStandardLibraryFunction(\n\t\t\t\"getCurrentBlock\",\n\t\t\tgetCurrentBlockFunctionType,\n\t\t\tgetCurrentBlockFunctionDocString,\n\t\t\timpls.GetCurrentBlock,\n\t\t),\n\t\tNewStandardLibraryFunction(\n\t\t\t\"getBlock\",\n\t\t\tgetBlockFunctionType,\n\t\t\tgetBlockFunctionDocString,\n\t\t\timpls.GetBlock,\n\t\t),\n\t\tNewStandardLibraryFunction(\n\t\t\t\"unsafeRandom\",\n\t\t\tunsafeRandomFunctionType,\n\t\t\tunsafeRandomFunctionDocString,\n\t\t\timpls.UnsafeRandom,\n\t\t),\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
New creates a new kubernetes executor.
|
func New(config Config) *KubernetesExecutor {
k := &KubernetesExecutor{
kl: config.Kubelet,
updateChan: config.Updates,
state: disconnectedState,
tasks: make(map[string]*kuberTask),
pods: make(map[string]*api.Pod),
sourcename: config.SourceName,
client: config.APIClient,
done: make(chan struct{}),
outgoing: make(chan func() (mesos.Status, error), 1024),
dockerClient: config.Docker,
suicideTimeout: config.SuicideTimeout,
kubeletFinished: config.KubeletFinished,
suicideWatch: &suicideTimer{},
shutdownAlert: config.ShutdownAlert,
exitFunc: config.ExitFunc,
podStatusFunc: config.PodStatusFunc,
initialRegComplete: make(chan struct{}),
staticPodsConfigPath: config.StaticPodsConfigPath,
}
// watch pods from the given pod ListWatch
_, k.podController = framework.NewInformer(config.PodLW, &api.Pod{}, podRelistPeriod, &framework.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
pod := obj.(*api.Pod)
log.V(4).Infof("pod %s/%s created on apiserver", pod.Namespace, pod.Name)
k.handleChangedApiserverPod(pod)
},
UpdateFunc: func(oldObj, newObj interface{}) {
pod := newObj.(*api.Pod)
log.V(4).Infof("pod %s/%s updated on apiserver", pod.Namespace, pod.Name)
k.handleChangedApiserverPod(pod)
},
DeleteFunc: func(obj interface{}) {
pod := obj.(*api.Pod)
log.V(4).Infof("pod %s/%s deleted on apiserver", pod.Namespace, pod.Name)
},
})
return k
}
|
[
"func New(kl *kubelet.Kubelet, ch chan<- interface{}, ns string, cl *client.Client, w watch.Interface, dc dockertools.DockerInterface) *KubernetesExecutor {\n\t//TODO(jdef) do something real with these events..\n\tevents := w.ResultChan()\n\tif events != nil {\n\t\tgo func() {\n\t\t\tfor e := range events {\n\t\t\t\t// e ~= watch.Event { ADDED, *api.Event }\n\t\t\t\tlog.V(1).Info(e)\n\t\t\t}\n\t\t}()\n\t}\n\tk := &KubernetesExecutor{\n\t\tkl: kl,\n\t\tupdateChan: ch,\n\t\tstate: disconnectedState,\n\t\ttasks: make(map[string]*kuberTask),\n\t\tpods: make(map[string]*api.BoundPod),\n\t\tsourcename: ns,\n\t\tclient: cl,\n\t\tevents: events,\n\t\tdone: make(chan struct{}),\n\t\toutgoing: make(chan func() (mesos.Status, error), 1024),\n\t\tdockerClient: dc,\n\t}\n\tgo k.sendLoop()\n\treturn k\n}",
"func New() *Executor {\n\treturn &Executor{}\n}",
"func New(client *containerd.Client, root, cgroup string, networkProviders map[pb.NetMode]network.Provider, dnsConfig *oci.DNSConfig) executor.Executor {\n\t// clean up old hosts/resolv.conf file. ignore errors\n\tos.RemoveAll(filepath.Join(root, \"hosts\"))\n\tos.RemoveAll(filepath.Join(root, \"resolv.conf\"))\n\n\treturn &containerdExecutor{\n\t\tclient: client,\n\t\troot: root,\n\t\tnetworkProviders: networkProviders,\n\t\tcgroupParent: cgroup,\n\t\tdnsConfig: dnsConfig,\n\t\trunning: make(map[string]chan error),\n\t}\n}",
"func New() Executor {\n\treturn make(Executor)\n}",
"func New(ctx context.Context, rootDir string, cli *containerd.Client, ns string, exitHandler ExitHandler, shim string, shimOpts interface{}) (*Executor, error) {\n\te := &Executor{\n\t\trootDir: rootDir,\n\t\texitHandler: exitHandler,\n\t\tshim: shim,\n\t\tshimOpts: shimOpts,\n\t\tplugins: make(map[string]*c8dPlugin),\n\t}\n\n\tclient, err := libcontainerd.NewClient(ctx, cli, rootDir, ns, e)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"error creating containerd exec client\")\n\t}\n\te.client = client\n\treturn e, nil\n}",
"func newExecutor() (*executor, error) {\n\tex := new(executor)\n\n\t// Find the Terraform binary.\n\tbinPath, err := tfBinaryPath()\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"failed to get Terraform binary's path\")\n\t}\n\n\tex.binaryPath = binPath\n\treturn ex, nil\n}",
"func New(executor *mesos.ExecutorInfo, scheduleFunc PodScheduleFunc, client *client.Client, helper tools.EtcdHelper, sr service.Registry) *KubernetesScheduler {\n\treturn &KubernetesScheduler{\n\t\tnew(sync.RWMutex),\n\t\thelper,\n\t\texecutor,\n\t\tnil,\n\t\tnil,\n\t\tnil,\n\t\tfalse,\n\t\tmake(map[string]*mesos.Offer),\n\t\tmake(map[string]*Slave),\n\t\tmake(map[string]string),\n\t\tmake(map[string]*PodTask),\n\t\tmake(map[string]*PodTask),\n\t\tring.New(defaultFinishedTasksSize),\n\t\tmake(map[string]string),\n\t\tscheduleFunc,\n\t\tclient,\n\t\tcache.NewFIFO(),\n\t\tsr,\n\t}\n}",
"func New() *Kitops {\n\turl := os.Getenv(\"KITOPS_DEPLOYMENTS_URL\")\n\tif len(url) == 0 {\n\t\t// set default URL\n\t\turl = \"https://github.com/300481/kitops-test.git\"\n\t}\n\n\trepo, err := sourcerepo.New(url, \"/tmp/repo\")\n\n\tif err != nil {\n\t\tlog.Printf(\"unable to get repository: %s\\n%v\", url, err)\n\t\treturn nil\n\t}\n\n\tqp := &QueueProcessor{\n\t\tClusterConfigs: make(map[string]*ClusterConfig),\n\t\trepository: repo,\n\t}\n\n\tq := queue.New(qp)\n\n\treturn &Kitops{\n\t\trouter: mux.NewRouter(),\n\t\tqueue: q,\n\t\tqueueProcessor: qp,\n\t}\n}",
"func New(zones []string) *Kubernetes {\n\tk := new(Kubernetes)\n\tk.Zones = zones\n\tk.Namespaces = make(map[string]struct{})\n\tk.podMode = podModeDisabled\n\tk.ttl = defaultTTL\n\n\treturn k\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 NewRuntime(opts ...runtime.Option) runtime.Runtime {\n\t// get default options\n\toptions := runtime.Options{\n\t\t// Create labels with type \"micro\": \"service\"\n\t\tType: \"service\",\n\t}\n\n\t// apply requested options\n\tfor _, o := range opts {\n\t\to(&options)\n\t}\n\n\t// kubernetes client\n\tclient := client.NewClientInCluster()\n\n\treturn &kubernetes{\n\t\toptions: options,\n\t\tclosed: make(chan bool),\n\t\tqueue: make(chan *task, 128),\n\t\tclient: client,\n\t}\n}",
"func New() *KubeCross {\n\treturn &KubeCross{&defaultImpl{}}\n}",
"func (m *ExecutorServiceFactory) New(name string, c core.Config, ch chan core.ServiceCommand) (core.Service, error) {\n\t// check mongo db configuration\n\thosts, err := c.String(\"conductor\", \"mongo\")\n\tif err != nil || hosts == \"\" {\n\t\treturn nil, errors.New(\"Invalid mongo configuration\")\n\t}\n\t// try connect with mongo db\n\tif session, err := mgo.Dial(hosts); err != nil {\n\t\treturn nil, err\n\t} else {\n\t\tsession.Close()\n\t}\n\texecutorService = &ExecutorService{\n\t\tconfig: c,\n\t\twg: sync.WaitGroup{},\n\t\tchn: ch,\n\t\truleChan: make(chan *Rule),\n\t\tengines: make(map[string]*ruleEngine),\n\t\tmutex: sync.Mutex{},\n\t}\n\treturn executorService, nil\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 New(ctx context.Context, cliset kubernetes.Interface, allowUnschedulable bool) (*Client, error) {\n\tvar (\n\t\tnc *nodeCache\n\t\terr error\n\t)\n\n\t// Watch nodes only if we do not consider kubenurses on unschedulable nodes\n\tif !allowUnschedulable {\n\t\tnc, err = watchNodes(ctx, cliset)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"starting node watcher: %w\", err)\n\t\t}\n\t}\n\n\treturn &Client{\n\t\tk8s: cliset,\n\t\tnodeCache: nc,\n\t\tallowUnschedulable: allowUnschedulable,\n\t}, nil\n}",
"func NewExecutor(holder *pilosa.Holder, cluster *pilosa.Cluster) *Executor {\n\te := &Executor{Executor: pilosa.NewExecutor()}\n\te.Holder = holder\n\te.Cluster = cluster\n\te.Host = cluster.Nodes[0].Host\n\treturn e\n}",
"func New(agent string) (*Operator, error) {\n\tcli, err := client.New(agent)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &Operator{cli: cli}, nil\n}",
"func New(config Config, opsCenterURL string, provisioner Provisioner) (Infra, error) {\n\treturn &autoCluster{\n\t\topsCenterURL: opsCenterURL,\n\t\tprovisioner: provisioner,\n\t}, nil\n}",
"func New(config *rest.Config) (*Cluster, error) {\n\tclientSet, err := kubernetes.NewForConfig(config)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"kubernetes.NewForConfig: %w\", err)\n\t}\n\treturn &Cluster{clientSet}, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Registered is called when the executor is successfully registered with the slave.
|
func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver,
executorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) {
if k.isDone() {
return
}
log.Infof("Executor %v of framework %v registered with slave %v\n",
executorInfo, frameworkInfo, slaveInfo)
if !(&k.state).transition(disconnectedState, connectedState) {
log.Errorf("failed to register/transition to a connected state")
}
if executorInfo != nil && executorInfo.Data != nil {
k.staticPodsConfig = executorInfo.Data
}
if slaveInfo != nil {
_, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes))
if err != nil {
log.Errorf("cannot update node labels: %v", err)
}
}
k.initialRegistration.Do(k.onInitialRegistration)
}
|
[
"func (k *Executor) Registered(\n\tdriver bindings.ExecutorDriver,\n\texecutorInfo *mesos.ExecutorInfo,\n\tframeworkInfo *mesos.FrameworkInfo,\n\tslaveInfo *mesos.SlaveInfo,\n) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\n\tlog.Infof(\n\t\t\"Executor %v of framework %v registered with slave %v\\n\",\n\t\texecutorInfo, frameworkInfo, slaveInfo,\n\t)\n\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to register/transition to a connected state\")\n\t}\n\n\tif executorInfo != nil && executorInfo.Data != nil {\n\t\terr := k.initializeStaticPodsSource(slaveInfo.GetHostname(), executorInfo.Data)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"failed to initialize static pod configuration: %v\", err)\n\t\t}\n\t}\n\n\tannotations, err := annotationsFor(executorInfo)\n\tif err != nil {\n\t\tlog.Errorf(\n\t\t\t\"cannot get node annotations from executor info %v error %v\",\n\t\t\texecutorInfo, err,\n\t\t)\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := k.nodeAPI.createOrUpdate(\n\t\t\tslaveInfo.GetHostname(),\n\t\t\tnode.SlaveAttributesToLabels(slaveInfo.Attributes),\n\t\t\tannotations,\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\tif slaveInfo != nil && k.nodeInfos != nil {\n\t\tk.nodeInfos <- nodeInfo(slaveInfo, executorInfo) // leave it behind the upper lock to avoid panics\n\t}\n}",
"func (k *KubernetesExecutor) Registered(driver bindings.ExecutorDriver,\n\texecutorInfo *mesos.ExecutorInfo, frameworkInfo *mesos.FrameworkInfo, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Executor %v of framework %v registered with slave %v\\n\",\n\t\texecutorInfo, frameworkInfo, slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}",
"func (builder *ImageBuilder) Registered(driver executor.ExecutorDriver, execInfo *mesosproto.ExecutorInfo, fwinfo *mesosproto.FrameworkInfo, slaveInfo *mesosproto.SlaveInfo) {\n\tfmt.Println(\"Registered Executor on slave \", slaveInfo.GetHostname())\n}",
"func (e *Executor) Registered(executor.ExecutorDriver, *mesosproto.ExecutorInfo, *mesosproto.FrameworkInfo, *mesosproto.SlaveInfo) {\n\te.Called()\n}",
"func (master *Master) Register(args *RegisterArgs, reply *RegisterReply) error {\n\tvar (\n\t\tnewWorker *RemoteWorker\n\t)\n\tlog.Printf(\"Registering worker '%v' with hostname '%v'\", master.totalWorkers, args.WorkerHostname)\n\n\tmaster.workersMutex.Lock()\n\n\tnewWorker = &RemoteWorker{master.totalWorkers, args.WorkerHostname, WORKER_IDLE}\n\tmaster.workers[newWorker.id] = newWorker\n\tmaster.totalWorkers++\n\n\tmaster.workersMutex.Unlock()\n\n\tmaster.idleWorkerChan <- newWorker\n\n\t*reply = RegisterReply{newWorker.id, master.task.NumReduceJobs}\n\treturn nil\n}",
"func (k *KubernetesScheduler) Registered(driver mesos.SchedulerDriver,\n\tframeworkId *mesos.FrameworkID, masterInfo *mesos.MasterInfo) {\n\tk.frameworkId = frameworkId\n\tk.masterInfo = masterInfo\n\tk.registered = true\n\tlog.Infof(\"Scheduler registered with the master: %v with frameworkId: %v\\n\", masterInfo, frameworkId)\n}",
"func (mr *Master) Register(ctx context.Context, args *pb.RegisterRequest) (r *pb.RegisterResponse, err error) {\n\tmr.Lock()\n\tdefer mr.Unlock()\n\n\tlog.Printf(\"Register: worker %d\\n\", args.WorkerIndex)\n\tendpoint := mr.workersAddress[args.WorkerIndex]\n\tconn, err := grpc.Dial(endpoint, grpc.WithInsecure())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmr.workerConn[int(args.WorkerIndex)] = conn\n\n\tif _, ok := mr.isWorkerRegistered[args.WorkerIndex]; ok {\n\t\t//TODO: if the master terminate, how about worker's register?\n\t\tlog.Fatal(\"%d worker register more than one times\", args.WorkerIndex)\n\t} else {\n\t\tmr.isWorkerRegistered[args.WorkerIndex] = true\n\t}\n\tif len(mr.isWorkerRegistered) == mr.workerNum {\n\t\tmr.registerDone <- true\n\t}\n\tlog.Printf(\"len:%d\\n\", len(mr.isWorkerRegistered))\n\tlog.Printf(\"workernum:%d\\n\", mr.workerNum)\n\t// There is no need about scheduler\n\treturn &pb.RegisterResponse{Ok: true}, nil\n}",
"func (s *Server) Register(ctx context.Context, registration *proto.SlaveRegistration) (*proto.SlaveRegistrationResponse, error) {\n\tfor i := 0; i < int(registration.Threads); i++ {\n\t\tclient, err := createCellInteractionClient(registration.Address)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.cisClientPool.AddClient(client)\n\t\tmetrics.CISClientCount.Inc()\n\t}\n\treturn &proto.SlaveRegistrationResponse{}, nil\n}",
"func (s *serverRegistry) Register(*FContext, FAsyncCallback) error {\n\treturn nil\n}",
"func (s *ParallelMaster) Register(workerAddress string) {\n\tatomic.AddInt32(&s.totalWorkers, 1)\n\tgo func() {\n\t\tfmt.Printf(\"Worker at %s has registered.\\n\", workerAddress)\n\t\ts.freeWorkers <- workerAddress\n\t}()\n}",
"func (j *Job) multiregionRegister(args *structs.JobRegisterRequest, reply *structs.JobRegisterResponse, newVersion uint64) (bool, error) {\n\treturn false, nil\n}",
"func (builder *ImageBuilder) Reregistered(driver executor.ExecutorDriver, slaveInfo *mesosproto.SlaveInfo) {\n\tfmt.Println(\"Re-registered Executor on slave \", slaveInfo.GetHostname())\n}",
"func (s *Server) Register() {\n\tdefer base.CheckPanic()\n\tfor {\n\t\tif _, err := s.MasterClient.RegisterServer(context.Background(), &protocol.Void{}); err != nil {\n\t\t\tbase.Logger().Error(\"failed to register\", zap.Error(err))\n\t\t}\n\t\ttime.Sleep(time.Duration(s.Config.Master.ClusterMetaTimeout/2) * time.Second)\n\t}\n}",
"func (node *Proxy) Register() error {\n\tnode.session.Register()\n\tmetrics.NumNodes.WithLabelValues(fmt.Sprint(paramtable.GetNodeID()), typeutil.ProxyRole).Inc()\n\tlog.Info(\"Proxy Register Finished\")\n\tnode.session.LivenessCheck(node.ctx, func() {\n\t\tlog.Error(\"Proxy disconnected from etcd, process will exit\", zap.Int64(\"Server Id\", node.session.ServerID))\n\t\tif err := node.Stop(); err != nil {\n\t\t\tlog.Fatal(\"failed to stop server\", zap.Error(err))\n\t\t}\n\t\tmetrics.NumNodes.WithLabelValues(fmt.Sprint(paramtable.GetNodeID()), typeutil.ProxyRole).Dec()\n\t\tif node.session.TriggerKill {\n\t\t\tif p, err := os.FindProcess(os.Getpid()); err == nil {\n\t\t\t\tp.Signal(syscall.SIGINT)\n\t\t\t}\n\t\t}\n\t})\n\t// TODO Reset the logger\n\t//Params.initLogCfg()\n\treturn nil\n}",
"func (s *SequentialMaster) Register(workerAddress string) {\n\tpanic(\"Registration should not occur in sequential master!\")\n}",
"func (m *SamplePlugin) Register(kubeletEndpoint, resourceName string) error {\n\tconn, err := dial(kubeletEndpoint, 5*time.Second)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer conn.Close()\n\n\tclient := pluginapi.NewRegistrationClient(conn)\n\treqt := &pluginapi.RegisterRequest{\n\t\tVersion: pluginapi.Version,\n\t\tEndpoint: path.Base(m.socket),\n\t\tResourceName: resourceName,\n\t}\n\n\t_, err = client.Register(context.Background(), reqt)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (k *Executor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to reregister/transition to a connected state\")\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := k.nodeAPI.createOrUpdate(\n\t\t\tslaveInfo.GetHostname(),\n\t\t\tnode.SlaveAttributesToLabels(slaveInfo.Attributes),\n\t\t\tnil, // don't change annotations\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tif slaveInfo != nil && k.nodeInfos != nil {\n\t\t// make sure nodeInfos is not nil and send new NodeInfo\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tif k.isDone() {\n\t\t\treturn\n\t\t}\n\t\tk.nodeInfos <- nodeInfo(slaveInfo, nil)\n\t}\n}",
"func registeredCB(\n ptr unsafe.Pointer,\n frameworkMessage *C.ProtobufObj,\n masterMessage *C.ProtobufObj) {\n if (ptr != nil) {\n var driver *SchedulerDriver = (*SchedulerDriver)(ptr)\n\n if (driver.Scheduler.Registered == nil) {\n return\n }\n\n frameworkData := C.GoBytes(\n frameworkMessage.data,\n C.int(frameworkMessage.size))\n\n var frameworkId FrameworkID\n err := proto.Unmarshal(frameworkData, &frameworkId); if err != nil {\n return\n }\n\n masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))\n var masterInfo MasterInfo\n err = proto.Unmarshal(masterData, &masterInfo); if err != nil {\n return\n }\n\n driver.Scheduler.Registered(driver, frameworkId, masterInfo)\n }\n}",
"func Register(appName string, localip string, port string, securePort string) {\n\tappName = strings.ToUpper(appName)\n\tVport = port\n\tcfg := newConfig(appName,localip ,port,securePort)\n\n\t// define Register request\n\tregisterAction := RequestAction{\n\t\tUrl: discoveryServerUrl + eurekaPath + appName,\n\t\tMethod: \"POST\",\n\t\tContentType: \"application/json;charset=UTF-8\",\n\t\tBody: cfg,\n\t}\n\tvar result bool\n\t// loop send heart beat every 5s\n\tfor {\n\t\tresult = isDoHttpRequest(registerAction)\n\t\tif result {\n\t\t\tlog.Println(\"Registration OK\")\n\t\t\thandleSigtermProcess(appName)\n\t\t\tgo startHeartbeat(appName, localip)\n\t\t\tbreak\n\t\t} else {\n\t\t\tlog.Println(\"Registration attempt of \" + appName + \" failed...\")\n\t\t\ttime.Sleep(time.Second * 5)\n\t\t}\n\t}\n\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Reregistered is called when the executor is successfully reregistered with the slave. This can happen when the slave fails over.
|
func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {
if k.isDone() {
return
}
log.Infof("Reregistered with slave %v\n", slaveInfo)
if !(&k.state).transition(disconnectedState, connectedState) {
log.Errorf("failed to reregister/transition to a connected state")
}
if slaveInfo != nil {
_, err := node.CreateOrUpdate(k.client, slaveInfo.GetHostname(), node.SlaveAttributesToLabels(slaveInfo.Attributes))
if err != nil {
log.Errorf("cannot update node labels: %v", err)
}
}
k.initialRegistration.Do(k.onInitialRegistration)
}
|
[
"func (k *KubernetesExecutor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !k.swapState(disconnectedState, connectedState) {\n\t\t//programming error?\n\t\tpanic(\"already connected?!\")\n\t}\n}",
"func (k *Executor) Reregistered(driver bindings.ExecutorDriver, slaveInfo *mesos.SlaveInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Reregistered with slave %v\\n\", slaveInfo)\n\tif !(&k.state).transition(disconnectedState, connectedState) {\n\t\tlog.Errorf(\"failed to reregister/transition to a connected state\")\n\t}\n\n\tif slaveInfo != nil {\n\t\t_, err := k.nodeAPI.createOrUpdate(\n\t\t\tslaveInfo.GetHostname(),\n\t\t\tnode.SlaveAttributesToLabels(slaveInfo.Attributes),\n\t\t\tnil, // don't change annotations\n\t\t)\n\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"cannot update node labels: %v\", err)\n\t\t}\n\t}\n\n\tif slaveInfo != nil && k.nodeInfos != nil {\n\t\t// make sure nodeInfos is not nil and send new NodeInfo\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\t\tif k.isDone() {\n\t\t\treturn\n\t\t}\n\t\tk.nodeInfos <- nodeInfo(slaveInfo, nil)\n\t}\n}",
"func (builder *ImageBuilder) Reregistered(driver executor.ExecutorDriver, slaveInfo *mesosproto.SlaveInfo) {\n\tfmt.Println(\"Re-registered Executor on slave \", slaveInfo.GetHostname())\n}",
"func (e *Executor) Reregistered(executor.ExecutorDriver, *mesosproto.SlaveInfo) {\n\te.Called()\n}",
"func (s *eremeticScheduler) Reregistered(driver sched.SchedulerDriver, masterInfo *mesos.MasterInfo) {\n\tlog.Debugf(\"Framework re-registered with master %s\", masterInfo)\n\tif !s.initialised {\n\t\tdriver.ReconcileTasks([]*mesos.TaskStatus{})\n\t\ts.initialised = true\n\t} else {\n\t\ts.Reconcile(driver)\n\t}\n}",
"func (k *KubernetesScheduler) Reregistered(driver mesos.SchedulerDriver, masterInfo *mesos.MasterInfo) {\n\tlog.Infof(\"Scheduler reregistered with the master: %v\\n\", masterInfo)\n\tk.registered = true\n}",
"func (k *KubernetesScheduler) ExecutorLost(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, status int) {\n\tlog.Infof(\"Executor %v of slave %v is lost, status: %v\\n\", executorId, slaveId, status)\n\t// TODO(yifan): Restart any unfinished tasks of the executor.\n}",
"func (e *LifecycleEvent) SetDeregisterCompleted(val bool) { e.deregisterCompleted = val }",
"func (r *Registrator) Deregister() error {\n\tr.Jobs = nil\n\treturn nil\n}",
"func (r *RegisterMonitor) deregister() {\n\t// Basic retry loop, no backoff for now. But we want to retry a few\n\t// times just in case there are basic ephemeral issues.\n\tfor i := 0; i < 3; i++ {\n\t\terr := r.Client.Agent().ServiceDeregister(r.serviceID())\n\t\tif err == nil {\n\t\t\treturn\n\t\t}\n\n\t\tr.Logger.Printf(\"[WARN] proxy: service deregister failed: %s\", err)\n\t\ttime.Sleep(500 * time.Millisecond)\n\t}\n}",
"func (agent *ecsAgent) reregisterContainerInstance(client api.ECSClient, capabilities []*ecs.Attribute,\n\ttags []*ecs.Tag, registrationToken string, platformDevices []*ecs.PlatformDevice, outpostARN string) error {\n\t_, availabilityZone, err := client.RegisterContainerInstance(agent.containerInstanceARN, capabilities, tags,\n\t\tregistrationToken, platformDevices, outpostARN)\n\n\t//set az to agent\n\tagent.availabilityZone = availabilityZone\n\n\tif err == nil {\n\t\treturn nil\n\t}\n\tlogger.Error(\"Error re-registering container instance\", logger.Fields{\n\t\tfield.Error: err,\n\t})\n\tif apierrors.IsInstanceTypeChangedError(err) {\n\t\tseelog.Criticalf(instanceTypeMismatchErrorFormat, err)\n\t\treturn err\n\t}\n\tif _, ok := err.(apierrors.AttributeError); ok {\n\t\tattributeErrorMsg := \"\"\n\t\tif len(agent.cfg.InstanceAttributes) > 0 {\n\t\t\tattributeErrorMsg = customAttributeErrorMessage\n\t\t}\n\t\tlogger.Critical(\"Instance re-registration attempt with invalid attribute(s)\", logger.Fields{\n\t\t\tfield.Error: attributeErrorMsg,\n\t\t})\n\t\treturn err\n\t}\n\treturn transientError{err}\n}",
"func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !k.swapState(connectedState, disconnectedState) {\n\t\t//programming error?\n\t\tpanic(\"already disconnected?!\")\n\t}\n}",
"func (e *EurekaConnection) ReregisterInstance(ins *Instance) error {\n\tslug := fmt.Sprintf(\"%s/%s\", EurekaURLSlugs[\"Apps\"], ins.App)\n\treqURL := e.generateURL(slug)\n\n\tvar out []byte\n\tvar err error\n\tif e.UseJson {\n\t\tins.PortJ.Number = strconv.Itoa(ins.Port)\n\t\tins.SecurePortJ.Number = strconv.Itoa(ins.SecurePort)\n\t\tout, err = e.marshal(&RegisterInstanceJson{ins})\n\t} else {\n\t\tout, err = e.marshal(ins)\n\t}\n\n\tbody, rcode, err := postBody(reqURL, out, e.UseJson)\n\tif err != nil {\n\t\tlog.Errorf(\"Could not complete registration, error: %s\", err.Error())\n\t\treturn err\n\t}\n\tif rcode != 204 {\n\t\tlog.Warningf(\"HTTP returned %d registering Instance=%s App=%s Body=\\\"%s\\\"\", rcode,\n\t\t\tins.Id(), ins.App, string(body))\n\t\treturn &unsuccessfulHTTPResponse{rcode, \"possible failure registering instance\"}\n\t}\n\n\t// read back our registration to pick up eureka-supplied values\n\te.readInstanceInto(ins)\n\n\treturn nil\n}",
"func (k *KubernetesScheduler) SlaveLost(driver mesos.SchedulerDriver, slaveId *mesos.SlaveID) {\n\tlog.Infof(\"Slave %v is lost\\n\", slaveId)\n\t// TODO(yifan): Restart any unfinished tasks on that slave.\n}",
"func (driver *MesosExecutorDriver) slaveExited() {\n\tif driver.status == mesosproto.Status_DRIVER_ABORTED {\n\t\tlog.Infof(\"Ignoring slave exited event because the driver is aborted!\\n\")\n\t\treturn\n\t}\n\n\tif driver.checkpoint && driver.connected {\n\t\tdriver.connected = false\n\n\t\tlog.Infof(\"Slave exited, but framework has checkpointing enabled. Waiting %v to reconnect with slave %v\",\n\t\t\tdriver.recoveryTimeout, driver.slaveID)\n\t\ttime.AfterFunc(driver.recoveryTimeout, func() { driver.recoveryTimeouts(driver.connection) })\n\t\treturn\n\t}\n\n\tlog.Infof(\"Slave exited ... shutting down\\n\")\n\tdriver.connected = false\n\t// Clean up\n\tdriver.Executor.Shutdown(driver)\n\tdriver.status = mesosproto.Status_DRIVER_ABORTED\n\tdriver.Stop()\n}",
"func (es *EventStream) Deregister(handle int64) error {\n\tes.mux.Lock()\n\tcount, err := es.deregister(handle)\n\tes.mux.Unlock()\n\t// Really wait should be for my specific one, but ...\n\t// Multi-threaded apps will have issues.\n\tfor i := 0; i < count; i++ {\n\t\t<-es.rchan\n\t}\n\treturn err\n}",
"func TestGetAfterReregisterWithMissedBucketUpdate(t *testing.T) {\n\ttutils.CheckSkip(t, tutils.SkipTestArgs{Long: true})\n\n\tvar (\n\t\tm = ioContext{\n\t\t\tt: t,\n\t\t\tnum: 10000,\n\t\t\tfileSize: 1024,\n\t\t\tnumGetsEachFile: 5,\n\t\t}\n\t)\n\n\t// Initialize ioContext\n\tm.saveClusterState()\n\tif m.originalTargetCount < 2 {\n\t\tt.Fatalf(\"Must have 2 or more targets in the cluster, have only %d\", m.originalTargetCount)\n\t}\n\n\ttargets := tutils.ExtractTargetNodes(m.smap)\n\n\t// Unregister target 0\n\terr := tutils.UnregisterNode(m.proxyURL, targets[0].ID())\n\ttassert.CheckFatal(t, err)\n\tn := tutils.GetClusterMap(t, m.proxyURL).CountTargets()\n\tif n != m.originalTargetCount-1 {\n\t\tt.Fatalf(\"%d targets expected after unregister, actually %d targets\", m.originalTargetCount-1, n)\n\t}\n\n\t// Create ais bucket\n\ttutils.CreateFreshBucket(t, m.proxyURL, m.bck)\n\tdefer tutils.DestroyBucket(t, m.proxyURL, m.bck)\n\n\tm.puts()\n\n\t// Reregister target 0\n\tm.reregisterTarget(targets[0])\n\n\t// Wait for rebalance and do gets\n\tbaseParams := tutils.BaseAPIParams(m.proxyURL)\n\ttutils.WaitForRebalanceToComplete(t, baseParams)\n\n\tm.gets()\n\n\tm.ensureNoErrors()\n\tm.assertClusterState()\n}",
"func (c *crdWatcher) restoreFinished() {\n\tc.mutex.Lock()\n\tdefer c.mutex.Unlock()\n\tif c.finishedRestore {\n\t\treturn\n\t}\n\n\t// creating a new controller will execute DoFunc immediately\n\tc.controller.UpdateController(clusterPoolStatusControllerName,\n\t\tcontroller.ControllerParams{\n\t\t\tGroup: clusterPoolStatusControllerGroup,\n\t\t\tDoFunc: c.updateCiliumNodeStatus,\n\t\t})\n\tc.finishedRestore = true\n}",
"func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !(&k.state).transition(connectedState, disconnectedState) {\n\t\tlog.Errorf(\"failed to disconnect/transition to a disconnected state\")\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
InitializeStaticPodsSource blocks until initial regstration is complete and then creates a static pod source using the given factory func.
|
func (k *KubernetesExecutor) InitializeStaticPodsSource(sourceFactory func()) {
<-k.initialRegComplete
if k.staticPodsConfig == nil {
return
}
log.V(2).Infof("extracting static pods config to %s", k.staticPodsConfigPath)
err := archive.UnzipDir(k.staticPodsConfig, k.staticPodsConfigPath)
if err != nil {
log.Errorf("Failed to extract static pod config: %v", err)
return
}
log.V(2).Infof("initializing static pods source factory, configured at path %q", k.staticPodsConfigPath)
sourceFactory()
}
|
[
"func (k *Executor) initializeStaticPodsSource(hostname string, data []byte) error {\n\tlog.V(2).Infof(\"extracting static pods config to %s\", k.staticPodsConfigPath)\n\t// annotate the pod with BindingHostKey so that the scheduler will ignore the pod\n\t// once it appears in the pod registry. the stock kubelet sets the pod host in order\n\t// to accomplish the same; we do this because the k8sm scheduler works differently.\n\tannotator := podutil.Annotator(map[string]string{\n\t\tmeta.BindingHostKey: hostname,\n\t})\n\treturn podutil.WriteToDir(annotator.Do(podutil.Gunzip(data)), k.staticPodsConfigPath)\n}",
"func NewStaticSource(users ...string) *StaticSource {\n\tfor i, u := range users {\n\t\tusers[i] = strings.ToLower(u)\n\t}\n\tsort.Strings(users)\n\n\tss := &StaticSource{\n\t\tnextUser: ring.New(len(users)),\n\t\tusernames: make(map[string]bool, len(users)),\n\t}\n\tfor _, u := range users {\n\t\tss.usernames[u] = true\n\t\tss.nextUser.Value = u\n\t\tss.nextUser = ss.nextUser.Next()\n\t}\n\treturn ss\n}",
"func NewStaticDiscovery(cfg config.DiscoveryConfig) interface{} {\n\n\td := Discovery{\n\t\topts: DiscoveryOpts{0},\n\t\tcfg: cfg,\n\t\tfetch: staticFetch,\n\t}\n\n\treturn &d\n}",
"func PrebuiltStaticLibraryFactory() android.Module {\n\tmodule, _ := NewPrebuiltStaticLibrary(android.HostAndDeviceSupported)\n\treturn module.Init()\n}",
"func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\tvar projectID string\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tglobal.collectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tprojectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\n\tglobal.firestoreClient, err = firestore.NewClient(ctx, projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}",
"func NewStaticPluginFactory(\n\tctx context.Context,\n\tft controller.Factory,\n\tbinaryID string,\n\tbus bus.Bus,\n) *StaticPluginFactory {\n\tnctx, nctxCancel := context.WithCancel(ctx)\n\treturn &StaticPluginFactory{\n\t\tFactory: ft,\n\t\tbinaryID: binaryID,\n\t\tbus: bus,\n\t\tctx: nctx,\n\t\tctxCancel: nctxCancel,\n\t}\n}",
"func Init(myIp string, namespace string, listOptions metav1.ListOptions, f NotifyFunc, client *kubernetes.Clientset, debugMode bool) ([]string, error) {\n\n\tlibConfig.debugMode = debugMode\n\n\t// Fetch initial pods from API\n\tinitialPods, err := getInitialPods(client, namespace, listOptions, myIp)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"PodWatch: could not get initial pod list: %v\", err)\n\t}\n\n\tif len(initialPods) <= 0 {\n\t\treturn nil, errors.New(\"PodWatch: no pods detected, not even self\")\n\t}\n\tpodIps := initialPods.Keys()\n\n\t// Start monitoring for pod transitions, to keep pool up to date\n\tgo monitorPodState(client, namespace, listOptions, myIp, initialPods, f)\n\n\treturn podIps, nil\n}",
"func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\tvar storageClient *storage.Client\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tglobal.assetsCollectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets\n\tglobal.ownerLabelKeyName = instanceDeployment.Core.SolutionSettings.Monitoring.LabelKeyNames.Owner\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tglobal.violationResolverLabelKeyName = instanceDeployment.Core.SolutionSettings.Monitoring.LabelKeyNames.ViolationResolver\n\tprojectID := instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\n\tstorageClient, err = storage.NewClient(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"storage.NewClient(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\t// bucketHandle must be evaluated after storateClient init\n\tglobal.bucketHandle = storageClient.Bucket(instanceDeployment.Core.SolutionSettings.Hosting.GCS.Buckets.AssetsJSONFile.Name)\n\n\tglobal.cloudresourcemanagerService, err = cloudresourcemanager.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanager.NewService(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.cloudresourcemanagerServiceV2, err = cloudresourcemanagerv2.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanagerv2.NewService(ctx) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.firestoreClient, err = firestore.NewClient(ctx, projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient(ctx, projectID) %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\treturn nil\n}",
"func newStaticClients(cfg micro.CliConfig, protoFunc socket.ProtoFunc) *StaticClients {\n\treturn &StaticClients{\n\t\tclients: make(map[string]*micro.Client),\n\t\tcfg: cfg,\n\t\tprotoFunc: protoFunc,\n\t}\n}",
"func createStaticPVC(ctx context.Context, f *framework.Framework,\n\tclient clientset.Interface, namespace string, defaultDatastore *object.Datastore,\n\tpandoraSyncWaitTime int) (string, *v1.PersistentVolumeClaim, *v1.PersistentVolume, *storagev1.StorageClass) {\n\tcurtime := time.Now().Unix()\n\n\tsc, err := createStorageClass(client, nil, nil, \"\", \"\", true, \"\")\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"Storage Class Name :%s\", sc.Name)\n\n\tginkgo.By(\"Creating FCD Disk\")\n\tcurtimeinstring := strconv.FormatInt(curtime, 10)\n\tfcdID, err := e2eVSphere.createFCD(ctx, \"BasicStaticFCD\"+curtimeinstring, diskSizeInMb, defaultDatastore.Reference())\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tframework.Logf(\"FCD ID :\", fcdID)\n\n\tginkgo.By(fmt.Sprintf(\"Sleeping for %v seconds to allow newly created FCD:%s to sync with pandora\",\n\t\tpandoraSyncWaitTime, fcdID))\n\ttime.Sleep(time.Duration(pandoraSyncWaitTime) * time.Second)\n\n\t// Creating label for PV.\n\t// PVC will use this label as Selector to find PV\n\tstaticPVLabels := make(map[string]string)\n\tstaticPVLabels[\"fcd-id\"] = fcdID\n\n\tginkgo.By(\"Creating PV\")\n\tpv := getPersistentVolumeSpecWithStorageclass(fcdID, v1.PersistentVolumeReclaimDelete, sc.Name, nil, diskSize)\n\tpv, err = client.CoreV1().PersistentVolumes().Create(ctx, pv, metav1.CreateOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tpvName := pv.GetName()\n\n\tginkgo.By(\"Creating PVC\")\n\tpvc := getPVCSpecWithPVandStorageClass(\"static-pvc\", namespace, nil, pvName, sc.Name, diskSize)\n\tpvc, err = client.CoreV1().PersistentVolumeClaims(namespace).Create(ctx, pvc, metav1.CreateOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tginkgo.By(\"Waiting for claim to be in bound phase\")\n\terr = fpv.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client,\n\t\tnamespace, pvc.Name, framework.Poll, framework.ClaimProvisionTimeout)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tginkgo.By(\"Verifying CNS entry is present in cache\")\n\t_, err = e2eVSphere.queryCNSVolumeWithResult(pv.Spec.CSI.VolumeHandle)\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\n\tpvc, err = client.CoreV1().PersistentVolumeClaims(namespace).Get(ctx, pvc.Name, metav1.GetOptions{})\n\tgomega.Expect(err).NotTo(gomega.HaveOccurred())\n\tpv = getPvFromClaim(client, namespace, pvc.Name)\n\tverifyBidirectionalReferenceOfPVandPVC(ctx, client, pvc, pv, fcdID)\n\n\tvolHandle := pv.Spec.CSI.VolumeHandle\n\n\t// Wait for PV and PVC to Bind\n\tframework.ExpectNoError(fpv.WaitOnPVandPVC(client, framework.NewTimeoutContextWithDefaults(), namespace, pv, pvc))\n\n\treturn volHandle, pvc, pv, sc\n}",
"func NewStaticProvider(groups []*config.TargetGroup) *StaticProvider {\n\tfor i, tg := range groups {\n\t\ttg.Source = fmt.Sprintf(\"%d\", i)\n\t}\n\treturn &StaticProvider{groups}\n}",
"func (frame *Framework) NewStaticFS(pattern string, fs FileSystem) *MuxAPI {\r\n\treturn frame.NewNamedStaticFS(\"\", pattern, fs)\r\n}",
"func InitServiceFactory(repo *repositories.Repository) *Service {\n\n\treturn &Service{\n\t\tAccountService: newAccountService(repo),\n\t\tUserService: newUserService(repo),\n\t\tTransactionService: newTransactionService(repo),\n\t}\n}",
"func Initialize(ctx context.Context, global *Global) (err error) {\n\tlog.SetFlags(0)\n\tglobal.ctx = ctx\n\n\tvar instanceDeployment InstanceDeployment\n\tvar clientOption option.ClientOption\n\tvar ok bool\n\n\tinitID := fmt.Sprintf(\"%v\", uuid.New())\n\terr = ffo.ReadUnmarshalYAML(solution.PathToFunctionCode+solution.SettingsFileName, &instanceDeployment)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"ReadUnmarshalYAML %s %v\", solution.SettingsFileName, err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tglobal.environment = instanceDeployment.Core.EnvironmentName\n\tglobal.instanceName = instanceDeployment.Core.InstanceName\n\tglobal.microserviceName = instanceDeployment.Core.ServiceName\n\n\tlog.Println(glo.Entry{\n\t\tMicroserviceName: global.microserviceName,\n\t\tInstanceName: global.instanceName,\n\t\tEnvironment: global.environment,\n\t\tSeverity: \"NOTICE\",\n\t\tMessage: \"coldstart\",\n\t\tInitID: initID,\n\t})\n\n\tgciAdminUserToImpersonate := instanceDeployment.Settings.Instance.GCI.SuperAdminEmail\n\tglobal.collectionID = instanceDeployment.Core.SolutionSettings.Hosting.FireStore.CollectionIDs.Assets\n\tglobal.GCIGroupMembersTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupMembers\n\tglobal.GCIGroupSettingsTopicName = instanceDeployment.Core.SolutionSettings.Hosting.Pubsub.TopicNames.GCIGroupSettings\n\tglobal.projectID = instanceDeployment.Core.SolutionSettings.Hosting.ProjectID\n\tglobal.retriesNumber = instanceDeployment.Settings.Service.RetriesNumber\n\tglobal.retryTimeOutSeconds = instanceDeployment.Settings.Service.GCF.RetryTimeOutSeconds\n\tkeyJSONFilePath := solution.PathToFunctionCode + instanceDeployment.Settings.Service.KeyJSONFileName\n\tserviceAccountEmail := fmt.Sprintf(\"%s@%s.iam.gserviceaccount.com\",\n\t\tinstanceDeployment.Core.ServiceName,\n\t\tinstanceDeployment.Core.SolutionSettings.Hosting.ProjectID)\n\n\tglobal.firestoreClient, err = firestore.NewClient(global.ctx, global.projectID)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"firestore.NewClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tserviceAccountKeyNames, err := gfs.ListKeyNames(ctx, global.firestoreClient, instanceDeployment.Core.ServiceName)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"gfs.ListKeyNames %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\n\tif clientOption, ok = aut.GetClientOptionAndCleanKeys(ctx,\n\t\tserviceAccountEmail,\n\t\tkeyJSONFilePath,\n\t\tinstanceDeployment.Core.SolutionSettings.Hosting.ProjectID,\n\t\tgciAdminUserToImpersonate,\n\t\t[]string{\"https://www.googleapis.com/auth/apps.groups.settings\", \"https://www.googleapis.com/auth/admin.directory.group.readonly\"},\n\t\tserviceAccountKeyNames,\n\t\tinitID,\n\t\tglobal.microserviceName,\n\t\tglobal.instanceName,\n\t\tglobal.environment); !ok {\n\t\treturn fmt.Errorf(\"aut.GetClientOptionAndCleanKeys\")\n\t}\n\tglobal.dirAdminService, err = admin.NewService(ctx, clientOption)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"admin.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t\treturn err\n\t}\n\tglobal.groupsSettingsService, err = groupssettings.NewService(ctx, clientOption)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"groupssettings.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\tglobal.pubsubPublisherClient, err = pubsub.NewPublisherClient(global.ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"global.pubsubPublisherClient %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\tglobal.cloudresourcemanagerService, err = cloudresourcemanager.NewService(ctx)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"cloudresourcemanager.NewService %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\terr = gps.GetTopicList(global.ctx, global.pubsubPublisherClient, global.projectID, &global.topicList)\n\tif err != nil {\n\t\tlog.Println(glo.Entry{\n\t\t\tMicroserviceName: global.microserviceName,\n\t\t\tInstanceName: global.instanceName,\n\t\t\tEnvironment: global.environment,\n\t\t\tSeverity: \"CRITICAL\",\n\t\t\tMessage: \"init_failed\",\n\t\t\tDescription: fmt.Sprintf(\"gps.GetTopicList %v\", err),\n\t\t\tInitID: initID,\n\t\t})\n\t}\n\treturn nil\n}",
"func (p *Provisioner) createInitPod(pOpts *HelperPodOptions) error {\n\t//err := pOpts.validate()\n\tif err := pOpts.validate(); err != nil {\n\t\treturn err\n\t}\n\n\t// Initialize HostPath builder and validate that\n\t// volume directory is not directly under root.\n\t// Extract the base path and the volume unique path.\n\tparentDir, volumeDir, vErr := hostpath.NewBuilder().WithPath(pOpts.path).\n\t\tWithCheckf(hostpath.IsNonRoot(), \"volume directory {%v} should not be under root directory\", pOpts.path).\n\t\tExtractSubPath()\n\tif vErr != nil {\n\t\treturn vErr\n\t}\n\n\tinitPod, _ := pod.NewBuilder().\n\t\tWithName(\"init-\" + pOpts.name).\n\t\tWithRestartPolicy(corev1.RestartPolicyNever).\n\t\tWithNodeName(pOpts.nodeName).\n\t\tWithContainerBuilder(\n\t\t\tcontainer.NewBuilder().\n\t\t\t\tWithName(\"local-path-init\").\n\t\t\t\tWithImage(p.helperImage).\n\t\t\t\tWithCommandNew(append(pOpts.cmdsForPath, filepath.Join(\"/data/\", volumeDir))).\n\t\t\t\tWithVolumeMountsNew([]corev1.VolumeMount{\n\t\t\t\t\t{\n\t\t\t\t\t\tName: \"data\",\n\t\t\t\t\t\tReadOnly: false,\n\t\t\t\t\t\tMountPath: \"/data/\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t).\n\t\tWithVolumeBuilder(\n\t\t\tvolume.NewBuilder().\n\t\t\t\tWithName(\"data\").\n\t\t\t\tWithHostDirectory(parentDir),\n\t\t).\n\t\tBuild()\n\n\t//Launch the init pod.\n\tiPod, err := p.kubeClient.CoreV1().Pods(p.namespace).Create(initPod)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer func() {\n\t\te := p.kubeClient.CoreV1().Pods(p.namespace).Delete(iPod.Name, &metav1.DeleteOptions{})\n\t\tif e != nil {\n\t\t\tglog.Errorf(\"unable to delete the helper pod: %v\", e)\n\t\t}\n\t}()\n\n\t//Wait for the cleanup pod to complete it job and exit\n\tcompleted := false\n\tfor i := 0; i < CmdTimeoutCounts; i++ {\n\t\tcheckPod, err := p.kubeClient.CoreV1().Pods(p.namespace).Get(iPod.Name, metav1.GetOptions{})\n\t\tif err != nil {\n\t\t\treturn err\n\t\t} else if checkPod.Status.Phase == corev1.PodSucceeded {\n\t\t\tcompleted = true\n\t\t\tbreak\n\t\t}\n\t\ttime.Sleep(1 * time.Second)\n\t}\n\tif !completed {\n\t\treturn errors.Errorf(\"create process timeout after %v seconds\", CmdTimeoutCounts)\n\t}\n\n\treturn nil\n}",
"func (r *runner) startInitialPods() error {\n\tfor d, ip := range r.config.InitialPods {\n\t\tname, podManifest, err := ip.Process(r.imageManager)\n\t\tif name == \"\" {\n\t\t\tname = fmt.Sprintf(\"pod%d\", d+1)\n\t\t}\n\t\tif err != nil {\n\t\t\tr.log.Errorf(\"Failed to configure pod %q: %v\", name, err)\n\t\t\tcontinue\n\t\t}\n\n\t\tpod, err := r.podManager.Create(name, podManifest, nil)\n\t\tif err != nil {\n\t\t\tr.log.Errorf(\"Failed to launch pod %q: %v\", name, err)\n\t\t\tcontinue\n\t\t}\n\t\tr.log.Infof(\"Launched pod %q.\", pod.Name())\n\t}\n\treturn nil\n}",
"func initSource(ctx context.Context, rootSecret string, prod bool) (Source, error) {\n\tswitch {\n\tcase strings.HasPrefix(rootSecret, \"devsecret://\"):\n\t\tvalue, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(rootSecret, \"devsecret://\"))\n\t\tif err != nil {\n\t\t\treturn nil, errors.Annotate(err, \"bad devsecret://, not base64 encoding\").Err()\n\t\t}\n\t\treturn &StaticSource{Secret: &Secret{Current: value}}, nil\n\n\tcase strings.HasPrefix(rootSecret, \"sm://\"):\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 get the token source\").Err()\n\t\t}\n\t\treturn NewSecretManagerSource(ctx, rootSecret, ts)\n\n\tcase strings.Contains(rootSecret, \"://\"):\n\t\treturn nil, errors.Reason(\"not supported secret reference %q\", rootSecret).Err()\n\n\tdefault:\n\t\treturn &FileSource{Path: rootSecret}, nil\n\t}\n}",
"func PrebuiltStubsSourcesFactory() android.Module {\n\tmodule := &PrebuiltStubsSources{}\n\n\tmodule.AddProperties(&module.properties)\n\n\tandroid.InitPrebuiltModule(module, &module.properties.Srcs)\n\tandroid.InitSdkAwareModule(module)\n\tInitDroiddocModule(module, android.HostAndDeviceSupported)\n\treturn module\n}",
"func PrebuiltApisFactory() android.Module {\n\tmodule := &prebuiltApis{}\n\tmodule.AddProperties(&module.properties)\n\tandroid.InitAndroidModule(module)\n\tandroid.AddLoadHook(module, createPrebuiltApiModules)\n\treturn module\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Disconnected is called when the executor is disconnected from the slave.
|
func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {
if k.isDone() {
return
}
log.Infof("Slave is disconnected\n")
if !(&k.state).transition(connectedState, disconnectedState) {
log.Errorf("failed to disconnect/transition to a disconnected state")
}
}
|
[
"func (k *Executor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !(&k.state).transition(connectedState, disconnectedState) {\n\t\tlog.Errorf(\"failed to disconnect/transition to a disconnected state\")\n\t}\n}",
"func (k *KubernetesExecutor) Disconnected(driver bindings.ExecutorDriver) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Slave is disconnected\\n\")\n\tif !k.swapState(connectedState, disconnectedState) {\n\t\t//programming error?\n\t\tpanic(\"already disconnected?!\")\n\t}\n}",
"func (ut *Client) OnDisconnected(context.Context, rpc.DisconnectStatus) {\n}",
"func (c *Client) OnDisconnected(_ context.Context, status rpc.DisconnectStatus) {\n}",
"func (a *WSMasterElection) OnDisconnected(c WSSpeaker) {\n\ta.Lock()\n\tif a.master != nil && a.master.GetHost() == c.GetHost() {\n\t\ta.selectMaster()\n\t\tdefer func() {\n\t\t\ta.notifyNewMaster(a.master)\n\t\t}()\n\t}\n\ta.Unlock()\n}",
"func (s *eremeticScheduler) Disconnected(sched.SchedulerDriver) {\n\tlog.Debugf(\"Framework disconnected with master\")\n}",
"func (er *EventRelay) Disconnected(err error) {\n\tlogger.Warnf(\"Disconnected: %s. Attempting to reconnect...\\n\", err)\n\n\ter.ehmutex.Lock()\n\tdefer er.ehmutex.Unlock()\n\n\ter.eventHub = nil\n\n\tgo er.connectEventHub()\n}",
"func printDisconnected() {\n\tfmt.Println(\"Disconnected\")\n}",
"func (eventHub *EventHub) Disconnected(err error) {\n\tif !eventHub.connected {\n\t\treturn\n\t}\n\teventHub.client.Stop()\n\teventHub.connected = false\n\n}",
"func (k *KubernetesScheduler) Disconnected(driver mesos.SchedulerDriver) {\n\tlog.Infof(\"Master disconnected!\\n\")\n\tk.registered = false\n\n\tk.Lock()\n\tdefer k.Unlock()\n\n\t// discard all cached offers to avoid unnecessary TASK_LOST updates\n\tfor offerId := range k.offers {\n\t\tk.deleteOffer(offerId)\n\t}\n\n\t// TODO(jdef): it's possible that a task is pending, in between Schedule() and\n\t// Bind(), such that it's offer is now invalid. We should check for that and\n\t// clearing the offer from the task (along with a related check in Bind())\n}",
"func (dc *Dynamic) disconnected() {\n\tif dc.cancel != nil {\n\t\tdc.cancel()\n\t}\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdc.cancel = cancel\n\tdc.c = NewDisconnected(ctx)\n\tdc.stat = machine.Status{}\n}",
"func (p *Probe) OnDisconnected() {\n\tlogging.GetLogger().Warning(\"disconnected from the OVSDB API\")\n\tclose(p.eventChan)\n}",
"func (m *peerManager) Disconnected(peerID NodeID) error {\n\tm.mtx.Lock()\n\tdefer m.mtx.Unlock()\n\tdelete(m.connected, peerID)\n\tm.broadcast(PeerUpdate{\n\t\tPeerID: peerID,\n\t\tStatus: PeerStatusDown,\n\t})\n\treturn nil\n}",
"func (n *Node) PeerDisconnected(net net.Network, conn net.Conn) {\n\tlogger.Debug(\"cancelled\", log.String(\"peer-id\", conn.RemotePeer().Pretty()))\n}",
"func (a *AbstractNetworkConnectionHandler) OnDisconnect() {\n}",
"func printDisconnected() {\n\tfmt.Println(\"Disconnected from the server.\")\n return\n}",
"func (vm *VM) Disconnected(id ids.ShortID) error {\n\treturn nil\n}",
"func (notifee *Notifee) Disconnected(net network.Network, conn network.Conn) {\n\n\tnotifee.logger.Info().Msgf(\n\t\t\"Disconnected from peer %s\",\n\t\tconn.RemotePeer().Pretty(),\n\t)\n\tpinfo := notifee.myRelayPeer\n\tif conn.RemotePeer().Pretty() != pinfo.ID.Pretty() {\n\t\treturn\n\t}\n\n\tnotifee.myHost.Peerstore().AddAddrs(pinfo.ID, pinfo.Addrs, peerstore.PermanentAddrTTL)\n\tfor {\n\t\tvar err error\n\t\tselect {\n\t\tcase _, open := <-notifee.closing:\n\t\t\tif !open {\n\t\t\t\treturn\n\t\t\t}\n\t\tdefault:\n\t\t\tnotifee.logger.Warn().Msgf(\n\t\t\t\t\"Lost connection to relay peer %s, reconnecting...\",\n\t\t\t\tpinfo.ID.Pretty(),\n\t\t\t)\n\t\t\tctx, cancel := context.WithTimeout(context.Background(), reconnectTimeout)\n\t\t\tdefer cancel()\n\t\t\tif err = notifee.myHost.Connect(ctx, pinfo); err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(1 * time.Second)\n\n\t\t}\n\t\tif err == nil {\n\t\t\tbreak\n\t\t}\n\t}\n\tnotifee.logger.Info().Msgf(\"Connection to relay peer %s reestablished\", pinfo.ID.Pretty())\n}",
"func (this *Monitor) Disconnect() error {\n\t// Advance to disconnecting state only if connected\n\tok, state := this.stateTransition(StateConnected, StateDisconnecting)\n\tif !ok {\n\t\tthis.Logf(LogLevelDebug, \"Cannot disconnect because monitor is %s\", state.String())\n\t\treturn errors.New(\"Cannot disconnect because monitor is \" + state.String())\n\t}\n\n\t// TODO: Implmement a graceful disconnect from the server\n\t// TODO: send termination package, requires an ACK to work properly\n\t// TODO: but only with max retries just like for connect\n\n\t// Interupt loops\n\tthis.disconnectWaitGroup.Add(3) // TODO: how many routines do we actually have?\n\tthis.connected = false // this prevents any more messages to be sent\n\tclose(this.disconnect)\n\tthis.disconnectWaitGroup.Wait()\n\tclose(this.statusMessageChannel)\n\tclose(this.controlMessageChannel)\n\n\t// Close the connection and signal connection state\n\tthis.connection.Close()\n\tthis.stateTransition(StateDisconnecting, StateDisconnected)\n\tthis.Log(LogLevelDebug, \"Disconnected\")\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
LaunchTask is called when the executor receives a request to launch a task. The happens when the k8sm scheduler has decided to schedule the pod (which corresponds to a Mesos Task) onto the node where this executor is running, but the binding is not recorded in the Kubernetes store yet. This function is invoked to tell the executor to record the binding in the Kubernetes store and start the pod via the Kubelet.
|
func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {
if k.isDone() {
return
}
log.Infof("Launch task %v\n", taskInfo)
if !k.isConnected() {
log.Errorf("Ignore launch task because the executor is disconnected\n")
k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
messages.ExecutorUnregistered))
return
}
obj, err := api.Codec.Decode(taskInfo.GetData())
if err != nil {
log.Errorf("failed to extract yaml data from the taskInfo.data %v", err)
k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
messages.UnmarshalTaskDataFailure))
return
}
pod, ok := obj.(*api.Pod)
if !ok {
log.Errorf("expected *api.Pod instead of %T: %+v", pod, pod)
k.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,
messages.UnmarshalTaskDataFailure))
return
}
k.lock.Lock()
defer k.lock.Unlock()
taskId := taskInfo.GetTaskId().GetValue()
if _, found := k.tasks[taskId]; found {
log.Errorf("task already launched\n")
// Not to send back TASK_RUNNING here, because
// may be duplicated messages or duplicated task id.
return
}
// remember this task so that:
// (a) we ignore future launches for it
// (b) we have a record of it so that we can kill it if needed
// (c) we're leaving podName == "" for now, indicates we don't need to delete containers
k.tasks[taskId] = &kuberTask{
mesosTaskInfo: taskInfo,
}
k.resetSuicideWatch(driver)
go k.launchTask(driver, taskId, pod)
}
|
[
"func (k *Executor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\n\tlog.Infof(\"Launch task %v\\n\", taskInfo)\n\n\ttaskID := taskInfo.GetTaskId().GetValue()\n\tif p := k.registry.pod(taskID); p != nil {\n\t\tlog.Warningf(\"task %v already launched\", taskID)\n\t\t// Not to send back TASK_RUNNING or TASK_FAILED here, because\n\t\t// may be duplicated messages\n\t\treturn\n\t}\n\n\tif !k.isConnected() {\n\t\tlog.Errorf(\"Ignore launch task because the executor is disconnected\\n\")\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.ExecutorUnregistered))\n\t\treturn\n\t}\n\n\tobj, err := kruntime.Decode(api.Codecs.UniversalDecoder(), taskInfo.GetData())\n\tif err != nil {\n\t\tlog.Errorf(\"failed to extract yaml data from the taskInfo.data %v\", err)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\tpod, ok := obj.(*api.Pod)\n\tif !ok {\n\t\tlog.Errorf(\"expected *api.Pod instead of %T: %+v\", pod, pod)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\n\tk.resetSuicideWatch(driver)\n\n\t// run the next step aync because it calls out to apiserver and we don't want to block here\n\tgo k.bindAndWatchTask(driver, taskInfo, time.NewTimer(k.launchGracePeriod), pod)\n}",
"func (k *KubernetesExecutor) LaunchTask(driver bindings.ExecutorDriver, taskInfo *mesos.TaskInfo) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Launch task %v\\n\", taskInfo)\n\n\tif !k.isConnected() {\n\t\tlog.Warningf(\"Ignore launch task because the executor is disconnected\\n\")\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.ExecutorUnregistered))\n\t\treturn\n\t}\n\n\tvar pod api.BoundPod\n\tif err := yaml.Unmarshal(taskInfo.GetData(), &pod); err != nil {\n\t\tlog.Warningf(\"Failed to extract yaml data from the taskInfo.data %v\\n\", err)\n\t\tk.sendStatus(driver, newStatus(taskInfo.GetTaskId(), mesos.TaskState_TASK_FAILED,\n\t\t\tmessages.UnmarshalTaskDataFailure))\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\ttaskId := taskInfo.GetTaskId().GetValue()\n\tif _, found := k.tasks[taskId]; found {\n\t\tlog.Warningf(\"task already launched\\n\")\n\t\t// Not to send back TASK_RUNNING here, because\n\t\t// may be duplicated messages or duplicated task id.\n\t\treturn\n\t}\n\t// remember this task so that:\n\t// (a) we ignore future launches for it\n\t// (b) we have a record of it so that we can kill it if needed\n\t// (c) we're leaving podName == \"\" for now, indicates we don't need to delete containers\n\tk.tasks[taskId] = &kuberTask{\n\t\tmesosTaskInfo: taskInfo,\n\t}\n\tgo k.launchTask(driver, taskId, &pod)\n}",
"func (e *Executor) LaunchTask(executor.ExecutorDriver, *mesosproto.TaskInfo) {\n\te.Called()\n}",
"func (k *KubernetesScheduler) Bind(binding *api.Binding) error {\n\tk.Lock()\n\tdefer k.Unlock()\n\n\tpodId := binding.PodID\n\ttaskId, exists := k.podToTask[podId]\n\tif !exists {\n\t\treturn fmt.Errorf(\"Could not resolve pod '%s' to task id\", podId)\n\t}\n\n\ttask, exists := k.pendingTasks[taskId]\n\tif !exists {\n\t\treturn fmt.Errorf(\"Pod Task does not exist %v\\n\", taskId)\n\t}\n\n\t// TODO(jdef): ensure that the task hasAcceptedOffer(), it's possible that between\n\t// Schedule() and now that the offer for this task was rescinded or invalidated\n\n\t// TODO(k8s): move this to a watch/rectification loop.\n\tmanifest, err := k.makeManifest(binding.Host, *task.Pod)\n\tif err != nil {\n\t\tlog.Warningf(\"Failed to generate an updated manifest\")\n\t\treturn err\n\t}\n\n\t// update the manifest here to pick up things like environment variables that\n\t// pod containers will use for service discovery. the kubelet-executor uses this\n\t// manifest to instantiate the pods and this is the last update we make before\n\t// firing up the pod.\n\ttask.Pod.DesiredState.Manifest = manifest\n\ttask.TaskInfo.Data, err = yaml.Marshal(&manifest)\n\tif err != nil {\n\t\tlog.Warningf(\"Failed to marshal the updated manifest\")\n\t\treturn err\n\t}\n\n\t// TODO(yifan): By this time, there is a chance that the slave is disconnected.\n\tlog.V(2).Infof(\"Launching task : %v\", task)\n\tofferId := &mesos.OfferID{Value: proto.String(task.OfferIds[0])}\n\tif err := k.Driver.LaunchTasks(offerId, []*mesos.TaskInfo{task.TaskInfo}, nil); err != nil {\n\t\ttask.ClearTaskInfo()\n\t\t// TODO(jdef): decline the offer too?\n\t\treturn fmt.Errorf(\"Failed to launch task for pod %s: %v\", podId, err)\n\t}\n\ttask.Pod.DesiredState.Host = binding.Host\n\ttask.Launched = true\n\n\t// we *intentionally* do not record our binding to etcd since we're not using bindings\n\t// to manage pod lifecycle\n\treturn nil\n}",
"func (h *Hub) StartTask(ctx context.Context, request *pb.HubStartTaskRequest) (*pb.HubStartTaskReply, error) {\n\tlog.G(h.ctx).Info(\"handling StartTask request\", zap.Any(\"req\", request))\n\n\ttaskID := uuid.New()\n\tminer, err := h.selectMiner(request)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar startRequest = &pb.MinerStartRequest{\n\t\tId: taskID,\n\t\tRegistry: request.Registry,\n\t\tImage: request.Image,\n\t\tAuth: request.Auth,\n\t\tPublicKeyData: request.PublicKeyData,\n\t\tCommitOnStop: request.CommitOnStop,\n\t\tEnv: request.Env,\n\t\tUsage: request.Requirements.GetResources(),\n\t\tRestartPolicy: &pb.ContainerRestartPolicy{\n\t\t\tName: \"\",\n\t\t\tMaximumRetryCount: 0,\n\t\t},\n\t}\n\n\tresp, err := miner.Client.Start(ctx, startRequest)\n\tif err != nil {\n\t\treturn nil, status.Errorf(codes.Internal, \"failed to start %v\", err)\n\t}\n\n\troutes := []extRoute{}\n\tfor k, v := range resp.Ports {\n\t\t_, protocol, err := decodePortBinding(k)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to decode miner's port mapping\",\n\t\t\t\tzap.String(\"mapping\", k),\n\t\t\t\tzap.Error(err),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\trealPort, err := strconv.ParseUint(v.Port, 10, 16)\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to convert real port to uint16\",\n\t\t\t\tzap.Error(err),\n\t\t\t\tzap.String(\"port\", v.Port),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\troute, err := miner.router.RegisterRoute(taskID, protocol, v.IP, uint16(realPort))\n\t\tif err != nil {\n\t\t\tlog.G(h.ctx).Warn(\"failed to register route\", zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\troutes = append(routes, extRoute{\n\t\t\tcontainerPort: k,\n\t\t\troute: route,\n\t\t})\n\t}\n\n\th.setMinerTaskID(miner.ID(), taskID)\n\n\tresources := request.GetRequirements().GetResources()\n\tcpuCount := resources.GetCPUCores()\n\tmemoryCount := resources.GetMaxMemory()\n\n\tvar usage = resource.NewResources(int(cpuCount), int64(memoryCount))\n\tif err := miner.Consume(taskID, &usage); err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar reply = pb.HubStartTaskReply{\n\t\tId: taskID,\n\t}\n\n\tfor _, route := range routes {\n\t\treply.Endpoint = append(\n\t\t\treply.Endpoint,\n\t\t\tfmt.Sprintf(\"%s->%s:%d\", route.containerPort, route.route.Host, route.route.Port),\n\t\t)\n\t}\n\n\treturn &reply, nil\n}",
"func (c *DockerScheduler) startTask(task *demand.Task) {\n\tvar labels = map[string]string{\n\t\tlabelMap: task.Name,\n\t}\n\n\tvar cmds = strings.Fields(task.Command)\n\n\tcreateOpts := docker.CreateContainerOptions{\n\t\tConfig: &docker.Config{\n\t\t\tImage: task.Image,\n\t\t\tCmd: cmds,\n\t\t\tAttachStdout: true,\n\t\t\tAttachStdin: true,\n\t\t\tLabels: labels,\n\t\t\tEnv: task.Env,\n\t\t},\n\t\tHostConfig: &docker.HostConfig{\n\t\t\tPublishAllPorts: task.PublishAllPorts,\n\t\t\tNetworkMode: task.NetworkMode,\n\t\t},\n\t}\n\n\tgo func() {\n\t\tscaling.Add(1)\n\t\tdefer scaling.Done()\n\n\t\tlog.Debugf(\"[start] task %s\", task.Name)\n\t\tcontainer, err := c.client.CreateContainer(createOpts)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Couldn't create container for task %s: %v\", task.Name, err)\n\t\t\treturn\n\t\t}\n\n\t\tvar containerID = container.ID[:12]\n\n\t\tc.Lock()\n\t\tc.taskContainers[task.Name][containerID] = &dockerContainer{\n\t\t\tstate: \"created\",\n\t\t}\n\t\tc.Unlock()\n\t\tlog.Debugf(\"[created] task %s ID %s\", task.Name, containerID)\n\n\t\t// Start it but passing nil for the HostConfig as this option was removed in Docker 1.12.\n\t\terr = c.client.StartContainer(containerID, nil)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Couldn't start container ID %s for task %s: %v\", containerID, task.Name, err)\n\t\t\treturn\n\t\t}\n\n\t\tlog.Debugf(\"[starting] task %s ID %s\", task.Name, containerID)\n\n\t\tc.Lock()\n\t\tc.taskContainers[task.Name][containerID].state = \"starting\"\n\t\tc.Unlock()\n\t}()\n}",
"func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) {\n\tif _, ok := d.tasks.Get(cfg.ID); ok {\n\t\treturn nil, nil, fmt.Errorf(\"task with ID %q already started\", cfg.ID)\n\t}\n\n\tvar driverConfig api.TaskConfig\n\n\tif err := cfg.DecodeDriverConfig(&driverConfig); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode task config: %v\", err)\n\t}\n\n\t// make all relevant strings lower case before processing\n\tdriverConfig.ToLower()\n\td.logger.Info(\"starting task\", \"driver_cfg\", hclog.Fmt(\"%+v\", driverConfig))\n\n\thandle := drivers.NewTaskHandle(taskHandleVersion)\n\thandle.Config = cfg\n\n\t// TODO: implement driver specific mechanism to start the task.\n\t//\n\t// Once the task is started you will need to store any relevant runtime\n\t// information in a taskHandle and TaskState. The taskHandle will be\n\t// stored in-memory in the plugin and will be used to interact with the\n\t// task.\n\t//\n\t// The TaskState will be returned to the Nomad client inside a\n\t// drivers.TaskHandle instance. This TaskHandle will be sent back to plugin\n\t// if the task ever needs to be recovered, so the TaskState should contain\n\t// enough information to handle that.\n\n\t// define and start domain\n\tdomainSpec, err := d.domainManager.SyncVM(cfg, &driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Detect domain address\n\t// stop and undefine domain if can't get ipv4 address\n\tguestIf, err := d.domainManager.DomainIfAddr(domainSpec.Name, true)\n\tif err != nil {\n\t\td.logger.Error(\"error getting domain address waiting for ipv4 addr\", \"error\", err)\n\t\td.domainManager.KillVM(domainSpec.Name)\n\t\td.domainManager.DestroyVM(domainSpec.Name)\n\t\treturn nil, nil, err\n\t}\n\n\t// default value for net, works for the following two cases:\n\t// 1. the domain has only lo interface\n\t// 2. or the domain has a non-lo interface but has no ip address assigned\n\tdrvNet := &drivers.DriverNetwork{}\n\n\tif guestIf != nil {\n\t\tfor _, ip := range guestIf.IPs {\n\t\t\td.logger.Debug(\"domain interface from guest agent\", \"ip\", ip.IP, \"type\", ip.Type, \"prefix\", ip.Prefix)\n\t\t\tif ip.Type == \"ipv4\" {\n\t\t\t\tdrvNet.IP = ip.IP\n\t\t\t\tif len(driverConfig.Interfaces) > 0 && driverConfig.Interfaces[0].InterfaceBindingMethod != \"network\" {\n\t\t\t\t\tdrvNet.AutoAdvertise = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Return a driver handle\n\th := &taskHandle{\n\t\tdomainManager: d.domainManager,\n\t\tresultChan: make(chan *drivers.ExitResult),\n\t\ttask: cfg, //contains taskid allocid for future use\n\t\tstartedAt: time.Now().Round(time.Millisecond),\n\t\tnet: drvNet,\n\t\tresourceUsage: &cstructs.TaskResourceUsage{\n\t\t\tResourceUsage: &cstructs.ResourceUsage{\n\t\t\t\tMemoryStats: &cstructs.MemoryStats{},\n\t\t\t\tCpuStats: &cstructs.CpuStats{},\n\t\t\t},\n\t\t}, // initial empty usage data, so that we won't return nil in stats channel\n\t}\n\n\t//config := &plugin.ClientConfig{\n\t//\tHandshakeConfig: base.Handshake,\n\t//\tPlugins: map[string]plugin.Plugin{\"executor\": p},\n\t//\tCmd: exec.Command(bin, \"executor\", string(c)),\n\t//\tAllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC},\n\t//\tLogger: logger.Named(\"executor\"),\n\t//}\n\t//\n\t//if driverConfig != nil {\n\t//\tconfig.MaxPort = driverConfig.ClientMaxPort\n\t//\tconfig.MinPort = driverConfig.ClientMinPort\n\t//} else {\n\t//\tconfig.MaxPort = ExecutorDefaultMaxPort\n\t//\tconfig.MinPort = ExecutorDefaultMinPort\n\t//}\n\n\tif err := handle.SetDriverState(h.buildState(cfg)); err != nil {\n\t\td.logger.Error(\"error persisting handle state\")\n\t\treturn nil, nil, err\n\t}\n\td.tasks.Set(cfg.ID, h)\n\n\td.logger.Debug(\"returning from starttask\")\n\treturn handle, drvNet, nil\n}",
"func (lenc *Lencak) StartTask(workSpaceName, taskName string, asService bool) bool {\n\treturn lenc.WithWorkspaceTask(workSpaceName, taskName, func(task *Task) {\n\t\tif asService {\n\t\t\ttask.serviceMu.Lock()\n\t\t\ttask.Service = true\n\t\t\ttask.serviceMu.Unlock()\n\t\t\tif task.ActiveTask == nil {\n\t\t\t\ttask.Start(lenc.sync)\n\t\t\t}\n\t\t} else {\n\t\t\ttask.Start(lenc.sync)\n\t\t}\n\t})\n}",
"func StartTask(ctx context.Context, id string, op Operation, driver Driver, opts Options) *Task {\n\tt := newTask(id, op)\n\tif t == nil {\n\t\treturn nil\n\t}\n\tt.start = time.Now()\n\tgo t.run(ctx, driver, opts)\n\treturn t\n}",
"func (c *client) StartTask(ctx context.Context, data StartTaskRequest) error {\n\turl := c.createURLs(\"/_api/task\", nil)\n\n\treq, err := c.newRequests(\"POST\", url, data)\n\tif err != nil {\n\t\treturn maskAny(err)\n\t}\n\tif err := c.do(ctx, req, nil); err != nil {\n\t\treturn maskAny(err)\n\t}\n\n\treturn nil\n}",
"func (rm *ResponseManager) StartTask(task *peertask.Task, responseTaskDataChan chan<- ResponseTaskData) {\n\trm.send(&startTaskRequest{task, responseTaskDataChan}, nil)\n}",
"func (d *Driver) StartTask(cfg *drivers.TaskConfig) (*drivers.TaskHandle, *drivers.DriverNetwork, error) {\n\tif _, ok := d.tasks.Get(cfg.ID); ok {\n\t\treturn nil, nil, fmt.Errorf(\"task with ID %q already started\", cfg.ID)\n\t}\n\n\tvar driverConfig TaskConfig\n\tif err := cfg.DecodeDriverConfig(&driverConfig); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"failed to decode driver config: %v\", err)\n\t}\n\n\thandle := drivers.NewTaskHandle(taskHandleVersion)\n\thandle.Config = cfg\n\n\tif driverConfig.Image == \"\" {\n\t\treturn nil, nil, fmt.Errorf(\"image name required\")\n\t}\n\n\tcreateOpts := api.SpecGenerator{}\n\tcreateOpts.ContainerBasicConfig.LogConfiguration = &api.LogConfig{}\n\tallArgs := []string{}\n\tif driverConfig.Command != \"\" {\n\t\tallArgs = append(allArgs, driverConfig.Command)\n\t}\n\tallArgs = append(allArgs, driverConfig.Args...)\n\n\tif driverConfig.Entrypoint != \"\" {\n\t\tcreateOpts.ContainerBasicConfig.Entrypoint = append(createOpts.ContainerBasicConfig.Entrypoint, driverConfig.Entrypoint)\n\t}\n\n\tcontainerName := BuildContainerName(cfg)\n\n\t// ensure to include port_map into tasks environment map\n\tcfg.Env = taskenv.SetPortMapEnvs(cfg.Env, driverConfig.PortMap)\n\n\t// Basic config options\n\tcreateOpts.ContainerBasicConfig.Name = containerName\n\tcreateOpts.ContainerBasicConfig.Command = allArgs\n\tcreateOpts.ContainerBasicConfig.Env = cfg.Env\n\tcreateOpts.ContainerBasicConfig.Hostname = driverConfig.Hostname\n\tcreateOpts.ContainerBasicConfig.Sysctl = driverConfig.Sysctl\n\n\tcreateOpts.ContainerBasicConfig.LogConfiguration.Path = cfg.StdoutPath\n\n\t// Storage config options\n\tcreateOpts.ContainerStorageConfig.Init = driverConfig.Init\n\tcreateOpts.ContainerStorageConfig.Image = driverConfig.Image\n\tcreateOpts.ContainerStorageConfig.InitPath = driverConfig.InitPath\n\tcreateOpts.ContainerStorageConfig.WorkDir = driverConfig.WorkingDir\n\tallMounts, err := d.containerMounts(cfg, &driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerStorageConfig.Mounts = allMounts\n\n\t// Resources config options\n\tcreateOpts.ContainerResourceConfig.ResourceLimits = &spec.LinuxResources{\n\t\tMemory: &spec.LinuxMemory{},\n\t\tCPU: &spec.LinuxCPU{},\n\t}\n\tif driverConfig.MemoryReservation != \"\" {\n\t\treservation, err := memoryInBytes(driverConfig.MemoryReservation)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Reservation = &reservation\n\t}\n\n\tif cfg.Resources.NomadResources.Memory.MemoryMB > 0 {\n\t\tlimit := cfg.Resources.NomadResources.Memory.MemoryMB * 1024 * 1024\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Limit = &limit\n\t}\n\tif driverConfig.MemorySwap != \"\" {\n\t\tswap, err := memoryInBytes(driverConfig.MemorySwap)\n\t\tif err != nil {\n\t\t\treturn nil, nil, err\n\t\t}\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swap = &swap\n\t}\n\tif !d.cgroupV2 {\n\t\tswappiness := uint64(driverConfig.MemorySwappiness)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.Memory.Swappiness = &swappiness\n\t}\n\t// FIXME: can fail for nonRoot due to missing cpu limit delegation permissions,\n\t// see https://github.com/containers/podman/blob/master/troubleshooting.md\n\tif !d.systemInfo.Host.Rootless {\n\t\tcpuShares := uint64(cfg.Resources.LinuxResources.CPUShares)\n\t\tcreateOpts.ContainerResourceConfig.ResourceLimits.CPU.Shares = &cpuShares\n\t}\n\n\t// Security config options\n\tcreateOpts.ContainerSecurityConfig.CapAdd = driverConfig.CapAdd\n\tcreateOpts.ContainerSecurityConfig.CapDrop = driverConfig.CapDrop\n\tcreateOpts.ContainerSecurityConfig.User = cfg.User\n\n\t// Network config options\n\tfor _, strdns := range driverConfig.Dns {\n\t\tipdns := net.ParseIP(strdns)\n\t\tif ipdns == nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"Invald dns server address\")\n\t\t}\n\t\tcreateOpts.ContainerNetworkConfig.DNSServers = append(createOpts.ContainerNetworkConfig.DNSServers, ipdns)\n\t}\n\t// Configure network\n\tif cfg.NetworkIsolation != nil && cfg.NetworkIsolation.Path != \"\" {\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Path\n\t\tcreateOpts.ContainerNetworkConfig.NetNS.Value = cfg.NetworkIsolation.Path\n\t} else {\n\t\tif driverConfig.NetworkMode == \"\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"bridge\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Bridge\n\t\t} else if driverConfig.NetworkMode == \"host\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Host\n\t\t} else if driverConfig.NetworkMode == \"none\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.NoNetwork\n\t\t} else if driverConfig.NetworkMode == \"slirp4netns\" {\n\t\t\tcreateOpts.ContainerNetworkConfig.NetNS.NSMode = api.Slirp\n\t\t} else {\n\t\t\treturn nil, nil, fmt.Errorf(\"Unknown/Unsupported network mode: %s\", driverConfig.NetworkMode)\n\t\t}\n\t}\n\n\tportMappings, err := d.portMappings(cfg, driverConfig)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\tcreateOpts.ContainerNetworkConfig.PortMappings = portMappings\n\n\tcontainerID := \"\"\n\trecoverRunningContainer := false\n\t// check if there is a container with same name\n\totherContainerInspect, err := d.podman.ContainerInspect(d.ctx, containerName)\n\tif err == nil {\n\t\t// ok, seems we found a container with similar name\n\t\tif otherContainerInspect.State.Running {\n\t\t\t// it's still running. So let's use it instead of creating a new one\n\t\t\td.logger.Info(\"Detect running container with same name, we reuse it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tcontainerID = otherContainerInspect.ID\n\t\t\trecoverRunningContainer = true\n\t\t} else {\n\t\t\t// let's remove the old, dead container\n\t\t\td.logger.Info(\"Detect stopped container with same name, removing it\", \"task\", cfg.ID, \"container\", otherContainerInspect.ID)\n\t\t\tif err = d.podman.ContainerDelete(d.ctx, otherContainerInspect.ID, true, true); err != nil {\n\t\t\t\treturn nil, nil, nstructs.WrapRecoverable(fmt.Sprintf(\"failed to remove dead container: %v\", err), err)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\t// FIXME: there are more variations of image sources, we should handle it\n\t\t// e.g. oci-archive:/... etc\n\t\t// see also https://github.com/hashicorp/nomad-driver-podman/issues/69\n\t\t// do we already have this image in local storage?\n\t\thaveImage, err := d.podman.ImageExists(d.ctx, createOpts.Image)\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to check for local image: %v\", err)\n\t\t}\n\t\tif !haveImage {\n\t\t\t// image is not in local storage, so we need to pull it\n\t\t\tif err = d.podman.ImagePull(d.ctx, createOpts.Image); err != nil {\n\t\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, unable to pull image %s: %v\", createOpts.Image, err)\n\t\t\t}\n\t\t}\n\n\t\tcreateResponse, err := d.podman.ContainerCreate(d.ctx, createOpts)\n\t\tfor _, w := range createResponse.Warnings {\n\t\t\td.logger.Warn(\"Create Warning\", \"warning\", w)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not create container: %v\", err)\n\t\t}\n\t\tcontainerID = createResponse.Id\n\t}\n\n\tcleanup := func() {\n\t\td.logger.Debug(\"Cleaning up\", \"container\", containerID)\n\t\tif err := d.podman.ContainerDelete(d.ctx, containerID, true, true); err != nil {\n\t\t\td.logger.Error(\"failed to clean up from an error in Start\", \"error\", err)\n\t\t}\n\t}\n\n\tif !recoverRunningContainer {\n\t\tif err = d.podman.ContainerStart(d.ctx, containerID); err != nil {\n\t\t\tcleanup()\n\t\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not start container: %v\", err)\n\t\t}\n\t}\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, containerID)\n\tif err != nil {\n\t\td.logger.Error(\"failed to inspect container\", \"err\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to start task, could not inspect container : %v\", err)\n\t}\n\n\tnet := &drivers.DriverNetwork{\n\t\tPortMap: driverConfig.PortMap,\n\t\tIP: inspectData.NetworkSettings.IPAddress,\n\t\tAutoAdvertise: true,\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: containerID,\n\t\tdriver: d,\n\t\ttaskConfig: cfg,\n\t\tprocState: drivers.TaskStateRunning,\n\t\texitResult: &drivers.ExitResult{},\n\t\tstartedAt: time.Now().Round(time.Millisecond),\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tdriverState := TaskState{\n\t\tContainerID: containerID,\n\t\tTaskConfig: cfg,\n\t\tStartedAt: h.startedAt,\n\t\tNet: net,\n\t}\n\n\tif err := handle.SetDriverState(&driverState); err != nil {\n\t\td.logger.Error(\"failed to start task, error setting driver state\", \"error\", err)\n\t\tcleanup()\n\t\treturn nil, nil, fmt.Errorf(\"failed to set driver state: %v\", err)\n\t}\n\n\td.tasks.Set(cfg.ID, h)\n\n\tgo h.runContainerMonitor()\n\n\td.logger.Info(\"Completely started container\", \"taskID\", cfg.ID, \"container\", containerID, \"ip\", inspectData.NetworkSettings.IPAddress)\n\n\treturn handle, net, nil\n}",
"func (i *TaskRegisterUpdater) StartTask(ctx context.Context, action string, age time.Duration) (models.Task, error) {\n\n\treturn i.repository.GetTask(ctx, action, age)\n}",
"func (c *TestClient) TriggerTask(t *swarming.SwarmingRpcsNewTaskRequest) (*swarming.SwarmingRpcsTaskRequestMetadata, error) {\n\tcreatedTs := time.Now().UTC().Format(TIMESTAMP_FORMAT)\n\tid := uuid.NewV5(uuid.NewV1(), uuid.NewV4().String()).String()\n\trv := &swarming.SwarmingRpcsTaskRequestMetadata{\n\t\tRequest: &swarming.SwarmingRpcsTaskRequest{\n\t\t\tCreatedTs: createdTs,\n\t\t\tExpirationSecs: t.ExpirationSecs,\n\t\t\tName: t.Name,\n\t\t\tPriority: t.Priority,\n\t\t\tProperties: t.Properties,\n\t\t\tTags: t.Tags,\n\t\t},\n\t\tTaskId: id,\n\t\tTaskResult: &swarming.SwarmingRpcsTaskResult{\n\t\t\tCreatedTs: createdTs,\n\t\t\tName: t.Name,\n\t\t\tState: \"PENDING\",\n\t\t\tTaskId: id,\n\t\t\tTags: t.Tags,\n\t\t},\n\t}\n\tc.taskListMtx.Lock()\n\tdefer c.taskListMtx.Unlock()\n\tc.taskList = append(c.taskList, rv)\n\treturn rv, nil\n}",
"func (s stressng) Launch() (executor.TaskHandle, error) {\n\treturn s.executor.Execute(fmt.Sprintf(\"stress-ng %s\", s.arguments))\n}",
"func (c Control) ServeStartTask(w http.ResponseWriter, r *http.Request) {\n\tc.ServeTaskAction(w, r, true)\n}",
"func StartDMTask(fw portforward.PortForward, ns, masterSvcName, taskConf, errSubStr string) error {\n\tapiPath := \"/apis/v1alpha1/tasks\"\n\n\ttype Req struct {\n\t\tTask string `json:\"task\"`\n\t}\n\ttype Resp struct {\n\t\tResult bool `json:\"result\"`\n\t\tMsg string `json:\"msg\"`\n\t\tCheckResult string `json:\"checkResult\"`\n\t}\n\n\tvar req = Req{\n\t\tTask: fmt.Sprintf(taskConf, DMTaskName(ns), v1alpha1.DefaultTiDBServerPort, DMTaskName(ns)),\n\t}\n\tdata, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal task start request, %v, %v\", req, err)\n\t}\n\n\treturn wait.Poll(5*time.Second, time.Minute, func() (bool, error) {\n\t\tlocalHost, localPort, cancel, err := portforward.ForwardOnePort(\n\t\t\tfw, ns, fmt.Sprintf(\"svc/%s\", masterSvcName), dmMasterSvcPort)\n\t\tif err != nil {\n\t\t\tlog.Logf(\"failed to forward dm-master svc: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tdefer cancel()\n\n\t\tbody, err := httputil.DoBodyOK(\n\t\t\t&http.Client{Transport: &http.Transport{}},\n\t\t\tfmt.Sprintf(\"http://%s:%d%s\", localHost, localPort, apiPath),\n\t\t\t\"POST\",\n\t\t\tbytes.NewReader(data))\n\t\tif err != nil {\n\t\t\tlog.Logf(\"failed to start DM task: %v\", err)\n\t\t\treturn false, nil\n\t\t}\n\t\tvar resp Resp\n\t\tif err = json.Unmarshal(body, &resp); err != nil {\n\t\t\tlog.Logf(\"failed to unmarshal DM task start response, %s: %v\", string(body), err)\n\t\t\treturn false, nil\n\t\t} else if !resp.Result && !strings.Contains(resp.Msg, \"already exists\") {\n\t\t\tif errSubStr != \"\" && strings.Contains(resp.Msg, errSubStr) {\n\t\t\t\tlog.Logf(\"start DM task match the error sub string %q: %s\", errSubStr, resp.Msg)\n\t\t\t\treturn true, nil\n\t\t\t}\n\t\t\tlog.Logf(\"failed to start DM task, msg: %s, err: %v, checkResult: %s\", resp.Msg, err, resp.CheckResult)\n\t\t\treturn false, nil\n\t\t}\n\t\treturn true, nil\n\t})\n}",
"func (e *ECS) StartTask(req *StartTaskReq) (*StartTaskResp, error) {\n\tif req == nil {\n\t\treturn nil, fmt.Errorf(\"The req params cannot be nil\")\n\t}\n\n\tparams := makeParams(\"StartTask\")\n\tif req.Cluster != \"\" {\n\t\tparams[\"cluster\"] = req.Cluster\n\t}\n\tif req.TaskDefinition != \"\" {\n\t\tparams[\"taskDefinition\"] = req.TaskDefinition\n\t}\n\tfor i, ci := range req.ContainerInstances {\n\t\tparams[fmt.Sprintf(\"containerInstances.member.%d\", i+1)] = ci\n\t}\n\tfor i, co := range req.Overrides.ContainerOverrides {\n\t\tkey := fmt.Sprintf(\"overrides.containerOverrides.member.%d\", i+1)\n\t\tparams[fmt.Sprintf(\"%s.name\", key)] = co.Name\n\t\tfor k, cmd := range co.Command {\n\t\t\tparams[fmt.Sprintf(\"%s.command.member.%d\", key, k+1)] = cmd\n\t\t}\n\t}\n\n\tresp := new(StartTaskResp)\n\tif err := e.query(params, resp); err != nil {\n\t\treturn nil, err\n\t}\n\treturn resp, nil\n}",
"func StartTaskService(brain *brain.Manager, errChan chan error) {\n\tlis, err := net.Listen(\"tcp\", taskServicePort)\n\tif err != nil {\n\t\terrChan <- err\n\t\treturn\n\t}\n\n\tgrpcServer := grpc.NewServer()\n\n\tRegisterTaskServiceServer(grpcServer, TaskService{Manager: brain})\n\n\tlog.LogInfo(\"starting taask-server task service on :3688\")\n\tif err := grpcServer.Serve(lis); err != nil {\n\t\terrChan <- err\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
determine whether we need to start a suicide countdown. if so, then start a timer that, upon expiration, causes this executor to commit suicide. this implementation runs asynchronously. callers that wish to wait for the reset to complete may wait for the returned signal chan to close.
|
func (k *KubernetesExecutor) resetSuicideWatch(driver bindings.ExecutorDriver) <-chan struct{} {
ch := make(chan struct{})
go func() {
defer close(ch)
k.lock.Lock()
defer k.lock.Unlock()
if k.suicideTimeout < 1 {
return
}
if k.suicideWatch != nil {
if len(k.tasks) > 0 {
k.suicideWatch.Stop()
return
}
if k.suicideWatch.Reset(k.suicideTimeout) {
// valid timer, reset was successful
return
}
}
//TODO(jdef) reduce verbosity here once we're convinced that suicide watch is working properly
log.Infof("resetting suicide watch timer for %v", k.suicideTimeout)
k.suicideWatch = k.suicideWatch.Next(k.suicideTimeout, driver, jumper(k.attemptSuicide))
}()
return ch
}
|
[
"func (k *Executor) resetSuicideWatch(driver bindings.ExecutorDriver) <-chan struct{} {\n\tch := make(chan struct{})\n\tgo func() {\n\t\tdefer close(ch)\n\t\tk.lock.Lock()\n\t\tdefer k.lock.Unlock()\n\n\t\tif k.suicideTimeout < 1 {\n\t\t\treturn\n\t\t}\n\n\t\tif k.suicideWatch != nil {\n\t\t\tif !k.registry.empty() {\n\t\t\t\tk.suicideWatch.Stop()\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif k.suicideWatch.Reset(k.suicideTimeout) {\n\t\t\t\t// valid timer, reset was successful\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\t//TODO(jdef) reduce verbosity here once we're convinced that suicide watch is working properly\n\t\tlog.Infof(\"resetting suicide watch timer for %v\", k.suicideTimeout)\n\n\t\tk.suicideWatch = k.suicideWatch.Next(k.suicideTimeout, driver, jumper(k.attemptSuicide))\n\t}()\n\treturn ch\n}",
"func TestRetryTimerSimple(t *testing.T) {\n\tdoneCh := make(chan struct{})\n\tattemptCh := newRetryTimerSimple(doneCh)\n\ti := <-attemptCh\n\tif i != 0 {\n\t\tclose(doneCh)\n\t\tt.Fatalf(\"Invalid attempt counter returned should be 0, found %d instead\", i)\n\t}\n\ti = <-attemptCh\n\tif i <= 0 {\n\t\tclose(doneCh)\n\t\tt.Fatalf(\"Invalid attempt counter returned should be greater than 0, found %d instead\", i)\n\t}\n\tclose(doneCh)\n\t_, ok := <-attemptCh\n\tif ok {\n\t\tt.Fatal(\"Attempt counter should be closed\")\n\t}\n}",
"func (r *FailBack) startResetTimer() chan struct{} {\n\tfailCh := make(chan struct{}, 1)\n\tgo func() {\n\t\ttimer := time.NewTimer(r.opt.ResetAfter)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-failCh:\n\t\t\t\tif !timer.Stop() {\n\t\t\t\t\t<-timer.C\n\t\t\t\t}\n\t\t\tcase <-timer.C:\n\t\t\t\tr.mu.Lock()\n\t\t\t\tr.active = 0\n\t\t\t\tLog.WithField(\"resolver\", r.resolvers[r.active].String()).Debug(\"failing back to resolver\")\n\t\t\t\tr.mu.Unlock()\n\t\t\t\tr.metrics.available.Add(1)\n\t\t\t\t// we just reset to the first resolver, let's wait for another failure before running again\n\t\t\t\t<-failCh\n\t\t\t}\n\t\t\ttimer.Reset(r.opt.ResetAfter)\n\t\t}\n\t}()\n\treturn failCh\n}",
"func ensureSignalBeforeTimeout(signalCh <-chan struct{}, timeout time.Duration) bool {\n\ttimer := time.NewTimer(timeout)\n\tdefer timer.Stop()\n\tselect {\n\tcase <-timer.C:\n\t\treturn false\n\tcase <-signalCh:\n\t\treturn true\n\t}\n}",
"func cancel() {\n\tch := make(chan string, 1)\n\n\tfor i := 1; i <= 10; i++ {\n\t\tfmt.Println(\"Trial \", i)\n\t\t// worker\n\t\tgo func() {\n\t\t\ttime.Sleep(time.Duration(rand.Intn(500)) * time.Millisecond)\n\t\t\tch <- \"paperwork\"\n\t\t\tfmt.Println(\"employee: sent paperwork\")\n\t\t}()\n\n\t\t// create a timer channel which will ping us 100ms in the future\n\t\ttc := time.After(100 * time.Millisecond)\n\n\t\tselect {\n\t\tcase p := <-ch:\n\t\t\tfmt.Println(\"manager: received signal from worker:\", p)\n\t\tcase t := <-tc:\n\t\t\tfmt.Println(\"manager: timeout. Done waiting. (msg:\", t, \")\")\n\t\t}\n\t}\n\n\ttime.Sleep(time.Second)\n}",
"func (ctx *DeferredContext) KickTimer() {\n\tctx.Ticker.TickNow()\n}",
"func (qp *quotaPool) cancel() {\n\tqp.lock.Lock()\n\tdefer qp.lock.Unlock()\n\tselect {\n\tcase n := <-qp.acquireChannel:\n\t\tqp.quota += n\n\tdefault:\n\t}\n}",
"func run(txer ndauTxer, minTime, maxTime time.Duration, logger *log.Entry) error {\n\tnomChan := make(chan Nomination, 0)\n\n\t// handle a ctrl C to shut down gracefully\n\tsignalChan := make(chan os.Signal, 0)\n\tsignal.Notify(signalChan, os.Interrupt)\n\n\t// and ensure the graceful shutdown\n\tdefer close(nomChan)\n\tdefer close(signalChan)\n\n\t// our cycle time can be non-cryptographically random\n\tgetCycleTime := func() time.Duration {\n\t\treturn maxTime + time.Duration(rand.Intn(int(maxTime-minTime)))\n\t}\n\ttimer := time.NewTimer(getCycleTime())\n\n\ttxer.Listen(nomChan)\n\n\tfor {\n\t\tselect {\n\t\t// if the timer runs out we need to post a tx\n\t\tcase <-timer.C:\n\t\t\tr, err := cryptorand.Int(cryptorand.Reader, big.NewInt(math.MaxInt64))\n\t\t\tif err != nil {\n\t\t\t\tlogger.WithError(err).Error(\"cryptorand returned error\")\n\t\t\t} else {\n\t\t\t\ttxer.Post(r.Int64())\n\t\t\t}\n\t\t\ttimer.Reset(getCycleTime())\n\t\tcase n := <-nomChan:\n\t\t\t// we got a nomination from someone else, so reset our timer\n\t\t\t// in a way that doesn't race\n\t\t\tif !timer.Stop() {\n\t\t\t\t<-timer.C\n\t\t\t}\n\t\t\ttimer.Reset(getCycleTime())\n\t\t\tfmt.Println(\"resetting timer because \", n)\n\t\tcase <-signalChan:\n\t\t\tlogger.Info(\"Received interrupt, stopping\")\n\t\t\treturn nil\n\t\t}\n\t}\n}",
"func (s *Stopper) Quiesce(ctx context.Context) {\n\tdefer s.Recover(ctx)\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tfor _, cancel := range s.mu.qCancels {\n\t\tcancel()\n\t}\n\tif !s.mu.quiescing {\n\t\ts.mu.quiescing = true\n\t\tclose(s.quiescer)\n\t}\n\tfor s.mu.numTasks > 0 {\n\t\tlog.Infof(ctx, \"quiescing; tasks left:\\n%s\", s.runningTasksLocked())\n\t\t// Unlock s.mu, wait for the signal, and lock s.mu.\n\t\ts.mu.quiesce.Wait()\n\t}\n}",
"func (db *DB) handleCsnpTickC() {\n\tcount := 0\n\tfor _, di := range db.dis {\n\t\tif di.c != nil {\n\t\t\tdi.c.Send(db.cachePdu(&di.i), db.li)\n\t\t\tcount++\n\t\t}\n\t}\n\tif count > 0 {\n\t\tdb.disTimer = time.AfterFunc(time.Second*10, func() {\n\t\t\tdb.csnpTickC <- true\n\t\t})\n\t\tdb.disTimer = nil\n\t}\n}",
"func (clock Timer) Countdown() {\n\tticker := newTicker()\n\tclock.runCountdown(ticker)\n}",
"func (tk *timekeeper) run() {\n\n\t//main timekeeper loop\nloop:\n\tfor {\n\t\tselect {\n\n\t\tcase cmd, ok := <-tk.supvCmdch:\n\t\t\tif ok {\n\t\t\t\tif cmd.GetMsgType() == TK_SHUTDOWN {\n\t\t\t\t\tcommon.Infof(\"Timekeeper::run Shutting Down\")\n\t\t\t\t\ttk.supvCmdch <- &MsgSuccess{}\n\t\t\t\t\tbreak loop\n\t\t\t\t}\n\t\t\t\ttk.handleSupvervisorCommands(cmd)\n\t\t\t} else {\n\t\t\t\t//supervisor channel closed. exit\n\t\t\t\tbreak loop\n\t\t\t}\n\n\t\t}\n\t}\n}",
"func Cron() {\n\tnow := time.Now()\n\tunn := now.UnixNano()\n\tManager.timers.Range(func(idInterface, tInterface interface{}) bool {\n\t\tt := tInterface.(*Timer)\n\t\tid := idInterface.(int64)\n\t\t// prevent ChClosingTimer exceed\n\t\tif t.counter == 0 {\n\t\t\tif len(Manager.ChClosingTimer) < timerBacklog {\n\t\t\t\tt.Stop()\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// condition timer\n\t\tif t.condition != nil {\n\t\t\tif t.condition.Check(now) {\n\t\t\t\tpexec(id, t.fn)\n\t\t\t}\n\t\t\treturn true\n\t\t}\n\n\t\t// execute job\n\t\tif t.createAt+t.elapse <= unn {\n\t\t\tpexec(id, t.fn)\n\t\t\tt.elapse += int64(t.interval)\n\n\t\t\t// update timer counter\n\t\t\tif t.counter != LoopForever && t.counter > 0 {\n\t\t\t\tt.counter--\n\t\t\t}\n\t\t}\n\t\treturn true\n\t})\n}",
"func (this *udpEndpoint) notifyDisco() {\n this.syncObj.Shutdown()\n\n if this.discoChan == nil {\n return\n }\n\n select {\n case this.discoChan<- this:\n case <-time.After(QUEUE_TIMEOUT_SEC * time.Second):\n log.Error(\"notifyDisco timeout\")\n case <-this.syncObj.QueryShutdown():\n return\n }\n}",
"func (i *idlenessManagerImpl) handleIdleTimeout() {\n\tif i.isClosed() {\n\t\treturn\n\t}\n\n\tif atomic.LoadInt32(&i.activeCallsCount) > 0 {\n\t\ti.resetIdleTimer(time.Duration(i.timeout))\n\t\treturn\n\t}\n\n\t// There has been activity on the channel since we last got here. Reset the\n\t// timer and return.\n\tif atomic.LoadInt32(&i.activeSinceLastTimerCheck) == 1 {\n\t\t// Set the timer to fire after a duration of idle timeout, calculated\n\t\t// from the time the most recent RPC completed.\n\t\tatomic.StoreInt32(&i.activeSinceLastTimerCheck, 0)\n\t\ti.resetIdleTimer(time.Duration(atomic.LoadInt64(&i.lastCallEndTime) + i.timeout - time.Now().UnixNano()))\n\t\treturn\n\t}\n\n\t// This CAS operation is extremely likely to succeed given that there has\n\t// been no activity since the last time we were here. Setting the\n\t// activeCallsCount to -math.MaxInt32 indicates to onCallBegin() that the\n\t// channel is either in idle mode or is trying to get there.\n\tif !atomic.CompareAndSwapInt32(&i.activeCallsCount, 0, -math.MaxInt32) {\n\t\t// This CAS operation can fail if an RPC started after we checked for\n\t\t// activity at the top of this method, or one was ongoing from before\n\t\t// the last time we were here. In both case, reset the timer and return.\n\t\ti.resetIdleTimer(time.Duration(i.timeout))\n\t\treturn\n\t}\n\n\t// Now that we've set the active calls count to -math.MaxInt32, it's time to\n\t// actually move to idle mode.\n\tif i.tryEnterIdleMode() {\n\t\t// Successfully entered idle mode. No timer needed until we exit idle.\n\t\treturn\n\t}\n\n\t// Failed to enter idle mode due to a concurrent RPC that kept the channel\n\t// active, or because of an error from the channel. Undo the attempt to\n\t// enter idle, and reset the timer to try again later.\n\tatomic.AddInt32(&i.activeCallsCount, math.MaxInt32)\n\ti.resetIdleTimer(time.Duration(i.timeout))\n}",
"func (f *failoverStatus) cancel() {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tif f.timer != nil {\n\t\tf.timer.Stop()\n\t}\n}",
"func (s *Stopper) Quiesce(ctx context.Context) {\n\tdefer time.AfterFunc(5*time.Second, func() {\n\t\tlog.Infof(ctx, \"quiescing...\")\n\t}).Stop()\n\tdefer s.Recover(ctx)\n\n\tfunc() {\n\t\ts.mu.Lock()\n\t\tdefer s.mu.Unlock()\n\t\tif !s.mu.quiescing {\n\t\t\ts.mu.quiescing = true\n\t\t\tclose(s.quiescer)\n\t\t}\n\n\t\ts.mu.qCancels.Range(func(k, v interface{}) (wantMore bool) {\n\t\t\tcancel := v.(func())\n\t\t\tcancel()\n\t\t\ts.mu.qCancels.Delete(k)\n\t\t\treturn true\n\t\t})\n\t}()\n\n\tfor s.NumTasks() > 0 {\n\t\ttime.Sleep(5 * time.Millisecond)\n\t}\n}",
"func resettimer(t *timer, when int64) bool {\n\treturn modtimer(t, when, t.period, t.f, t.arg, t.seq)\n}",
"func (th *Throttler) resetCounterLoop(after time.Duration) {\n\tticker := time.NewTicker(after)\n\tdefer ticker.Stop()\n\n\tfor {\n\t\tselect {\n\t\tcase <-ticker.C:\n\t\t\tif th.quotaHit() {\n\t\t\t\tatomic.StoreUint64(&th.counter, 0)\n\t\t\t\tth.doNotify()\n\t\t\t}\n\n\t\tcase <-th.done:\n\t\t\treturn\n\t\t}\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Intended to be executed as part of the pod monitoring loop, this fn (ultimately) checks with Docker whether the pod is running. It will only return false if the task is still registered and the pod is registered in Docker. Otherwise it returns true. If there's still a task record on file, but no pod in Docker, then we'll also send a TASK_LOST event.
|
func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {
// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)
k.lock.Lock()
defer k.lock.Unlock()
// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the
// kubelet may constantly attempt to instantiate a pod as long as it's in the pod state that we're
// handing to it. otherwise, we're probably reporting a TASK_LOST prematurely. Should probably
// consult RestartPolicy to determine appropriate behavior. Should probably also gracefully handle
// docker daemon restarts.
if _, ok := k.tasks[taskId]; ok {
if isKnownPod() {
return false
} else {
log.Warningf("Detected lost pod, reporting lost task %v", taskId)
k.reportLostTask(driver, taskId, messages.ContainersDisappeared)
}
} else {
log.V(2).Infof("Task %v no longer registered, stop monitoring for lost pods", taskId)
}
return true
}
|
[
"func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the kubelet\n\t// may constantly attempt to instantiate a pod as long as it's in the pod state that we're handing to it.\n\t// otherwise, we're probably reporting a TASK_LOST prematurely. Should probably consult RestartPolicy to\n\t// determine appropriate behavior. Should probably also gracefully handle docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}",
"func IsTaskRunning() bool {\n\treturn persist.HasValue(taskPayloadKey)\n}",
"func onRunIsResolved(target *api.Container, run *api.Container) bool {\n\tif target.DesiredStatus >= api.ContainerCreated {\n\t\treturn run.KnownStatus >= api.ContainerRunning\n\t}\n\treturn false\n}",
"func isRunning(on_node, operation, rcCode string) bool {\n\treturn on_node != \"\" && (operation == \"start\" || (operation == \"monitor\" && rcCode == \"0\"))\n}",
"func (t ResolvedPipelineRunTask) IsRunning() bool {\n\tif t.IsCustomTask() {\n\t\tif t.Run == nil {\n\t\t\treturn false\n\t\t}\n\t} else {\n\t\tif t.TaskRun == nil {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn !t.IsSuccessful() && !t.IsFailure() && !t.IsCancelled()\n}",
"func (task *Task) Running() bool {\n\ttask.lock.Lock()\n\trunning := task.running\n\ttask.lock.Unlock()\n\treturn running\n}",
"func (t *task) IsRunning() bool {\n\treturn t.running\n}",
"func isPodRunningAndReady(pod *v1.Pod) bool {\n\treturn pod.Status.Phase == v1.PodRunning && podutil.IsPodReady(pod) && pod.Status.PodIP != \"\"\n}",
"func isPodRunning(pod *v1.Pod) bool {\n\tif pod.Status.Phase == v1.PodRunning {\n\t\t// If all conditions exists in ConditionTrue then service is guaranteed to be good.\n\t\tfor _, condition := range pod.Status.Conditions {\n\t\t\t// BEGIN WORKAROUND\n\t\t\t// Ignore condition Ready == false (i.e. consider the pod good assuming all other conditions are True)\n\t\t\t// Pods with readiness probes need special handling for resolution, see venice/cmd/services/resolver.go\n\t\t\tif condition.Type == v1.PodReady {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// END WORKAROUND\n\t\t\tif condition.Status != v1.ConditionTrue {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t\treturn true\n\t}\n\treturn false\n}",
"func (m *Machine) IsRunningSwarmingTask() bool {\n\tm.mutex.Lock()\n\tdefer m.mutex.Unlock()\n\treturn m.runningTask\n}",
"func (d *dispatcher) monitorTask(taskID int64) (finished bool, subTaskErrs []error) {\n\t// TODO: Consider putting the following operations into a transaction.\n\tvar err error\n\td.task, err = d.taskMgr.GetGlobalTaskByID(taskID)\n\tif err != nil {\n\t\tlogutil.BgLogger().Error(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\treturn false, nil\n\t}\n\tswitch d.task.State {\n\tcase proto.TaskStateCancelling:\n\t\treturn false, []error{errors.New(\"cancel\")}\n\tcase proto.TaskStateReverting:\n\t\tcnt, err := d.taskMgr.GetSubtaskInStatesCnt(d.task.ID, proto.TaskStateRevertPending, proto.TaskStateReverting)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn cnt == 0, nil\n\tdefault:\n\t\tsubTaskErrs, err = d.taskMgr.CollectSubTaskError(d.task.ID)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"collect subtask error failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\tif len(subTaskErrs) > 0 {\n\t\t\treturn false, subTaskErrs\n\t\t}\n\t\t// check subtasks pending or running.\n\t\tcnt, err := d.taskMgr.GetSubtaskInStatesCnt(d.task.ID, proto.TaskStatePending, proto.TaskStateRunning)\n\t\tif err != nil {\n\t\t\tlogutil.BgLogger().Warn(\"check task failed\", zap.Int64(\"task ID\", d.task.ID), zap.Error(err))\n\t\t\treturn false, nil\n\t\t}\n\t\treturn cnt == 0, nil\n\t}\n}",
"func (folderWatcher *FolderWatcher) IsRunning() bool {\n\treturn folderWatcher.running\n}",
"func podRunningReady(p *corev1.Pod) (bool, error) {\n\t// Check the phase is running.\n\tif p.Status.Phase != corev1.PodRunning {\n\t\treturn false, fmt.Errorf(\"want pod '%s' on '%s' to be '%v' but was '%v'\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, corev1.PodRunning, p.Status.Phase)\n\t}\n\t// Check the ready condition is true.\n\tif !isPodReady(&p.Status) {\n\t\treturn false, fmt.Errorf(\"pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, corev1.PodReady, corev1.ConditionTrue, p.Status.Conditions)\n\t}\n\treturn true, nil\n}",
"func podRunningReady(p *v1.Pod) (bool, error) {\n\t// Check the phase is running.\n\tif p.Status.Phase != v1.PodRunning {\n\t\treturn false, fmt.Errorf(\"want pod '%s' on '%s' to be '%v' but was '%v'\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodRunning, p.Status.Phase)\n\t}\n\t// Check the ready condition is true.\n\n\tif !isPodReady(p) {\n\t\treturn false, fmt.Errorf(\"pod '%s' on '%s' didn't have condition {%v %v}; conditions: %v\",\n\t\t\tp.ObjectMeta.Name, p.Spec.NodeName, v1.PodReady, v1.ConditionTrue, p.Status.Conditions)\n\t}\n\treturn true, nil\n}",
"func (n *Node) IsRunning() bool {\n\treturn n.host != nil\n}",
"func (p *statusUpdate) isOrphanTaskEvent(\n\tctx context.Context,\n\tevent *statusupdate.Event,\n) (bool, *pb_task.TaskInfo, error) {\n\ttaskInfo, err := p.taskStore.GetTaskByID(ctx, event.TaskID())\n\tif err != nil {\n\t\tif yarpcerrors.IsNotFound(err) {\n\t\t\t// if task runtime or config is not present in the DB,\n\t\t\t// then the task is orphan\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"mesos_task_id\": event.MesosTaskStatus(),\n\t\t\t\t\"task_status_event≠\": event.State().String(),\n\t\t\t}).Info(\"received status update for task not found in DB\")\n\t\t\treturn true, nil, nil\n\t\t}\n\n\t\tlog.WithError(err).\n\t\t\tWithField(\"task_id\", event.TaskID()).\n\t\t\tWithField(\"task_status_event\", event.MesosTaskStatus()).\n\t\t\tWithField(\"state\", event.State().String()).\n\t\t\tError(\"fail to find taskInfo for taskID for mesos event\")\n\t\treturn false, nil, err\n\t}\n\n\t// TODO p2k: verify v1 pod id in taskInfo\n\tif event.V0() != nil {\n\t\tdbTaskID := taskInfo.GetRuntime().GetMesosTaskId().GetValue()\n\t\tif dbTaskID != event.MesosTaskStatus().GetTaskId().GetValue() {\n\t\t\tlog.WithFields(log.Fields{\n\t\t\t\t\"orphan_task_id\": event.MesosTaskStatus().GetTaskId().GetValue(),\n\t\t\t\t\"db_task_id\": dbTaskID,\n\t\t\t\t\"db_task_runtime_state\": taskInfo.GetRuntime().GetState().String(),\n\t\t\t\t\"mesos_event_state\": event.State().String(),\n\t\t\t}).Info(\"received status update for orphan mesos task\")\n\t\t\treturn true, nil, nil\n\t\t}\n\t}\n\n\treturn false, taskInfo, nil\n}",
"func (b *binaryNode) IsRunning() (bool, error) {\n\t//add a blank space at the end to avoid common prefix\n\tcommand := fmt.Sprintf(\"pgrep -f '^%s '| wc -l\", b.name)\n\tres := b.ssh.execCmdWithResult(command)\n\tr := strings.TrimSpace(string(res))\n\tcount, err := strconv.Atoi(r)\n\tif err != nil {\n\t\treturn false, errors.Trace(err)\n\t}\n\tif count == 1 {\n\t\treturn true, nil\n\t}\n\tif count > 1 {\n\t\treturn false, errors.Errorf(\"Services have common prefix with the name\")\n\t}\n\treturn false, nil\n}",
"func (p *TaskRunner) isRunning() bool {\n\treturn atomic.LoadUint32(&p.state) == startedState\n}",
"func IsWatchRunning() error {\n\t// This is connecting locally and it is very unlikely watch is overloaded,\n\t// set the timeout *super* short to make it easier on the users when they\n\t// forgot to start watch.\n\twithTimeout, _ := context.WithTimeout(context.TODO(), 100*time.Millisecond)\n\n\tconn, err := grpc.DialContext(\n\t\twithTimeout,\n\t\tfmt.Sprintf(\"127.0.0.1:%d\", viper.GetInt(\"port\")),\n\t\t[]grpc.DialOption{\n\t\t\tgrpc.WithBlock(),\n\t\t\tgrpc.WithInsecure(),\n\t\t}...)\n\n\tif err != nil {\n\t\t// The assumption is that the only real error here is because watch isn't\n\t\t// running\n\t\tlog.Debug(err)\n\t\treturn errWatchNotRunning\n\t}\n\n\tclient := pb.NewKsyncClient(conn)\n\talive, err := client.IsAlive(context.Background(), &empty.Empty{})\n\tif err != nil {\n\t\tlog.Debug(err)\n\t\treturn errWatchNotResponding\n\t}\n\n\tif !alive.Alive {\n\t\treturn errSyncthingNotRunning\n\t}\n\n\tif err := conn.Close(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
KillTask is called when the executor receives a request to kill a task.
|
func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {
if k.isDone() {
return
}
log.Infof("Kill task %v\n", taskId)
if !k.isConnected() {
//TODO(jdefelice) sent TASK_LOST here?
log.Warningf("Ignore kill task because the executor is disconnected\n")
return
}
k.lock.Lock()
defer k.lock.Unlock()
k.removePodTask(driver, taskId.GetValue(), messages.TaskKilled, mesos.TaskState_TASK_KILLED)
}
|
[
"func (e *Executor) KillTask(executor.ExecutorDriver, *mesosproto.TaskID) {\n\te.Called()\n}",
"func (k *KubernetesExecutor) KillTask(driver bindings.ExecutorDriver, taskId *mesos.TaskID) {\n\tif k.isDone() {\n\t\treturn\n\t}\n\tlog.Infof(\"Kill task %v\\n\", taskId)\n\n\tif !k.isConnected() {\n\t\t//TODO(jdefelice) sent TASK_LOST here?\n\t\tlog.Warningf(\"Ignore kill task because the executor is disconnected\\n\")\n\t\treturn\n\t}\n\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\tk.killPodForTask(driver, taskId.GetValue(), messages.TaskKilled)\n}",
"func (s *service) KillTask(request *KillTaskRequest) *KillTaskResponse {\n\tvar response = &KillTaskResponse{BaseResponse: &BaseResponse{StartTime: time.Now()}}\n\tfor _, candidate := range s.tasks {\n\t\tif request.ID == candidate.ID {\n\t\t\tresponse.Task = candidate\n\t\t\tatomic.StoreInt32(&candidate.StatusCode, StatusTaskNotRunning)\n\t\t\tbreak\n\t\t}\n\t}\n\treturn response\n}",
"func (builder *ImageBuilder) KillTask(executor.ExecutorDriver, *mesosproto.TaskID) {\n\tfmt.Println(\"Kill task\")\n}",
"func (f *Failer) KillTask(host, task string) error {\n\tscript := \"sudo pkill -x %s\"\n\tlog.V(1).Infof(\"Killing task %s on host %s\", task, host)\n\treturn f.runWithEvilTag(host, fmt.Sprintf(script, task))\n}",
"func KillTask(tid int) Errno {\n\t_, e := internal.Syscall1(KILLTASK, uintptr(tid))\n\treturn Errno(e)\n}",
"func (tr *TaskRunner) Kill(ctx context.Context, event *structs.TaskEvent) error {\n\ttr.logger.Trace(\"Kill requested\")\n\n\t// Cancel the task runner to break out of restart delay or the main run\n\t// loop.\n\ttr.killCtxCancel()\n\n\t// Emit kill event\n\tif event != nil {\n\t\ttr.logger.Trace(\"Kill event\", \"event_type\", event.Type, \"event_reason\", event.KillReason)\n\t\ttr.EmitEvent(event)\n\t}\n\n\tselect {\n\tcase <-tr.WaitCh():\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\t}\n\n\treturn tr.getKillErr()\n}",
"func HandleStopTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleStopTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStopTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleStopTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\ttaskCapacity, err := node.StopTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleStopTask Stop task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleStopTask END\")\n\tHttpResponseData(w, H{\n\t\t\"taskCapacity\": taskCapacity,\n\t})\n\treturn\n}",
"func (t *TimeTask) DeleteTask(task *RawTask) {\n\tt.deleteChan <- task\n}",
"func (s *BaseNuggetListener) ExitTask(ctx *TaskContext) {}",
"func (d *Driver) StopTask(taskID string, timeout time.Duration, signal string) error {\n\td.logger.Debug(\"StopTask called\")\n\th, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\t// implement driver specific logic to stop a task.\n\t//\n\t// The StopTask function is expected to stop a running task by sending the\n\t// given signal to it. If the task does not stop during the given timeout,\n\t// the driver must forcefully kill the task.\n\td.logger.Debug(\"StopTask returning\")\n\treturn h.KillVM()\n}",
"func (c Control) ServeStopTask(w http.ResponseWriter, r *http.Request) {\n\tc.ServeTaskAction(w, r, false)\n}",
"func (d *Driver) StopTask(taskID string, timeout time.Duration, signal string) error {\n\td.logger.Info(\"Stopping task\", \"taskID\", taskID, \"signal\", signal)\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\t// fixme send proper signal to container\n\terr := d.podman.ContainerStop(d.ctx, handle.containerID, int(timeout.Seconds()))\n\tif err != nil {\n\t\td.logger.Error(\"Could not stop/kill container\", \"containerID\", handle.containerID, \"err\", err)\n\t\treturn err\n\t}\n\treturn nil\n}",
"func HandleDeleteTask(w http.ResponseWriter, r *http.Request) {\n\tlog.Root.Info(\"HandleDeleteTask BEGIN\")\n\n\tif r.Method != http.MethodPost {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\tHttpResponseError(w, ErrNotFound)\n\t\treturn\n\t}\n\n\tdefer r.Body.Close()\n\tbody, _ := ioutil.ReadAll(r.Body)\n\n\tdata := make(map[string]interface{})\n\terr := json.Unmarshal(body, &data)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleDeleteTask Parse HTTP request body error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\telem, ok := data[\"taskID\"]\n\tif !ok {\n\t\tlog.Root.Error(\"HandleDeleteTask HTTP form data error\")\n\t\tHttpResponseError(w, ErrForm)\n\t\treturn\n\t}\n\n\ttaskID := elem.(string)\n\terr = node.DeleteTask(taskID)\n\tif err != nil {\n\t\tlog.Root.Error(\"HandleDeleteTask Delete task error. TaskID: %v\", taskID)\n\t\tHttpResponseError(w, ErrServer)\n\t\treturn\n\t}\n\n\tlog.Root.Info(\"HandleDeleteTask END\")\n\tHttpResponseOk(w)\n\treturn\n}",
"func (m TaskManager) AbortTask(c context.Context, ctl task.Controller) error {\n\treturn nil\n}",
"func (s *Scheduler) KillExecutor(agentID, executerID string) (*http.Response, error) {\n\tblog.Info(\"kill taskgroup on AgentID(%s), ExecutorID(%s)\", agentID, executerID)\n\tcall := &sched.Call{\n\t\tFrameworkId: s.framework.GetId(),\n\t\tType: sched.Call_SHUTDOWN.Enum(),\n\t\tShutdown: &sched.Call_Shutdown{\n\t\t\tExecutorId: &mesos.ExecutorID{\n\t\t\t\tValue: &executerID,\n\t\t\t},\n\t\t\tAgentId: &mesos.AgentID{\n\t\t\t\tValue: &agentID,\n\t\t\t},\n\t\t},\n\t}\n\n\treturn s.send(call)\n}",
"func (c *DockerScheduler) stopTask(task *demand.Task) error {\n\tvar err error\n\n\t// Kill a currently-running container of this type\n\tc.Lock()\n\ttheseContainers := c.taskContainers[task.Name]\n\tvar containerToKill string\n\tfor id, v := range theseContainers {\n\t\tif v.state == \"running\" {\n\t\t\tcontainerToKill = id\n\t\t\tv.state = \"stopping\"\n\t\t\tbreak\n\t\t}\n\t}\n\tc.Unlock()\n\n\tif containerToKill == \"\" {\n\t\treturn fmt.Errorf(\"[stop] No containers of type %s to kill\", task.Name)\n\t}\n\n\tremoveOpts := docker.RemoveContainerOptions{\n\t\tID: containerToKill,\n\t\tRemoveVolumes: true,\n\t}\n\n\tgo func() {\n\t\tscaling.Add(1)\n\t\tdefer scaling.Done()\n\n\t\tlog.Debugf(\"[stopping] container for task %s with ID %s\", task.Name, containerToKill)\n\t\terr = c.client.StopContainer(containerToKill, 1)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Couldn't stop container %s: %v\", containerToKill, err)\n\t\t\treturn\n\t\t}\n\n\t\tc.Lock()\n\t\tc.taskContainers[task.Name][containerToKill].state = \"removing\"\n\t\tc.Unlock()\n\n\t\tlog.Debugf(\"[removing] container for task %s with ID %s\", task.Name, containerToKill)\n\t\terr = c.client.RemoveContainer(removeOpts)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Couldn't remove container %s: %v\", containerToKill, err)\n\t\t\treturn\n\t\t}\n\t}()\n\n\treturn nil\n}",
"func (c *Consumer) stopTask(taskID string) {\n\tc.runL.Lock()\n\ttask, ok := c.running[taskID]\n\tc.runL.Unlock()\n\n\tif !ok {\n\t\t// This can happen if a task completes during Balance() and is not an error.\n\t\tWarnf(\"%s tried to release a non-running task=%q\", c, taskID)\n\t\treturn\n\t}\n\n\t// all handler methods must be wrapped in a recover to prevent a misbehaving\n\t// handler from crashing the entire consumer\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif err := recover(); err != nil {\n\t\t\t\tstack := make([]byte, 50*1024)\n\t\t\t\tsz := runtime.Stack(stack, false)\n\t\t\t\tErrorf(\"%s Handler %s panic()'d on Stop: %v\\n%s\", c, taskID, err, stack[:sz])\n\t\t\t}\n\t\t}()\n\n\t\t// Serialize calls to Stop as a convenience to handler implementors.\n\t\ttask.stop()\n\t}()\n}",
"func (d *Driver) SignalTask(taskID string, signal string) error {\n\thandle, ok := d.tasks.Get(taskID)\n\tif !ok {\n\t\treturn drivers.ErrTaskNotFound\n\t}\n\n\treturn d.podman.ContainerKill(d.ctx, handle.containerID, signal)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Reports a lost task to the slave and updates internal task and pod tracking state. Assumes that the caller is locking around pod and task state.
|
func (k *KubernetesExecutor) reportLostTask(driver bindings.ExecutorDriver, tid, reason string) {
k.removePodTask(driver, tid, reason, mesos.TaskState_TASK_LOST)
}
|
[
"func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the kubelet\n\t// may constantly attempt to instantiate a pod as long as it's in the pod state that we're handing to it.\n\t// otherwise, we're probably reporting a TASK_LOST prematurely. Should probably consult RestartPolicy to\n\t// determine appropriate behavior. Should probably also gracefully handle docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}",
"func (k *KubernetesExecutor) checkForLostPodTask(driver bindings.ExecutorDriver, taskId string, isKnownPod func() bool) bool {\n\t// TODO (jdefelice) don't send false alarms for deleted pods (KILLED tasks)\n\tk.lock.Lock()\n\tdefer k.lock.Unlock()\n\n\t// TODO(jdef) we should really consider k.pods here, along with what docker is reporting, since the\n\t// kubelet may constantly attempt to instantiate a pod as long as it's in the pod state that we're\n\t// handing to it. otherwise, we're probably reporting a TASK_LOST prematurely. Should probably\n\t// consult RestartPolicy to determine appropriate behavior. Should probably also gracefully handle\n\t// docker daemon restarts.\n\tif _, ok := k.tasks[taskId]; ok {\n\t\tif isKnownPod() {\n\t\t\treturn false\n\t\t} else {\n\t\t\tlog.Warningf(\"Detected lost pod, reporting lost task %v\", taskId)\n\t\t\tk.reportLostTask(driver, taskId, messages.ContainersDisappeared)\n\t\t}\n\t} else {\n\t\tlog.V(2).Infof(\"Task %v no longer registered, stop monitoring for lost pods\", taskId)\n\t}\n\treturn true\n}",
"func (suite *TaskFailRetryTestSuite) TestLostTaskNoRetry() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 0,\n\t\t},\n\t}\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.lostTaskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}",
"func (suite *TaskFailRetryTestSuite) TestLostTaskRetry() {\n\ttaskConfig := pbtask.TaskConfig{\n\t\tRestartPolicy: &pbtask.RestartPolicy{\n\t\t\tMaxFailures: 3,\n\t\t},\n\t}\n\n\tsuite.cachedTask.EXPECT().\n\t\tID().\n\t\tReturn(uint32(0)).\n\t\tAnyTimes()\n\n\tsuite.jobFactory.EXPECT().\n\t\tGetJob(suite.jobID).Return(suite.cachedJob)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetTask(suite.instanceID).Return(suite.cachedTask)\n\n\tsuite.cachedJob.EXPECT().\n\t\tID().Return(suite.jobID)\n\n\tsuite.cachedTask.EXPECT().\n\t\tGetRuntime(gomock.Any()).Return(suite.lostTaskRuntime, nil)\n\n\tsuite.taskConfigV2Ops.EXPECT().\n\t\tGetTaskConfig(gomock.Any(), suite.jobID, suite.instanceID, gomock.Any()).\n\t\tReturn(&taskConfig, &models.ConfigAddOn{}, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tPatchTasks(gomock.Any(), gomock.Any(), false).\n\t\tDo(func(ctx context.Context,\n\t\t\truntimeDiffs map[uint32]jobmgrcommon.RuntimeDiff,\n\t\t\t_ bool) {\n\t\t\truntimeDiff := runtimeDiffs[suite.instanceID]\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.MesosTaskIDField].(*mesosv1.TaskID).GetValue() != suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.PrevMesosTaskIDField].(*mesosv1.TaskID).GetValue() == suite.mesosTaskID)\n\t\t\tsuite.True(\n\t\t\t\truntimeDiff[jobmgrcommon.StateField].(pbtask.TaskState) == pbtask.TaskState_INITIALIZED)\n\t\t}).Return(nil, nil, nil)\n\n\tsuite.cachedJob.EXPECT().\n\t\tGetJobType().Return(pbjob.JobType_BATCH)\n\n\tsuite.taskGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\tsuite.jobGoalStateEngine.EXPECT().\n\t\tEnqueue(gomock.Any(), gomock.Any()).\n\t\tReturn()\n\n\terr := TaskFailRetry(context.Background(), suite.taskEnt)\n\tsuite.NoError(err)\n}",
"func (k *KubernetesScheduler) SlaveLost(driver mesos.SchedulerDriver, slaveId *mesos.SlaveID) {\n\tlog.Infof(\"Slave %v is lost\\n\", slaveId)\n\t// TODO(yifan): Restart any unfinished tasks on that slave.\n}",
"func resetSystemFailedTask(ctx context.Context, settings *evergreen.Settings, t *task.Task, description string) error {\n\tif t.IsFinished() {\n\t\treturn nil\n\t}\n\n\tunschedulableTask := time.Since(t.ActivatedTime) > task.UnschedulableThreshold\n\tmaxExecutionTask := t.Execution >= evergreen.MaxTaskExecution\n\n\tif evergreen.IsCommitQueueRequester(t.Requester) && evergreen.IsSystemFailedTaskStatus(t.Status) {\n\t\tmaxSystemFailedTaskRetries := settings.CommitQueue.MaxSystemFailedTaskRetries\n\t\tif maxSystemFailedTaskRetries > 0 {\n\t\t\tmaxExecutionTask = t.Execution >= maxSystemFailedTaskRetries\n\t\t}\n\t}\n\n\tif unschedulableTask || maxExecutionTask {\n\t\tfailureDetails := task.GetSystemFailureDetails(description)\n\t\t// If the task has already exceeded the unschedulable threshold, we\n\t\t// don't want to restart it, so just mark it as finished.\n\t\tif t.DisplayOnly {\n\t\t\texecTasks, err := task.FindAll(db.Query(task.ByIds(t.ExecutionTasks)))\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"finding execution tasks\")\n\t\t\t}\n\t\t\tfor _, execTask := range execTasks {\n\t\t\t\tif !evergreen.IsFinishedTaskStatus(execTask.Status) {\n\t\t\t\t\tif err = MarkEnd(ctx, settings, &execTask, evergreen.MonitorPackage, time.Now(), &failureDetails, false); err != nil {\n\t\t\t\t\t\treturn errors.Wrap(err, \"marking execution task as ended\")\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn errors.WithStack(MarkEnd(ctx, settings, t, evergreen.MonitorPackage, time.Now(), &failureDetails, false))\n\t}\n\n\tif err := t.MarkSystemFailed(description); err != nil {\n\t\treturn errors.Wrap(err, \"marking task as system failed\")\n\t}\n\tif err := logTaskEndStats(ctx, t); err != nil {\n\t\treturn errors.Wrap(err, \"logging task end stats\")\n\t}\n\n\treturn errors.Wrap(ResetTaskOrDisplayTask(ctx, settings, t, evergreen.User, evergreen.MonitorPackage, true, &t.Details), \"resetting task\")\n}",
"func (t *Task) fail() {\n\tif t.Retry >= t.tasker.Retry() && t.tasker.Retry() != -1 {\n\t\tt.Failed = time.Now()\n\t\tt.Closed = true\n\t} else {\n\t\tt.Retry++\n\t}\n\n\tt.Owner = data.EmptyKey //throw it back in the queue for processing by any available task runner\n\n\terr := data.TaskUpdate(t, t.Key)\n\tif err != nil {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"taskKey\": t.Key,\n\t\t\t\"type\": t.Type,\n\t\t}).Errorf(\"An error occured when updating a task for failure: %s\", err)\n\t}\n}",
"func (ctx *coordinatorContext) Lost(taskID string) {\n\tErrorf(\"Lost task %s\", taskID)\n\tctx.stopTask(taskID)\n}",
"func (m *TaskManager) ResetOverdueTask() {\n\tm.WIPTable.Range(func(key, value interface{}) bool {\n\t\tif t := value.(*Task); t.IsTimeout() {\n\t\t\tif t.LifeCycle != WIP {\n\t\t\t\tlog.Logger.Fatalf(\"the LifeCycle of the task under check is %d, but `WIP` is expected\", t.LifeCycle)\n\t\t\t}\n\t\t\tt.LifeCycle = READY\n\t\t\tm.ReadyQueue <- t\n\t\t\tm.WIPTable.Delete(key)\n\t\t\tlog.Logger.WithFields(logrus.Fields{\n\t\t\t\t\"ID\": t.ID,\n\t\t\t\t\"TaskType\": t.TaskType,\n\t\t\t}).Warn(\"reset an overdue task\")\n\t\t\treturn false\n\t\t}\n\t\treturn true\n\t})\n}",
"func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode task state from handle: %v\", err)\n\t}\n\td.logger.Debug(\"Checking for recoverable task\", \"task\", handle.Config.Name, \"taskid\", handle.Config.ID, \"container\", taskState.ContainerID)\n\n\tinspectData, err := d.podman.ContainerInspect(d.ctx, taskState.ContainerID)\n\tif err != nil {\n\t\td.logger.Warn(\"Recovery lookup failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\treturn nil\n\t}\n\n\th := &TaskHandle{\n\t\tcontainerID: taskState.ContainerID,\n\t\tdriver: d,\n\t\ttaskConfig: taskState.TaskConfig,\n\t\tprocState: drivers.TaskStateUnknown,\n\t\tstartedAt: taskState.StartedAt,\n\t\texitResult: &drivers.ExitResult{},\n\t\tlogger: d.logger.Named(\"podmanHandle\"),\n\n\t\ttotalCPUStats: stats.NewCpuStats(),\n\t\tuserCPUStats: stats.NewCpuStats(),\n\t\tsystemCPUStats: stats.NewCpuStats(),\n\n\t\tremoveContainerOnExit: d.config.GC.Container,\n\t}\n\n\tif inspectData.State.Running {\n\t\td.logger.Info(\"Recovered a still running container\", \"container\", inspectData.State.Pid)\n\t\th.procState = drivers.TaskStateRunning\n\t} else if inspectData.State.Status == \"exited\" {\n\t\t// are we allowed to restart a stopped container?\n\t\tif d.config.RecoverStopped {\n\t\t\td.logger.Debug(\"Found a stopped container, try to start it\", \"container\", inspectData.State.Pid)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery restart failed\", \"task\", handle.Config.ID, \"container\", taskState.ContainerID, \"err\", err)\n\t\t\t} else {\n\t\t\t\td.logger.Info(\"Restarted a container during recovery\", \"container\", inspectData.ID)\n\t\t\t\th.procState = drivers.TaskStateRunning\n\t\t\t}\n\t\t} else {\n\t\t\t// no, let's cleanup here to prepare for a StartTask()\n\t\t\td.logger.Debug(\"Found a stopped container, removing it\", \"container\", inspectData.ID)\n\t\t\tif err = d.podman.ContainerStart(d.ctx, inspectData.ID); err != nil {\n\t\t\t\td.logger.Warn(\"Recovery cleanup failed\", \"task\", handle.Config.ID, \"container\", inspectData.ID)\n\t\t\t}\n\t\t\th.procState = drivers.TaskStateExited\n\t\t}\n\t} else {\n\t\td.logger.Warn(\"Recovery restart failed, unknown container state\", \"state\", inspectData.State.Status, \"container\", taskState.ContainerID)\n\t\th.procState = drivers.TaskStateUnknown\n\t}\n\n\td.tasks.Set(taskState.TaskConfig.ID, h)\n\n\tgo h.runContainerMonitor()\n\td.logger.Debug(\"Recovered container handle\", \"container\", taskState.ContainerID)\n\n\treturn nil\n}",
"func (mgr *DataCheckMgr) checkTaskgroupWhetherLost(taskGroups []*types.TaskGroup, reschedule bool) int {\n\tnow := time.Now().Unix()\n\tlostnum := 0\n\tfor _, taskGroup := range taskGroups {\n\t\tif taskGroup.LastUpdateTime == 0 ||\n\t\t\t(taskGroup.Status != types.TASKGROUP_STATUS_RUNNING &&\n\t\t\t\ttaskGroup.Status != types.TASKGROUP_STATUS_STAGING &&\n\t\t\t\ttaskGroup.Status != types.TASKGROUP_STATUS_STARTING) {\n\t\t\tcontinue\n\t\t}\n\n\t\tvar updateInterval int64\n\n\t\tswitch taskGroup.Status {\n\t\tcase types.TASKGROUP_STATUS_RUNNING, types.TASKGROUP_STATUS_STARTING:\n\t\t\tupdateInterval = 4 * MAX_DATA_UPDATE_INTERVAL\n\t\t\t/*case types.TASKGROUP_STATUS_STAGING:\n\t\t\tupdateInterval = 4 * MAX_STAGING_UPDATE_INTERVAL*/\n\t\t}\n\n\t\tif taskGroup.LastUpdateTime+updateInterval < now {\n\t\t\tfor _, task := range taskGroup.Taskgroup {\n\t\t\t\tif task.Status != types.TASK_STATUS_RUNNING && task.Status != types.TASK_STATUS_STAGING && task.Status != types.TASK_STATUS_STARTING {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tif task.LastUpdateTime+updateInterval < now {\n\t\t\t\t\tblog.Warn(\"data checker: task(%s) lost for long time not report status under status(%s)\",\n\t\t\t\t\t\ttask.ID, task.Status)\n\t\t\t\t\ttask.LastStatus = task.Status\n\t\t\t\t\ttask.Status = types.TASK_STATUS_LOST\n\t\t\t\t\ttask.LastUpdateTime = now\n\t\t\t\t\tmgr.sched.SendHealthMsg(alarm.WarnKind, taskGroup.RunAs, task.ID+\"(\"+taskGroup.HostName+\")\"+\"long time not report status, set status to lost\", \"\", nil)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlostnum++\n\t\t\tblog.Warn(\"data checker: taskgroup(%s) lost for long time not report status under status(%s)\",\n\t\t\t\ttaskGroup.ID, taskGroup.Status)\n\t\t\ttaskGroupStatus := taskGroup.Status\n\t\t\ttaskGroup.LastStatus = taskGroup.Status\n\t\t\ttaskGroup.Status = types.TASKGROUP_STATUS_LOST\n\t\t\ttaskGroup.LastUpdateTime = now\n\t\t\t//if reschedule==true, then trigger reschedule function\n\t\t\tif reschedule {\n\t\t\t\tmgr.sched.taskGroupStatusUpdated(taskGroup, taskGroupStatus)\n\t\t\t\tmgr.sched.ServiceMgr.TaskgroupUpdate(taskGroup)\n\t\t\t}\n\t\t\tif err := mgr.sched.store.SaveTaskGroup(taskGroup); err != nil {\n\t\t\t\tblog.Errorf(\"data checker: save taskgroup(%s) into db failed! err:%s\", taskGroup.ID, err.Error())\n\t\t\t\treturn 0\n\t\t\t}\n\t\t}\n\t}\n\n\treturn lostnum\n}",
"func TestPersistentTaskLoss(t *testing.T) {\n\tvar (\n\t\ttest simpleEvalTest\n\t\tctx, cancel = context.WithTimeout(context.Background(), 10*time.Second)\n\t)\n\tdefer cancel()\n\ttest.Go(t)\n\tfst := test.ConstTask\n\tfor {\n\t\tif err := ctx.Err(); err != nil {\n\t\t\tt.Fatal(err)\n\t\t}\n\t\tfst.Lock()\n\t\tfor fst.state != TaskRunning {\n\t\t\tif err := fst.Wait(ctx); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t\tfst.state = TaskLost\n\t\tfst.Broadcast()\n\t\tfor fst.state == TaskLost {\n\t\t\tif err := fst.Wait(ctx); err != nil {\n\t\t\t\tt.Fatal(err)\n\t\t\t}\n\t\t}\n\t\tisErr := fst.state == TaskErr\n\t\tfst.Unlock()\n\t\tif isErr {\n\t\t\t// The evaluator has given up on the task.\n\t\t\tbreak\n\t\t}\n\t}\n\terr := test.EvalErr()\n\tif !errors.Is(errors.TooManyTries, err) {\n\t\tt.Errorf(\"expected TooManyTries error, got: %v\", err)\n\t}\n}",
"func (d *Driver) RecoverTask(handle *drivers.TaskHandle) error {\n\tif handle == nil {\n\t\treturn fmt.Errorf(\"error: handle cannot be nil in RecoverTask\")\n\t}\n\n\tif _, ok := d.tasks.Get(handle.Config.ID); ok {\n\t\t// nothing to do if handle found in task store\n\t\treturn nil\n\t}\n\n\tvar taskState TaskState\n\tif err := handle.GetDriverState(&taskState); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode driver task state: %v\", err)\n\t}\n\n\tvar driverConfig api.TaskConfig\n\tif err := taskState.TaskConfig.DecodeDriverConfig(&driverConfig); err != nil {\n\t\treturn fmt.Errorf(\"failed to decode driver config: %v\", err)\n\t}\n\n\t// create new handle from restored state from state db\n\t// libvirt doesn't track the creation/completion time of domains\n\t// so I'm tracking those myself\n\th := &taskHandle{\n\t\tdomainManager: d.domainManager,\n\t\tresultChan: make(chan *drivers.ExitResult),\n\t\ttask: handle.Config,\n\t\tstartedAt: taskState.startedAt,\n\t\tcompletedAt: taskState.completedAt,\n\t\texitResult: taskState.exitResult,\n\t}\n\n\t// set the in memory handle in task store\n\td.tasks.Set(handle.Config.ID, h)\n\n\treturn nil\n}",
"func FixStaleTask(ctx context.Context, settings *evergreen.Settings, t *task.Task) error {\n\terr := UpdateBlockedDependencies(t)\n\tif err != nil {\n\t\treturn errors.Wrapf(err, \"updating blocked dependencies for task '%s'\", t.Id)\n\t}\n\n\tfailureDesc := evergreen.TaskDescriptionHeartbeat\n\tif t.Aborted {\n\t\tfailureDesc = evergreen.TaskDescriptionAborted\n\t\tif err := finishStaleAbortedTask(ctx, settings, t); err != nil {\n\t\t\treturn errors.Wrapf(err, \"finishing stale aborted task '%s'\", t.Id)\n\t\t}\n\t} else {\n\t\tif err := resetSystemFailedTask(ctx, settings, t, failureDesc); err != nil {\n\t\t\treturn errors.Wrap(err, \"resetting heartbeat task\")\n\t\t}\n\t}\n\n\tgrip.Info(message.Fields{\n\t\t\"message\": \"successfully fixed stale task\",\n\t\t\"task\": t.Id,\n\t\t\"execution\": t.Execution,\n\t\t\"execution_platform\": t.ExecutionPlatform,\n\t\t\"description\": failureDesc,\n\t})\n\n\treturn nil\n}",
"func (rn *RawNode) ReportUnreachable(id uint64) {\n\t_ = rn.raft.Step(pb.Message{Type: pb.MsgUnreachable, From: id})\n}",
"func (m *MeasurementData) lossMeasurementTasks(){\n\tm.hdrData.loss = true\n}",
"func notifyOfDeadNode(node *shared.Node, milestone string) {\n\tLogger.LogLocalEvent(\"Sending DeadNodeNotification for node: \" + node.NodeID)\n\targs := shared.DeadNodeNotification{NodeIP: node.IPport, ZorY: milestone}\n\tliveNodesMutex.RLock()\n\tfor _, node := range liveNodes {\n\t\t// Connect to the Bots RPC service.\n\t\tcbc, err := rpc.Dial(\"tcp\", node.IPport)\n\t\tif err != nil {\n\t\t\tliveNodesMutex.RUnlock()\n\t\t\treturn\n\t\t}\n\t\tvar tids []uint64\n\t\terr = cbc.Call(\"CNCBotCommunication.DeadNodeNotification\", args, &tids) //Query the CNC\n\t\tshared.CheckErrorNonFatal(\"\", err)\n\t\tdbMutex.Lock()\n\t\tdb.Update(func(tx *bolt.Tx) error {\n\t\t\tsb := tx.Bucket([]byte(\"Storage\"))\n\t\t\tnodebytes := sb.Get([]byte(node.IPport))\n\t\t\tvar n shared.Node\n\t\t\tn, err := decodeNode(nodebytes)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcb := tx.Bucket([]byte(\"Completed\"))\n\t\t\tfor _, tid := range tids {\n\t\t\t\ttidstr := strconv.FormatUint(tid, 10)\n\t\t\t\tenctxn := cb.Get([]byte(tidstr))\n\t\t\t\tif enctxn == nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\ttxn, err := shared.DecodeTxn(enctxn)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\n\t\t\t\t}\n\t\t\t\tif milestone == \"Z\" {\n\t\t\t\t\tn.FreeSpace += txn.FileSize\n\t\t\t\t} else {\n\t\t\t\t\tn.UsedSpace -= txn.FileSize\n\n\t\t\t\t}\n\t\t\t}\n\t\t\t// Add available space on the node the node that's receiving the file\n\n\t\t\t// Decrement the amount of storage used by the sender\n\t\t\tnbytes, err := encodeNode(&n)\n\t\t\terr = sb.Put([]byte(node.IPport), nbytes)\n\t\t\treturn err\n\t\t})\n\t\tdbMutex.Unlock()\n\t}\n\tliveNodesMutex.RUnlock()\n}",
"func (c *TowerClient) taskRejected(task *backupTask, curStatus reserveStatus) {\n\tswitch curStatus {\n\n\t// The sessionQueue has available capacity but the task was rejected,\n\t// this indicates that the task was ineligible for backup.\n\tcase reserveAvailable:\n\t\tc.stats.taskIneligible()\n\n\t\tlog.Infof(\"Backup chanid=%s commit-height=%d is ineligible\",\n\t\t\ttask.id.ChanID, task.id.CommitHeight)\n\n\t\terr := c.cfg.DB.MarkBackupIneligible(\n\t\t\ttask.id.ChanID, task.id.CommitHeight,\n\t\t)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Unable to mark task chanid=%s \"+\n\t\t\t\t\"commit-height=%d ineligible: %v\",\n\t\t\t\ttask.id.ChanID, task.id.CommitHeight, err)\n\n\t\t\t// It is safe to not handle this error, even if we could\n\t\t\t// not persist the result. At worst, this task may be\n\t\t\t// reprocessed on a subsequent start up, and will either\n\t\t\t// succeed do a change in session parameters or fail in\n\t\t\t// the same manner.\n\t\t}\n\n\t\t// If this task was rejected *and* the session had available\n\t\t// capacity, we discard anything held in the prevTask. Either it\n\t\t// was nil before, or is the task which was just rejected.\n\t\tc.prevTask = nil\n\n\t// The sessionQueue rejected the task because it is full, we will stash\n\t// this task and try to add it to the next available sessionQueue.\n\tcase reserveExhausted:\n\t\tc.stats.sessionExhausted()\n\n\t\tlog.Debugf(\"Session %s exhausted, backup chanid=%s \"+\n\t\t\t\"commit-height=%d queued for next session\",\n\t\t\tc.sessionQueue.ID(), task.id.ChanID,\n\t\t\ttask.id.CommitHeight)\n\n\t\t// Cache the task that we pulled off, so that we can process it\n\t\t// once a new session queue is available.\n\t\tc.sessionQueue = nil\n\t\tc.prevTask = task\n\t}\n}",
"func (_this *RaftNode) ReportUnreachable(id uint64) {}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
FrameworkMessage is called when the framework sends some message to the executor
|
func (k *KubernetesExecutor) FrameworkMessage(driver bindings.ExecutorDriver, message string) {
if k.isDone() {
return
}
if !k.isConnected() {
log.Warningf("Ignore framework message because the executor is disconnected\n")
return
}
log.Infof("Receives message from framework %v\n", message)
//TODO(jdef) master reported a lost task, reconcile this! @see scheduler.go:handleTaskLost
if strings.HasPrefix(message, messages.TaskLost+":") {
taskId := message[len(messages.TaskLost)+1:]
if taskId != "" {
// clean up pod state
k.lock.Lock()
defer k.lock.Unlock()
k.reportLostTask(driver, taskId, messages.TaskLostAck)
}
}
switch message {
case messages.Kamikaze:
k.attemptSuicide(driver, nil)
}
}
|
[
"func (e *Executor) FrameworkMessage(executor.ExecutorDriver, string) {\n\te.Called()\n}",
"func (k *KubernetesScheduler) FrameworkMessage(driver mesos.SchedulerDriver,\n\texecutorId *mesos.ExecutorID, slaveId *mesos.SlaveID, message string) {\n\tlog.Infof(\"Received messages from executor %v of slave %v, %v\\n\", executorId, slaveId, message)\n}",
"func (builder *ImageBuilder) FrameworkMessage(driver executor.ExecutorDriver, msg string) {\n\tfmt.Println(\"Got framework message: \", msg)\n}",
"func (driver *MesosExecutorDriver) SendFrameworkMessage(data string) (mesosproto.Status, error) {\n\tlog.Infoln(\"Send framework message\")\n\n\tdriver.mutex.Lock()\n\tdefer driver.mutex.Unlock()\n\n\tif driver.status != mesosproto.Status_DRIVER_RUNNING {\n\t\treturn driver.status, nil\n\t}\n\tmessage := &mesosproto.ExecutorToFrameworkMessage{\n\t\tSlaveId: driver.slaveID,\n\t\tFrameworkId: driver.frameworkID,\n\t\tExecutorId: driver.executorID,\n\t\tData: []byte(data),\n\t}\n\t// Send the message.\n\tif err := driver.messenger.Send(driver.slaveUPID, message); err != nil {\n\t\tlog.Errorf(\"Failed to send %v: %v\\n\")\n\t\treturn driver.status, err\n\t}\n\treturn driver.status, nil\n}",
"func registeredCB(\n ptr unsafe.Pointer,\n frameworkMessage *C.ProtobufObj,\n masterMessage *C.ProtobufObj) {\n if (ptr != nil) {\n var driver *SchedulerDriver = (*SchedulerDriver)(ptr)\n\n if (driver.Scheduler.Registered == nil) {\n return\n }\n\n frameworkData := C.GoBytes(\n frameworkMessage.data,\n C.int(frameworkMessage.size))\n\n var frameworkId FrameworkID\n err := proto.Unmarshal(frameworkData, &frameworkId); if err != nil {\n return\n }\n\n masterData := C.GoBytes(masterMessage.data, C.int(masterMessage.size))\n var masterInfo MasterInfo\n err = proto.Unmarshal(masterData, &masterInfo); if err != nil {\n return\n }\n\n driver.Scheduler.Registered(driver, frameworkId, masterInfo)\n }\n}",
"func (w *BaseWebsocketClient) OnWsMessage(payload []byte, isBinary bool) {}",
"func (f *Handler) dispatch(msg *provisioners.Message) error {\n\terr := f.dispatcher.DispatchMessage(msg, f.destination, \"\", provisioners.DispatchDefaults{})\n\tif err != nil {\n\t\tf.logger.Error(\"Error dispatching message\", zap.String(\"destination\", f.destination))\n\t}\n\treturn err\n}",
"func (ce *executor) dispatchHandleMessage(msg wire.Message) {\n\tcmsg := msg.(consensusMsg)\n\tcurRound := ce.state.getRound()\n\tce.logger.Debugf(\"Receive msg %s ,msg round %d, current round %d\", msg.Command(), cmsg.GetRound(), curRound)\n\tswitch ce.msgFilter(curRound, cmsg) {\n\tcase ignore:\n\t\treturn\n\tcase handleMsg:\n\t\tce.handleNewMessage(curRound, cmsg)\n\tcase handleOtherStateMsg:\n\t\tce.handleOtherStateMessage(curRound, cmsg)\n\t}\n}",
"func (object *MQMessageHandler) OnMQMessage(raw []byte, offset int64) {\n}",
"func (b *Bot) dispatchMessage(s *Server, msg *irc.IrcMessage) {\n\tendpoint := createServerEndpoint(s)\n\tb.dispatcher.Dispatch(msg, endpoint)\n\ts.dispatcher.Dispatch(msg, endpoint)\n}",
"func (b *Bus) dispatchMessage(msg *Message) {\n\tb.messageHandler[msg.Mtype](msg.Addr, msg.Msg)\n}",
"func runCallback(receivedMessage *Message, consumerMessage *sarama.ConsumerMessage) {\n\tcallback := subscribeMap[consumerMessage.Topic][receivedMessage.MessageType]\n\n\tif callback == nil {\n\t\tlogrus.Error(fmt.Sprintf(\"callback not found for topic : %s, message type : %s\", consumerMessage.Topic,\n\t\t\treceivedMessage.MessageType))\n\t\treturn\n\t}\n\n\tgo callback(&Message{\n\t\tTopic: consumerMessage.Topic,\n\t\tMessage: receivedMessage.Message,\n\t\tMessageType: receivedMessage.MessageType,\n\t\tService: receivedMessage.Service,\n\t\tTraceId: receivedMessage.TraceId,\n\t\tMessageId: receivedMessage.MessageId,\n\t}, nil)\n}",
"func (worker *Worker) processMessage(d *amqp.Delivery) {\n\tsignature := TaskSignature{}\n\tjson.Unmarshal([]byte(d.Body), &signature)\n\n\ttask := worker.server.GetRegisteredTask(signature.Name)\n\tif task == nil {\n\t\tlog.Printf(\"Task with a name '%s' not registered\", signature.Name)\n\t\treturn\n\t}\n\n\t// Everything seems fine, process the task!\n\tlog.Printf(\"Started processing %s\", signature.Name)\n\n\treflectedTask := reflect.ValueOf(task)\n\trelfectedArgs, err := ReflectArgs(signature.Args)\n\tif err != nil {\n\t\tworker.finalize(\n\t\t\t&signature,\n\t\t\treflect.ValueOf(nil),\n\t\t\terr,\n\t\t)\n\t\treturn\n\t}\n\n\tresults := reflectedTask.Call(relfectedArgs)\n\tif !results[1].IsNil() {\n\t\tworker.finalize(\n\t\t\t&signature,\n\t\t\treflect.ValueOf(nil),\n\t\t\terrors.New(results[1].String()),\n\t\t)\n\t\treturn\n\t}\n\n\t// Trigger success or error tasks\n\tworker.finalize(&signature, results[0], err)\n}",
"func (em *EventManager) handleMessage(i interface{}) error {\n\tvar err error = nil\n\n\tm := i.(Message)\n\n\tlog.Printf(\"Processing message\")\n\n\t// TODO: process incoming message\n\tres, err := em.wc.HandleMessage(m.Text())\n\tif err != nil {\n\t\tlog.Printf(\"Error processing message\")\n\t\treturn err\n\t}\n\n\t// TODO: act on message\n\tswitch res.Intent {\n\tcase analysis.IntentCreateEvent:\n \n\n\tcase analysis.IntentCancelEvent:\n // Check owner, when and where match\n\n // Delete event\n\n\tcase analysis.IntentFindEvents:\n // Find events based on when / where filters\n\n\tcase analysis.IntentAttending:\n // Set attending flag for a given event\n\n\tcase analysis.IntentNotAttending:\n // Set not attending flag for a given event\n\n case analysis.IntentArrived:\n // Set arrived flag for a given event\n\n\t}\n\n\tif res.Response != \"\" {\n\t\tlog.Printf(\"Sending reply\")\n\n\t\t// Generate reply\n\t\treply := m.Reply(res.Response)\n\n\t\t// Locate matching client\n\t\tc, ok := em.clients[m.Connector()]\n\t\tif !ok {\n\t\t\tlog.Printf(\"Invalid connector %s for response\", m.Connector())\n\t\t\treturn err\n\t\t}\n\n\t\t// Send reply\n\t\tc.Send(reply)\n\t}\n\n\treturn err\n}",
"func (*GenericFramework) ValidateMessage(ctx *MessageContext) bool { return true }",
"func (h *Handler) dispatchMsg(msg message) {\n\tif h.closing {\n\t\th.ctx.Log.Debug(\"dropping message due to closing:\\n%s\", msg)\n\t\th.metrics.dropped.Inc()\n\t\treturn\n\t}\n\n\tstartTime := h.clock.Time()\n\n\th.ctx.Lock.Lock()\n\tdefer h.ctx.Lock.Unlock()\n\n\tif msg.IsPeriodic() {\n\t\th.ctx.Log.Verbo(\"Forwarding message to consensus: %s\", msg)\n\t} else {\n\t\th.ctx.Log.Debug(\"Forwarding message to consensus: %s\", msg)\n\t}\n\n\tvar (\n\t\terr error\n\t)\n\tswitch msg.messageType {\n\tcase notifyMsg:\n\t\terr = h.engine.Notify(msg.notification)\n\t\th.notify.Observe(float64(h.clock.Time().Sub(startTime)))\n\tcase gossipMsg:\n\t\terr = h.engine.Gossip()\n\t\th.gossip.Observe(float64(h.clock.Time().Sub(startTime)))\n\tdefault:\n\t\terr = h.handleValidatorMsg(msg, startTime)\n\t}\n\n\tif err != nil {\n\t\th.ctx.Log.Fatal(\"forcing chain to shutdown due to: %s\", err)\n\t\th.closing = true\n\t}\n}",
"func (a *customAdapter) sendMessage(ctx *customAdapterWorkerContext, req interface{}) error {\n\tb, err := json.Marshal(req)\n\tif err != nil {\n\t\treturn err\n\t}\n\ta.Trace(\"xfer: Custom adapter worker %d sending message: %v\", ctx.workerNum, string(b))\n\t// Line oriented JSON\n\tb = append(b, '\\n')\n\t_, err = ctx.stdin.Write(b)\n\treturn err\n}",
"func (r *slaveRunner) onCustomMessage(msg *CustomMessage) {\n\tif msg == nil {\n\t\treturn\n\t}\n\tEvents.Publish(msg.Type, msg)\n}",
"func dispatchMessage(r Recorder, key string, msg *model.Message) error {\n\tif f := (*r.GetHandlerMap())[key]; f != nil {\n\t\treturn f(r, key, msg)\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Start will start the provided command and return a Session that can be used to await completion or signal the process. The provided logger is used log stderr from the running process.
|
func Start(logger *flogging.FabricLogger, cmd *exec.Cmd, exitFuncs ...ExitFunc) (*Session, error) {
logger = logger.With("command", filepath.Base(cmd.Path))
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
err = cmd.Start()
if err != nil {
return nil, err
}
sess := &Session{
command: cmd,
exitFuncs: exitFuncs,
exited: make(chan struct{}),
}
go sess.waitForExit(logger, stderr)
return sess, nil
}
|
[
"func (c *Cmd) Start() error",
"func (a *ExternalAgentProcess) Start() error {\n\treturn a.cmd.Start()\n}",
"func (c *Cmd) Start() error {\n\t// go routines to scan command out and err\n\tif c.ShowOutput {\n\t\terr := c.createPipeScanners()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn c.Cmd.Start()\n}",
"func Start(writer io.Writer) error {\n\tfmt.Println(NOTICE_ENTER)\n\n\tlogger.Debug(\"Start the shell\")\n\n\tsh := getShell()\n\tif sh == \"\" {\n\t\treturn errors.New(\"nil shell\")\n\t}\n\n\tlogger.Debug(\"Create command with shell: \" + sh)\n\n\tcmd := exec.Command(sh)\n\tif cmd == nil {\n\t\treturn fmt.Errorf(\"nil command for shell %s\", sh)\n\t}\n\n\tlogger.Debug(\"Assign the pipes.\")\n\n\tcmd.Stdin = os.Stdin\n\tcmd.Stdout = writer\n\tcmd.Stderr = os.Stderr\n\n\tlogger.Debug(\"Start the command\")\n\n\tif err := cmd.Start(); err != nil {\n\t\treturn err\n\t}\n\n\tlogger.Debug(\"Wait for the command to end.\")\n\n\terr := cmd.Wait()\n\n\tfmt.Println(NOTICE_EXIT)\n\n\treturn err\n}",
"func (cmd *Cmd) Start() error {\n\n\t// Bind output routines if channel exists\n\tif cmd.OutputChan != nil {\n\t\tstdout, err := cmd.Cmd.StdoutPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo cmd.readCloserToChannel(stdout, cmd.OutputChan)\n\t\tstderr, err := cmd.Cmd.StderrPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo cmd.readCloserToChannel(stderr, cmd.OutputChan)\n\t}\n\n\t// Bind input routine if channel exists\n\tif cmd.InputChan != nil {\n\t\tstdin, err := cmd.Cmd.StdinPipe()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tgo cmd.channelToWriteCloser(cmd.InputChan, stdin)\n\t}\n\n\treturn cmd.Cmd.Start()\n}",
"func (cmd *Cmd) Start() error {\n\tif cmd.Exited() {\n\t\treturn fmt.Errorf(\"command already exitted\")\n\t}\n\tcmd.Lock()\n\tdefer cmd.Unlock()\n\n\tcmd.start.Do(func() {\n\t\terr := cmd.cmd.Start()\n\t\tcmd.startErr = err\n\t})\n\treturn cmd.startErr\n}",
"func StartLogger(name, filename string, verbose bool) *logger.Logger {\n\tlogPath := \"/var/log/gogios/\" + filename + \".log\"\n\n\tfile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0660)\n\tif err != nil {\n\t\tlogger.Fatalf(\"Failed to open log file: %v\", err)\n\t}\n\tdefer file.Close()\n\n\tgoglog := logger.Init(name, verbose, true, file)\n\n\treturn goglog\n}",
"func (l *Logger) StartLogger() {\n\tfor {\n\t\tselect {\n\t\tcase bm := <-l.msg:\n\t\t\tfor _, l := range l.outputs {\n\t\t\t\tif err := l.WriteMsg(bm.msg, bm.skip, bm.level); err != nil {\n\t\t\t\t\tfmt.Println(\"ERROR, unable to WriteMsg:\", err)\n\t\t\t\t}\n\t\t\t}\n\t\tcase <-l.quit:\n\t\t\treturn\n\t\t}\n\t}\n}",
"func (p *Process) Start() error {\n\t// See if we have a PID.\n\tif p.PID > 0 {\n\t\t// See if there is still a process with that PID.\n\t\t_, err := process.NewProcess(p.PID)\n\t\tif err == nil {\n\t\t\treturn fmt.Errorf(\"process with PID %d already started\", p.PID)\n\t\t}\n\t\t// Process for this PID no longer running so clear the PID and start\n\t\t// new process.\n\t\tp.PID = 0\n\t}\n\n\tif p.Cmdline == \"\" {\n\t\treturn errors.New(\"no Cmdline set\")\n\t}\n\n\tp2, err := p.Pane.StartProcess(p.Cmdline)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t*p = *p2\n\n\treturn nil\n}",
"func (d *WebhookDaemon) StartWithLogger(ctx context.Context, logger *log.Logger) error {\n\n\thandler, err := d.HandlerFuncWithLogger(logger)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to create handler func, %w\", err)\n\t}\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/\", handler)\n\n\tsvr := d.server\n\n\tlogger.Printf(\"webhookd listening for requests on %s\\n\", svr.Address())\n\n\terr = svr.ListenAndServe(ctx, mux)\n\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Failed to listen for requests, %w\", err)\n\t}\n\n\treturn nil\n}",
"func (r *RunRunc) Start(log lager.Logger, bundlePath, id string, io garden.ProcessIO) (garden.Process, error) {\n\tlog = log.Session(\"start\", lager.Data{\"bundle\": bundlePath})\n\n\tlog.Info(\"started\")\n\tdefer log.Info(\"finished\")\n\n\tcmd := r.runc.StartCommand(bundlePath, id)\n\n\tprocess, err := r.tracker.Run(r.pidGenerator.Generate(), cmd, io, nil)\n\tif err != nil {\n\t\tlog.Error(\"run\", err)\n\t\treturn nil, err\n\t}\n\n\treturn process, nil\n}",
"func (p *process) Start() error {\n\tvar err error\n\n\tif p.cmd != nil {\n\t\treturn fmt.Errorf(p.Title, \": Process already started\")\n\t}\n\n\tname := p.Command[0]\n\targs := make([]string, len(p.Command)-1)\n\tcopy(args, p.Command[1:])\n\tfor i := range args {\n\t\tif strings.HasPrefix(args[i], \"$\") {\n\t\t\targs[i] = os.Getenv(strings.TrimPrefix(args[i], \"$\"))\n\t\t}\n\t}\n\tlog.Print(p.Title, \": Starting: \", name, \" \", strings.Join(args, \" \"))\n\tp.cmd = exec.Command(name, args...) // HL\n\tp.cmd.Dir = p.Dir\n\n\tp.stdin, err = p.cmd.StdinPipe() // HL\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.stdout, err = p.cmd.StdoutPipe() // HL\n\tif err != nil {\n\t\treturn err\n\t}\n\tp.cmd.Stderr = p.cmd.Stdout // HL\n\n\terr = p.cmd.Start() // HL\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (t *Transaction) Start(ctx context.Context) error {\n\tcmd := fmt.Sprintf(\"%s transaction %s\", t.Binary, t.Repo)\n\tres := shell.Run(cmd, shell.Context(ctx))\n\tt.log.InfoL(res.Stdout().Lines())\n\tt.log.ErrorL(res.Stderr().Lines())\n\treturn res.Err()\n}",
"func (m *mware) Start() error {\n\tif err := m.cmd.Start(); err != nil {\n\t\treturn fmt.Errorf(\"failed to start middleware command: %w\", err)\n\t}\n\n\treturn nil\n}",
"func (l *Locker) Start(_ context.Context) error {\n\t// perform dialing\n\tcli, err := dial(l.cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.cli = cli\n\n\tss, err := concurrency.NewSession(l.cli)\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.ss = ss\n\tlog.Infof(\"Started etcd locker\")\n\treturn nil\n}",
"func (c *ChatClient) Start() (err error) {\n\tc.session.AddHandler(c.handleIncomingMessage)\n\treturn c.session.Open()\n}",
"func (c *Communicator) Start(rc *remote.Cmd) error {\n\trc.Init()\n\tlog.Printf(\"[DEBUG] starting remote command: %s\", rc.Command)\n\n\t// TODO: make sure communicators always connect first, so we can get output\n\t// from the connection.\n\tif c.client == nil {\n\t\tlog.Println(\"[WARN] winrm client not connected, attempting to connect\")\n\t\tif err := c.Connect(nil); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tstatus, err := c.client.Run(rc.Command, rc.Stdout, rc.Stderr)\n\trc.SetExitStatus(status, err)\n\n\treturn nil\n}",
"func (s *SSHRunner) StartCmd(cmd *exec.Cmd) (*StartedCmd, error) {\n\tif cmd.Stdin != nil {\n\t\treturn nil, fmt.Errorf(\"SSHRunner does not support stdin - you could be the first to add it\")\n\t}\n\n\tif s.s != nil {\n\t\treturn nil, fmt.Errorf(\"another SSH command has been started and is currently running\")\n\t}\n\n\tvar wg sync.WaitGroup\n\twg.Add(2)\n\trr := &RunResult{Args: cmd.Args}\n\tsc := &StartedCmd{cmd: cmd, rr: rr, wg: &wg}\n\tklog.Infof(\"Start: %v\", rr.Command())\n\n\tvar outb, errb io.Writer\n\n\tif cmd.Stdout == nil {\n\t\tvar so bytes.Buffer\n\t\toutb = io.MultiWriter(&so, &rr.Stdout)\n\t} else {\n\t\toutb = io.MultiWriter(cmd.Stdout, &rr.Stdout)\n\t}\n\n\tif cmd.Stderr == nil {\n\t\tvar se bytes.Buffer\n\t\terrb = io.MultiWriter(&se, &rr.Stderr)\n\t} else {\n\t\terrb = io.MultiWriter(cmd.Stderr, &rr.Stderr)\n\t}\n\n\tsess, err := s.session()\n\tif err != nil {\n\t\treturn sc, errors.Wrap(err, \"NewSession\")\n\t}\n\n\ts.s = sess\n\n\terr = teeSSHStart(s.s, shellquote.Join(cmd.Args...), outb, errb, &wg)\n\n\treturn sc, err\n}",
"func StartCommand(ctx context.Context, cmd string, args ...string) Fixer {\n\treturn func() (string, error) {\n\t\tcmd := exec.CommandContext(ctx, cmd, args...)\n\t\terr := cmd.Start()\n\t\tif err != nil {\n\t\t\treturn \"command did not start successfully.\", err\n\t\t}\n\t\treturn \"command started successfully.\", nil\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
canonical service name, e.g. "comment" => "comment.hy.byted.org." can be further used as DNS domain name
|
func (sd *ServiceDiscovery) CanonicalName(service string) string {
if strings.HasSuffix(service, sd.Domain) {
return service
}
return strings.Join([]string{service, serviceSuffix, sd.Dc, sd.Domain}, ".")
}
|
[
"func hostnameForService(svc string) string {\n\n\tparts := strings.Split(svc, \"/\")\n\tif len(parts) < 2 {\n\t\treturn parts[0]\n\t}\n\tif len(parts) > 2 {\n\t\tlog.Printf(\"Malformated service identifier [%s] - Hostname will be truncated\", svc)\n\t}\n\treturn fmt.Sprintf(\"%s.%s\", parts[1], parts[0])\n\n}",
"func serviceHostname(name string) string {\n\t// TODO include datacenter in Hostname?\n\t// consul DNS uses \"redis.service.us-east-1.consul\" -> \"[<optional_tag>].<svc>.service.[<optional_datacenter>].consul\"\n\treturn fmt.Sprintf(\"%s.service.consul\", name)\n}",
"func (me *Entry) ServiceName() (string, error) {\n\n\tvar sn string\n\tvar err error\n\n\tfor range only.Once {\n\t\tif me == nil {\n\t\t\terr = errors.New(\"software error\")\n\t\t\tbreak\n\t\t}\n\n\t\tsn = fmt.Sprintf(\"%s.%s.\", trimDot(me.Service), trimDot(me.Domain))\n\t}\n\n\treturn sn, err\n}",
"func NormalizeForServiceName(svcName string) string {\n\tre := regexp.MustCompile(\"[._]\")\n\tnewName := strings.ToLower(re.ReplaceAllString(svcName, \"-\"))\n\tif newName != svcName {\n\t\tlog.Infof(\"Changing service name to %s from %s\", svcName, newName)\n\t}\n\treturn newName\n}",
"func cleanServiceName(in string) string {\n\tr := strings.NewReplacer(\n\t\t\"-\", \"_\",\n\t\t\" \", \"_\",\n\t\t\".\", \"_\",\n\t\t\"/\", \"_\",\n\t\t\"\\\\\", \"_\",\n\t)\n\n\treturn snaker.SnakeToCamel(r.Replace(in))\n}",
"func CanonicalName(s string) string {\n\treturn strings.ToLower(Fqdn(s))\n}",
"func servicename(meta metav1.ObjectMeta, portname string) string {\n\tname := []string{\n\t\tmeta.Namespace,\n\t\tmeta.Name,\n\t\tportname,\n\t}\n\tif portname == \"\" {\n\t\tname = name[:2]\n\t}\n\treturn strings.Join(name, \"/\")\n}",
"func fullyQualifiedDomainName(log log.T) string {\n\thostName, _ := os.Hostname()\n\n\tdnsHostName := getWMICComputerSystemValue(\"DNSHostName\")\n\tdomainName := getWMICComputerSystemValue(\"Domain\")\n\n\tif dnsHostName == \"\" || domainName == \"\" {\n\t\treturn hostName\n\t}\n\n\treturn dnsHostName + \".\" + domainName\n}",
"func GetServiceDomainName(prefix string) (ret string) {\n\tsuffix := extractSuffix()\n\tret = prefix + suffix\n\tLogf(\"Get domain name: %s\", ret)\n\treturn\n}",
"func TLSAName(name, service, network string) (string, error) {\n\tif !IsFqdn(name) {\n\t\treturn \"\", ErrFqdn\n\t}\n\tp, err := net.LookupPort(network, service)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"_\" + strconv.Itoa(p) + \"._\" + network + \".\" + name, nil\n}",
"func (name Name) DNSName() string {\n\treturn strings.ReplaceAll(name.String(), \"_\", \"-\")\n}",
"func BuildServiceDNSName(service, branch, environment, serviceNamespace string) string {\n\treturn service + \"-\" + branch + \"-\" + environment + \".\" + serviceNamespace\n}",
"func (p project) DNSName() string {\n\treturn strings.Replace(strcase.ToSnake(p.Name), \"_\", \"-\", -1)\n}",
"func ToCanonicalName(name string) string {\n\tnameParts := strings.Split(name, \"/\")\n\t// Reverse first part. e.g., io.k8s... instead of k8s.io...\n\tif len(nameParts) > 0 && strings.Contains(nameParts[0], \".\") {\n\t\tparts := strings.Split(nameParts[0], \".\")\n\t\tfor i, j := 0, len(parts)-1; i < j; i, j = i+1, j-1 {\n\t\t\tparts[i], parts[j] = parts[j], parts[i]\n\t\t}\n\t\tnameParts[0] = strings.Join(parts, \".\")\n\t}\n\treturn strings.Join(nameParts, \".\")\n}",
"func (me *Entry) ServiceTypeName() (string, error) {\n\n\tvar sn string\n\tvar err error\n\n\tfor range only.Once {\n\t\tif me == nil {\n\t\t\terr = errors.New(\"software error\")\n\t\t\tbreak\n\t\t}\n\n\t\tsn = fmt.Sprintf(\"_services._dns-sd._udp.%s.\", trimDot(me.Domain))\n\t}\n\n\treturn sn, err\n}",
"func normalizeDomain(domain string) (string, error) {\n\tdomain = strings.Trim(strings.ToLower(domain), \" \")\n\t// not checking if it belongs to icann\n\tsuffix, _ := publicsuffix.PublicSuffix(domain)\n\tif domain != \"\" && suffix == domain { // input is publicsuffix\n\t\treturn \"\", errors.New(\"domain [\" + domain + \"] is public suffix\")\n\t}\n\tif !strings.HasPrefix(domain, \"http\") {\n\t\tdomain = fmt.Sprintf(\"http://%s\", domain)\n\t}\n\turl, err := url.Parse(domain)\n\tif nil == err && url.Host != \"\" {\n\t\treturn strings.Replace(url.Host, \"www.\", \"\", 1), nil\n\t}\n\treturn \"\", err\n}",
"func fullyQualifiedDomainName(log log.T) string {\n\tvar hostName, fqdn string\n\tvar err error\n\n\tif hostName, err = os.Hostname(); err != nil {\n\t\treturn \"\"\n\t}\n\n\tvar contentBytes []byte\n\tif contentBytes, err = execWithTimeout(hostNameCommand, \"-f\"); err == nil {\n\t\tfqdn = string(contentBytes)\n\t\t//trim whitespaces - since by default above command appends '\\n' at the end.\n\t\t//e.g: 'ip-172-31-7-113.ec2.internal\\n'\n\t\tfqdn = strings.TrimSpace(fqdn)\n\t}\n\n\tif fqdn != \"\" {\n\t\treturn fqdn\n\t}\n\n\treturn strings.TrimSpace(hostName)\n}",
"func frontendNameForServicePort(service *corev1.Service, port corev1.ServicePort) string {\n\treturn fmt.Sprintf(serviceFrontendNameFormatString, stringsutil.ReplaceForwardSlashesWithDots(cluster.Name), service.Namespace, service.Name, port.Port)\n}",
"func (o ForwardingRuleOutput) ServiceName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v *ForwardingRule) pulumi.StringOutput { return v.ServiceName }).(pulumi.StringOutput)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Single path ClearPath of a participant.
|
func (g *game) ClearPath(participant int) {
g.paths[participant] = *NewPathEmpty()
}
|
[
"func (p *Path) Clear() {\n\tp.Components = p.Components[0:0]\n\tp.Points = p.Points[0:0]\n\treturn\n}",
"func (g *game) ResetPath(participant int) {\r\n\t// GeneratePath contains a path-finding algorithm. This function is used as a path finder.\r\n\tGeneratePath := func(g *game, participant int) Path {\r\n\t\tconst icol int = 0 // level\r\n\t\tirow := participant // participant\r\n\t\tgrid := g.ladder.grid\r\n\t\troute := []pixel.Vec{}\r\n\t\tprize := -1\r\n\t\tfor level := icol; level < g.ladder.nLevel; level++ {\r\n\t\t\troute = append(route, grid[irow][level])\r\n\t\t\tprize = irow\r\n\t\t\tif irow+1 < g.ladder.nParticipants {\r\n\t\t\t\tif g.ladder.bridges[irow][level] {\r\n\t\t\t\t\tirow++ // cross the bridge ... to the left (south)\r\n\t\t\t\t\troute = append(route, grid[irow][level])\r\n\t\t\t\t\tprize = irow\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif irow-1 >= 0 {\r\n\t\t\t\tif g.ladder.bridges[irow-1][level] {\r\n\t\t\t\t\tirow-- // cross the bridge ... to the right (north)\r\n\t\t\t\t\troute = append(route, grid[irow][level])\r\n\t\t\t\t\tprize = irow\r\n\t\t\t\t\tcontinue\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\t// log.Println(participant, prize, irow) //\r\n\r\n\t\t// A path found here is called a route or roads.\r\n\t\treturn *NewPath(route, &prize) // val, not ptr\r\n\t}\r\n\r\n\tg.paths[participant] = GeneratePath(g, participant) // path-find\r\n\tg.paths[participant].OnPassedEachPoint = func(pt pixel.Vec, dir pixel.Vec) {\r\n\t\tg.explosions.ExplodeAt(pt, dir.Scaled(2))\r\n\t}\r\n}",
"func (a *ScratchAccount) Path() string {\n\treturn \"\"\n}",
"func (p *TargetEdgePath) Clear() {\n\t*p = (*p)[:0]\n}",
"func (*CaVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/verification_ca/%s\", ref)\n}",
"func (o WaitingRoomAdditionalRouteOutput) Path() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v WaitingRoomAdditionalRoute) *string { return v.Path }).(pulumi.StringPtrOutput)\n}",
"func (duo *DatumUpdateOne) ClearParticipant() *DatumUpdateOne {\n\tduo.mutation.ClearParticipant()\n\treturn duo\n}",
"func (c *Client) PathDestroy(i *PathInput) error {\n\tvar err error\n\n\t// Initialize the input\n\ti.opType = \"destroy\"\n\terr = c.InitPathInput(i)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to init destroy path %s: %w\", i.Path, err)\n\t}\n\n\t// Do the actual destroy\n\t_, err = c.Logical().Delete(i.opPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to destroy secret at %s: %w\", i.opPath, err)\n\t}\n\n\treturn err\n}",
"func (c *container) Path() *Path {\n\tp := &Path{}\n\tc.contents = append(c.contents, p)\n\n\treturn p\n}",
"func (id ID) Path() string {\n\treturn id.path\n}",
"func (*CaHttpVerificationCa) DeletePath(ref string) string {\n\treturn fmt.Sprintf(\"/api/objects/ca/http_verification_ca/%s\", ref)\n}",
"func (hc *HealthCheckArgsOrString) Path() *string {\n\tif hc.IsBasic() {\n\t\treturn aws.String(hc.Basic)\n\t}\n\treturn hc.Advanced.Path\n}",
"func (s *stubPathHandler) DeletePath(ctx context.Context, id string) (int, error) {\n\n\n\tidp, err := primitive.ObjectIDFromHex(id)\n\tif err != nil{\n\t\tlevel.Error(s.logger).Log(\"method\", \"GetSpotsInQuadrant\", \"error\", err)\n\t\treturn 0, err\n\t}\n\tfilter := bson.D{{\"_id\", idp}}\n\n\tresult, err := s.db.DeleteOne(ctx, filter, \"mazedb\", \"paths\")\n\tif err != nil {\n\t\tlevel.Error(s.logger).Log(\"method\", \"DeletePath\", \"error\", err)\n\t\treturn 0, err\n\t}\n\n\treturn result, nil\n}",
"func clearPath(filePath string) string {\n\t_, file := path.Split(filePath)\n\tconst fileFormatSeparator = \".\"\n\tformatParts := strings.Split(file, fileFormatSeparator)\n\treturn strings.Join(formatParts[:len(formatParts)-1], fileFormatSeparator)\n}",
"func (i *Instance) Path() (string, error) {\n\tref, _, _, err := i.GetAsAny(WmiPathKey)\n\treturn ref.(string), err\n}",
"func (piuo *ProviderIDUpdateOne) ClearParticpant() *ProviderIDUpdateOne {\n\tpiuo.mutation.ClearParticpant()\n\treturn piuo\n}",
"func (tc *TrafficCapture) Path() (string, error) {\n\ttc.RLock()\n\tdefer tc.RUnlock()\n\n\treturn tc.writer.Path()\n}",
"func (aauo *APIAuditUpdateOne) ClearHTTPPath() *APIAuditUpdateOne {\n\taauo.mutation.ClearHTTPPath()\n\treturn aauo\n}",
"func (r Rooted) Path() Path {\n\treturn r.Root.Join(string(r.Fragment))\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
ResetPath of a participant.
|
func (g *game) ResetPath(participant int) {
// GeneratePath contains a path-finding algorithm. This function is used as a path finder.
GeneratePath := func(g *game, participant int) Path {
const icol int = 0 // level
irow := participant // participant
grid := g.ladder.grid
route := []pixel.Vec{}
prize := -1
for level := icol; level < g.ladder.nLevel; level++ {
route = append(route, grid[irow][level])
prize = irow
if irow+1 < g.ladder.nParticipants {
if g.ladder.bridges[irow][level] {
irow++ // cross the bridge ... to the left (south)
route = append(route, grid[irow][level])
prize = irow
continue
}
}
if irow-1 >= 0 {
if g.ladder.bridges[irow-1][level] {
irow-- // cross the bridge ... to the right (north)
route = append(route, grid[irow][level])
prize = irow
continue
}
}
}
// log.Println(participant, prize, irow) //
// A path found here is called a route or roads.
return *NewPath(route, &prize) // val, not ptr
}
g.paths[participant] = GeneratePath(g, participant) // path-find
g.paths[participant].OnPassedEachPoint = func(pt pixel.Vec, dir pixel.Vec) {
g.explosions.ExplodeAt(pt, dir.Scaled(2))
}
}
|
[
"func (g *game) ClearPath(participant int) {\r\n\tg.paths[participant] = *NewPathEmpty()\r\n}",
"func (r *reaper) resetPath(path string) {\n\tr.pathsMtx.Lock()\n\tr.paths[path] = 0\n\tr.pathsMtx.Unlock()\n}",
"func (m *FileMutation) ResetPath() {\n\tm._path = nil\n}",
"func (m *URLMutation) ResetPath() {\n\tm._path = nil\n}",
"func SetPath(p string) {\n\tcurrentPath = \"\"\n\tbeginPath = p\n\tdirsAmount = 0\n}",
"func SetPath(p string) {\n\tpath = filepath.FromSlash(p)\n}",
"func (p *Path) Clear() {\n\tp.Components = p.Components[0:0]\n\tp.Points = p.Points[0:0]\n\treturn\n}",
"func (de *Dirent) reset() {\n\tde.name = \"\"\n\tde.path = \"\"\n\tde.modeType = 0\n}",
"func (d *DeploymentCoreStruct) restorePath() (err error) {\n\tif d.savedPath == \"\" {\n\t\treturn\n\t}\n\terr = os.Chdir(d.savedPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\tgotrace.Trace(\"GIT: Restored to '%s'\", d.savedPath)\n\td.savedPath = \"\"\n\tgit.UnIndent()\n\treturn\n}",
"func (o *HyperflexTrackedFileAllOf) UnsetFilePath() {\n\to.FilePath.Unset()\n}",
"func (c *CmdReal) SetPath(path string) {\n\tc.cmd.Path = path\n}",
"func (m *ItemReference) SetPath(value *string)() {\n m.path = value\n}",
"func (o *GetNdmpSettingsVariableParams) SetPath(path *string) {\n\to.Path = path\n}",
"func (_m *requestHeaderMapUpdatable) SetPath(path string) {\n\t_m.Called(path)\n}",
"func (p *peer) Reset(addr net.Addr) {\n\tp.addr = addr\n\tp.Close()\n}",
"func (r *Input) SetPath(path string) error {\n\tquery, err := fetch.Parse(path)\n\tif err != nil {\n\t\treturn err\n\t}\n\tr.Lock()\n\tr.Path = query\n\tr.Unlock()\n\treturn nil\n}",
"func (p Path) UnencryptedPath() paths.Unencrypted { return p.unencPath }",
"func (f *LogFile) SetPath(path string) { f.path = path }",
"func clearPath(filePath string) string {\n\t_, file := path.Split(filePath)\n\tconst fileFormatSeparator = \".\"\n\tformatParts := strings.Split(file, fileFormatSeparator)\n\treturn strings.Join(formatParts[:len(formatParts)-1], fileFormatSeparator)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Shuffle in an approximate time.
|
func (g *game) Shuffle(times, inMillisecond int) {
speed := g.galaxy.Speed()
g.galaxy.SetSpeed(speed * 10)
{
i := 0
for range time.Tick(
(time.Millisecond * time.Duration(inMillisecond)) / time.Duration(times),
) {
g.bg = gg.RandomNiceColor()
g.Reset()
i++
if i >= times {
break
}
}
}
g.galaxy.SetSpeed(speed)
}
|
[
"func Shuffle(n int, swap func(i, j int)) { globalRand.Shuffle(n, swap) }",
"func (s *summary) shuffle(rng RNG) {\n\tfor i := len(s.means) - 1; i > 1; i-- {\n\t\ts.Swap(i, rng.Intn(i+1))\n\t}\n}",
"func Shuffle(n int, swap func(i, j int)) { pseudo.Shuffle(n, swap) }",
"func Benchmark_rand_ShuffleOverhead(b *testing.B) {\n\tr := gorand.New(rand.NewSource(5489))\n\tfor n := b.N; n > 0; n-- {\n\t\tr.Shuffle(52, func(i, j int) {\n\t\t\tif i < 0 || i >= 52 || j < 0 || j >= 52 {\n\t\t\t\tb.Fatalf(\"bad swap(%d, %d)\", i, j)\n\t\t\t}\n\t\t})\n\t}\n}",
"func (pts testDatapoints) Shuffle() {\n\tfor i := len(pts) - 1; i > 0; i-- {\n\t\tif j := rand.Intn(i + 1); i != j {\n\t\t\tpts[i], pts[j] = pts[j], pts[i]\n\t\t}\n\t}\n}",
"func BenchmarkShuffleOverhead(b *testing.B) {\n\tr := New(NewSource(1))\n\tfor n := b.N; n > 0; n-- {\n\t\tr.Shuffle(52, func(i, j int) {\n\t\t\tif i < 0 || i >= 52 || j < 0 || j >= 52 {\n\t\t\t\tb.Fatalf(\"bad swap(%d, %d)\", i, j)\n\t\t\t}\n\t\t})\n\t}\n}",
"func shuffle(a []string) {\n\tfor i := range a {\n\t\tj := r.Intn(i + 1)\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n}",
"func shuffle(cards []int) {\n\tfor i := len(cards) - 1; i >= 1; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\tcards[i], cards[j] = cards[j], cards[i]\n\t}\n}",
"func (c *Cage) shuffle() {\n\tc.rng.Shuffle(len(c.Inside), func(i, j int) {\n\t\tc.Inside[i], c.Inside[j] = c.Inside[j], c.Inside[i]\n\t})\n}",
"func ShuffleSeedTime() int64 {\n\treturn time.Now().UnixNano()\n}",
"func TestShuffle(t *testing.T) {\n\tdeck := New()\n\tShuffle(deck)\n}",
"func (q *Quiz) Shuffle() {\n\trand.Seed(time.Now().UnixNano())\n\trand.Shuffle(len(q.QAS), func(i, j int) { q.QAS[i], q.QAS[j] = q.QAS[j], q.QAS[i] })\n\tfor _, qa := range q.QAS {\n\t\tqa.Shuffle()\n\t}\n}",
"func (d *Deck) shuffle() {\n\tdeck := d.cards\n\tfor i := 1; i < len(deck); i++ {\n\t\tr := rand.Intn(i + 1)\n\t\tif i != r {\n\t\t\tdeck[r], deck[i] = deck[i], deck[r]\n\t\t}\n\t}\n}",
"func (a Slice[T]) Shuffle() Slice[T] {\n\tfor i := len(a) - 1; i > 0; i-- {\n\t\tj := rand.Intn(i + 1)\n\t\ta[i], a[j] = a[j], a[i]\n\t}\n\treturn a\n}",
"func (list *List) Shuffle() {\n\tfor i := range list.data {\n\t\tj := rand.Intn(i + 1)\n\t\tlist.data[i], list.data[j] = list.data[j], list.data[i]\n\t}\n}",
"func (g *game) Shuffle() {\n\tfor i := 0; i < len(g); i++ {\n\t\tj := rand.Intn(i + 1)\n\t\tg[i].Shuffle()\n\t\tg[j].Shuffle()\n\t\tg[i], g[j] = g[j], g[i]\n\t}\n}",
"func (list List) Shuffle() {\n\trand.Seed(time.Now().Unix())\n\trand.Shuffle(len(list), func(i, j int) {\n\t\tlist[i], list[j] = list[j], list[i]\n\t})\n}",
"func TestShuffle(t *testing.T) {\n\tdeckcount := 100\n\toffset := 1\n\n\tdeck := Deck{}\n\tcards := make([]Card, deckcount)\n\tdeck.cards = &cards\n\n\tfor i := 0; i < deckcount; i++ {\n\t\tcards[i] = Card{id: i + offset}\n\t}\n\n\tfor i := 0; i < deckcount; i++ {\n\t\tfmt.Println(strconv.Itoa(cards[i].id))\n\t}\n\n\tdeck.Shuffle()\n\n\tavg := (float32(offset+deckcount) / 2)\n\tdesiredtotal := int(avg * (float32(deckcount)))\n\n\tdecktotal := 0\n\tfor i := 0; i < deckcount; i++ {\n\t\tdecktotal += cards[i].id\n\t\tfmt.Println(strconv.Itoa(cards[i].id))\n\t}\n\n\tif desiredtotal != decktotal {\n\t\tt.Error(\"The deck is corrupt, expected \" + strconv.Itoa(desiredtotal) + \" received \" + strconv.Itoa(decktotal))\n\t}\n}",
"func ShuffleDeck(deck *Deck) *Deck{\n cards := deck.Cards\n\n for z := 1; z <=100; z++ {\n for i := range cards {\n j := rand.Intn(i + 1)\n cards[i], cards[j] = cards[j], cards[i]\n }\n }\n\n return deck\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Read only methods WindowDeep is a hacky way to access a window in deep. It returns (window glfw.Window) which is an unexported member inside a (pixelgl.Window). Read only argument game ignores the pass lock by value warning.
|
func (g game) WindowDeep() (baseWindow *glfw.Window) {
return *(**glfw.Window)(unsafe.Pointer(reflect.Indirect(reflect.ValueOf(g.window)).FieldByName("window").UnsafeAddr()))
}
|
[
"func (ref *UIElement) Window() *UIElement {\n\tret, _ := ref.UIElementAttr(WindowAttribute)\n\treturn ret\n}",
"func (c *Context) Window() *Window {\n\treturn c.window\n}",
"func (s *Scroll) Window() sparta.Window {\n\treturn s.win\n}",
"func (l *List) Window() sparta.Window {\n\treturn l.win\n}",
"func (wl *WindowList) Win(idx int) *Window {\n\tWindowGlobalMu.Lock()\n\tdefer WindowGlobalMu.Unlock()\n\tif idx >= len(*wl) || idx < 0 {\n\t\treturn nil\n\t}\n\treturn (*wl)[idx]\n}",
"func (s *Session) Window(name string) (*Window, error) {\n\tws, err := s.Windows()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, w := range ws {\n\t\tif w.Name == name {\n\t\t\treturn w, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(`window \"%s\" not found in session \"%s\"`, name, s.Name)\n}",
"func Xsqlite3WindowDup(tls *libc.TLS, db uintptr, pOwner uintptr, p uintptr) uintptr {\n\tvar pNew uintptr = uintptr(0)\n\tif p != 0 {\n\t\tpNew = Xsqlite3DbMallocZero(tls, db, uint64(unsafe.Sizeof(Window{})))\n\t\tif pNew != 0 {\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FzName = Xsqlite3DbStrDup(tls, db, (*Window)(unsafe.Pointer(p)).FzName)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FzBase = Xsqlite3DbStrDup(tls, db, (*Window)(unsafe.Pointer(p)).FzBase)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpFilter = Xsqlite3ExprDup(tls, db, (*Window)(unsafe.Pointer(p)).FpFilter, 0)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpWFunc = (*Window)(unsafe.Pointer(p)).FpWFunc\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpPartition = Xsqlite3ExprListDup(tls, db, (*Window)(unsafe.Pointer(p)).FpPartition, 0)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpOrderBy = Xsqlite3ExprListDup(tls, db, (*Window)(unsafe.Pointer(p)).FpOrderBy, 0)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FeFrmType = (*Window)(unsafe.Pointer(p)).FeFrmType\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FeEnd = (*Window)(unsafe.Pointer(p)).FeEnd\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FeStart = (*Window)(unsafe.Pointer(p)).FeStart\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FeExclude = (*Window)(unsafe.Pointer(p)).FeExclude\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FregResult = (*Window)(unsafe.Pointer(p)).FregResult\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FregAccum = (*Window)(unsafe.Pointer(p)).FregAccum\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FiArgCol = (*Window)(unsafe.Pointer(p)).FiArgCol\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FiEphCsr = (*Window)(unsafe.Pointer(p)).FiEphCsr\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FbExprArgs = (*Window)(unsafe.Pointer(p)).FbExprArgs\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpStart = Xsqlite3ExprDup(tls, db, (*Window)(unsafe.Pointer(p)).FpStart, 0)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpEnd = Xsqlite3ExprDup(tls, db, (*Window)(unsafe.Pointer(p)).FpEnd, 0)\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FpOwner = pOwner\n\t\t\t(*Window)(unsafe.Pointer(pNew)).FbImplicitFrame = (*Window)(unsafe.Pointer(p)).FbImplicitFrame\n\t\t}\n\t}\n\treturn pNew\n}",
"func (p *Page) GetWindow() kit.JSONResult {\n\tbounds, err := p.GetWindowE()\n\tkit.E(err)\n\treturn bounds\n}",
"func (obj *world) WindowApplication() windows.Application {\n\treturn obj.winApp\n}",
"func Window(title string) *WindowWidget {\n\treturn &WindowWidget{\n\t\ttitle: title,\n\t}\n}",
"func WindowDrawList() DrawList {\n\treturn DrawList(C.iggGetWindowDrawList())\n}",
"func (w *windowImpl) WinTex() oswin.Texture {\n\treturn w.winTex\n}",
"func (sc *slidingCounter) getCurrentWindow() *window {\n\tnow := time.Now().Unix()\n\n\tif w, found := sc.windows[now]; found {\n\t\treturn w\n\t}\n\n\tresult := &window{}\n\tsc.windows[now] = result\n\treturn result\n}",
"func (t *Tracker) Window() time.Duration {\n\t// acquire mutex\n\tt.mutex.RLock()\n\tdefer t.mutex.RUnlock()\n\n\treturn t.timeout - time.Since(t.last)\n}",
"func (p *Page) WindowNormal() *Page {\n\tkit.E(p.WindowE(cdp.Object{\n\t\t\"windowState\": \"normal\",\n\t}))\n\treturn p\n}",
"func NewWindow(p Properties, ap *AdvancedProperties) (*window, error) {\n\tif err := glfw.Init(); err != nil {\n\t\treturn nil, err\n\t}\n\tw := &window{t: time.Now()}\n\tif ap != nil {\n\t\tglfw.OpenWindowHint(glfw.RefreshRate, ap.RefreshRate)\n\t\tglfw.OpenWindowHint(glfw.AccumRedBits, ap.AccumRedBits)\n\t\tglfw.OpenWindowHint(glfw.AccumGreenBits, ap.AccumGreenBits)\n\t\tglfw.OpenWindowHint(glfw.AccumBlueBits, ap.AccumBlueBits)\n\t\tglfw.OpenWindowHint(glfw.AccumAlphaBits, ap.AccumAlphaBits)\n\t\tglfw.OpenWindowHint(glfw.AuxBuffers, ap.AuxBuffers)\n\t\tif ap.Stereo {\n\t\t\tglfw.OpenWindowHint(glfw.Stereo, 1)\n\t\t} else {\n\t\t\tglfw.OpenWindowHint(glfw.Stereo, 0)\n\t\t}\n\t\tif ap.NoWindowResize {\n\t\t\tglfw.OpenWindowHint(glfw.WindowNoResize, 1)\n\t\t} else {\n\t\t\tglfw.OpenWindowHint(glfw.WindowNoResize, 0)\n\t\t}\n\t\tglfw.OpenWindowHint(glfw.FsaaSamples, ap.FsaaSamples)\n\t\tglfw.OpenWindowHint(glfw.OpenGLVersionMajor, ap.OpenGLVersionMajor)\n\t\tglfw.OpenWindowHint(glfw.OpenGLVersionMinor, ap.OpenGLVersionMinor)\n\t\tif ap.OpenGLForwardCompat {\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLForwardCompat, 1)\n\t\t} else {\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLForwardCompat, 0)\n\t\t}\n\t\tif ap.OpenGLDebugContext {\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLDebugContext, 1)\n\t\t} else {\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLDebugContext, 0)\n\t\t}\n\t\tswitch ap.OpenGLProfile {\n\t\tcase OpenGLCompatProfile:\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLProfile, glfw.OpenGLCompatProfile)\n\t\tcase OpenGLCoreProfile:\n\t\t\tglfw.OpenWindowHint(glfw.OpenGLProfile, glfw.OpenGLCoreProfile)\n\t\tdefault:\n\t\t\treturn nil, ErrUnknownOpenGLProfile\n\t\t}\n\t}\n\tmode := glfw.Windowed\n\tif p.Fullscreen {\n\t\tmode = glfw.Fullscreen\n\t}\n\tif err := glfw.OpenWindow(p.Width, p.Height, p.R, p.G, p.B, p.A, p.Depth, p.Stencil, mode); err != nil {\n\t\treturn nil, err\n\t}\n\treturn w, nil\n}",
"func PropValWindow(reply *xproto.GetPropertyReply,\n\terr error) (xproto.Window, error) {\n\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\tif reply.Format != 32 {\n\t\treturn 0, fmt.Errorf(\"PropValId: Expected format 32 but got %d\",\n\t\t\treply.Format)\n\t}\n\treturn xproto.Window(xgb.Get32(reply.Value)), nil\n}",
"func NewUpdateWindow()(*UpdateWindow) {\n m := &UpdateWindow{\n }\n m.backingStore = ie8677ce2c7e1b4c22e9c3827ecd078d41185424dd9eeb92b7d971ed2d49a392e.BackingStoreFactoryInstance();\n m.SetAdditionalData(make(map[string]any))\n return m\n}",
"func (w *WidgetImplement) FindWindow() IWindow {\n\tparent := w.Parent()\n\tif parent == nil {\n\t\tpanic(\"Widget:internal error (could not find parent window)\")\n\t}\n\treturn parent.FindWindow()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewWin32LobAppRegistryDetection instantiates a new win32LobAppRegistryDetection and sets the default values.
|
func NewWin32LobAppRegistryDetection()(*Win32LobAppRegistryDetection) {
m := &Win32LobAppRegistryDetection{
Win32LobAppDetection: *NewWin32LobAppDetection(),
}
odataTypeValue := "#microsoft.graph.win32LobAppRegistryDetection"
m.SetOdataType(&odataTypeValue)
return m
}
|
[
"func NewWin32LobAppRegistryRule()(*Win32LobAppRegistryRule) {\n m := &Win32LobAppRegistryRule{\n Win32LobAppRule: *NewWin32LobAppRule(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppRegistryRule\";\n m.SetOdataType(&odataTypeValue);\n return m\n}",
"func NewWin32LobAppFileSystemDetection()(*Win32LobAppFileSystemDetection) {\n m := &Win32LobAppFileSystemDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppFileSystemDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}",
"func NewWin32LobAppProductCodeDetection()(*Win32LobAppProductCodeDetection) {\n m := &Win32LobAppProductCodeDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppProductCodeDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}",
"func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryDetection(), nil\n}",
"func NewWin32LobAppReturnCode()(*Win32LobAppReturnCode) {\n m := &Win32LobAppReturnCode{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}",
"func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}",
"func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}",
"func NewRegistry(b biz.RegistryBiz) *RegistryHandler {\n\treturn &RegistryHandler{\n\t\tSearch: registrySearch(b),\n\t\tFind: registryFind(b),\n\t\tDelete: registryDelete(b),\n\t\tSave: registrySave(b),\n\t}\n}",
"func NewRegistry() *Registry {\n\treturn &Registry{\n\t\tregisteredChecks: make(map[string]Checker),\n\t}\n}",
"func newRegistry() *registry {\n\treg := new(registry)\n\treg.keyManagers = NewKeyManagerMap()\n\treturn reg\n}",
"func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}",
"func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}",
"func NewLob(baseAPI, apiKey, userAgent string) *lob {\n\treturn &lob{\n\t\tBaseAPI: baseAPI,\n\t\tAPIKey: apiKey,\n\t\tUserAgent: userAgent,\n\t}\n}",
"func NewBitmaps(library io.StoreLibrary) (bitmaps *Bitmaps, err error) {\n\tvar mfdArt [model.LanguageCount]*io.DynamicChunkStore\n\n\tfor i := 0; i < model.LanguageCount && err == nil; i++ {\n\t\tmfdArt[i], err = library.ChunkStore(localized[i].mfdart)\n\t}\n\n\tif err == nil {\n\t\tbitmaps = &Bitmaps{mfdArt: mfdArt}\n\t}\n\n\treturn\n}",
"func NewRegistry() *Registry {\n\treturn &Registry{make(coderMap)}\n}",
"func NewRegistry() *Registry {\n\treturn RegistryWith(Options{})\n}",
"func New(glabel string, flags int) (*GlvlStruct, error) {\n\treturn newll(glabel, flags, LflagsDef, nil, false)\n}",
"func NewRegistry() *bsoncodec.Registry {\n\treturn NewRegistryBuilder().Build()\n}",
"func NewAndroidLobApp()(*AndroidLobApp) {\n m := &AndroidLobApp{\n MobileLobApp: *NewMobileLobApp(),\n }\n odataTypeValue := \"#microsoft.graph.androidLobApp\"\n m.SetOdataType(&odataTypeValue)\n return m\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
CreateWin32LobAppRegistryDetectionFromDiscriminatorValue creates a new instance of the appropriate class based on discriminator value
|
func CreateWin32LobAppRegistryDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {
return NewWin32LobAppRegistryDetection(), nil
}
|
[
"func CreateWin32LobAppRegistryRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppRegistryRule(), nil\n}",
"func CreateWin32LobAppProductCodeDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppProductCodeDetection(), nil\n}",
"func CreateWin32LobAppFileSystemDetectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWin32LobAppFileSystemDetection(), nil\n}",
"func CreateWindowsInformationProtectionDeviceRegistrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDeviceRegistration(), nil\n}",
"func NewWin32LobAppRegistryDetection()(*Win32LobAppRegistryDetection) {\n m := &Win32LobAppRegistryDetection{\n Win32LobAppDetection: *NewWin32LobAppDetection(),\n }\n odataTypeValue := \"#microsoft.graph.win32LobAppRegistryDetection\"\n m.SetOdataType(&odataTypeValue)\n return m\n}",
"func CreateAndroidLobAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidLobApp(), nil\n}",
"func CreateAndroidManagedAppRegistrationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewAndroidManagedAppRegistration(), nil\n}",
"func CreateMobileAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.androidForWorkApp\":\n return NewAndroidForWorkApp(), nil\n case \"#microsoft.graph.androidLobApp\":\n return NewAndroidLobApp(), nil\n case \"#microsoft.graph.androidManagedStoreApp\":\n return NewAndroidManagedStoreApp(), nil\n case \"#microsoft.graph.androidManagedStoreWebApp\":\n return NewAndroidManagedStoreWebApp(), nil\n case \"#microsoft.graph.androidStoreApp\":\n return NewAndroidStoreApp(), nil\n case \"#microsoft.graph.iosiPadOSWebClip\":\n return NewIosiPadOSWebClip(), nil\n case \"#microsoft.graph.iosLobApp\":\n return NewIosLobApp(), nil\n case \"#microsoft.graph.iosStoreApp\":\n return NewIosStoreApp(), nil\n case \"#microsoft.graph.iosVppApp\":\n return NewIosVppApp(), nil\n case \"#microsoft.graph.macOSDmgApp\":\n return NewMacOSDmgApp(), nil\n case \"#microsoft.graph.macOSLobApp\":\n return NewMacOSLobApp(), nil\n case \"#microsoft.graph.macOSMdatpApp\":\n return NewMacOSMdatpApp(), nil\n case \"#microsoft.graph.macOSMicrosoftDefenderApp\":\n return NewMacOSMicrosoftDefenderApp(), nil\n case \"#microsoft.graph.macOSMicrosoftEdgeApp\":\n return NewMacOSMicrosoftEdgeApp(), nil\n case \"#microsoft.graph.macOSOfficeSuiteApp\":\n return NewMacOSOfficeSuiteApp(), nil\n case \"#microsoft.graph.macOSPkgApp\":\n return NewMacOSPkgApp(), nil\n case \"#microsoft.graph.macOsVppApp\":\n return NewMacOsVppApp(), nil\n case \"#microsoft.graph.managedAndroidLobApp\":\n return NewManagedAndroidLobApp(), nil\n case \"#microsoft.graph.managedAndroidStoreApp\":\n return NewManagedAndroidStoreApp(), nil\n case \"#microsoft.graph.managedApp\":\n return NewManagedApp(), nil\n case \"#microsoft.graph.managedIOSLobApp\":\n return NewManagedIOSLobApp(), nil\n case \"#microsoft.graph.managedIOSStoreApp\":\n return NewManagedIOSStoreApp(), nil\n case \"#microsoft.graph.managedMobileLobApp\":\n return NewManagedMobileLobApp(), nil\n case \"#microsoft.graph.microsoftStoreForBusinessApp\":\n return NewMicrosoftStoreForBusinessApp(), nil\n case \"#microsoft.graph.mobileLobApp\":\n return NewMobileLobApp(), nil\n case \"#microsoft.graph.officeSuiteApp\":\n return NewOfficeSuiteApp(), nil\n case \"#microsoft.graph.webApp\":\n return NewWebApp(), nil\n case \"#microsoft.graph.win32LobApp\":\n return NewWin32LobApp(), nil\n case \"#microsoft.graph.windowsAppX\":\n return NewWindowsAppX(), nil\n case \"#microsoft.graph.windowsMicrosoftEdgeApp\":\n return NewWindowsMicrosoftEdgeApp(), nil\n case \"#microsoft.graph.windowsMobileMSI\":\n return NewWindowsMobileMSI(), nil\n case \"#microsoft.graph.windowsPhone81AppX\":\n return NewWindowsPhone81AppX(), nil\n case \"#microsoft.graph.windowsPhone81AppXBundle\":\n return NewWindowsPhone81AppXBundle(), nil\n case \"#microsoft.graph.windowsPhone81StoreApp\":\n return NewWindowsPhone81StoreApp(), nil\n case \"#microsoft.graph.windowsPhoneXAP\":\n return NewWindowsPhoneXAP(), nil\n case \"#microsoft.graph.windowsStoreApp\":\n return NewWindowsStoreApp(), nil\n case \"#microsoft.graph.windowsUniversalAppX\":\n return NewWindowsUniversalAppX(), nil\n case \"#microsoft.graph.windowsWebApp\":\n return NewWindowsWebApp(), nil\n case \"#microsoft.graph.winGetApp\":\n return NewWinGetApp(), nil\n }\n }\n }\n }\n return NewMobileApp(), nil\n}",
"func CreateRegistryKeyStateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewRegistryKeyState(), nil\n}",
"func CreateWindowsKioskAutologonFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsKioskAutologon(), nil\n}",
"func CreateApplicationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewApplication(), nil\n}",
"func CreateMacOSLobChildAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewMacOSLobChildApp(), nil\n}",
"func CreateManagedAppProtectionFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.androidManagedAppProtection\":\n return NewAndroidManagedAppProtection(), nil\n case \"#microsoft.graph.defaultManagedAppProtection\":\n return NewDefaultManagedAppProtection(), nil\n case \"#microsoft.graph.iosManagedAppProtection\":\n return NewIosManagedAppProtection(), nil\n case \"#microsoft.graph.targetedManagedAppProtection\":\n return NewTargetedManagedAppProtection(), nil\n }\n }\n }\n }\n return NewManagedAppProtection(), nil\n}",
"func CreateWindowsKioskDesktopAppFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsKioskDesktopApp(), nil\n}",
"func CreateDetectionRuleFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewDetectionRule(), nil\n}",
"func CreateDeviceCompliancePolicyFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n if parseNode != nil {\n mappingValueNode, err := parseNode.GetChildNode(\"@odata.type\")\n if err != nil {\n return nil, err\n }\n if mappingValueNode != nil {\n mappingValue, err := mappingValueNode.GetStringValue()\n if err != nil {\n return nil, err\n }\n if mappingValue != nil {\n switch *mappingValue {\n case \"#microsoft.graph.androidCompliancePolicy\":\n return NewAndroidCompliancePolicy(), nil\n case \"#microsoft.graph.androidWorkProfileCompliancePolicy\":\n return NewAndroidWorkProfileCompliancePolicy(), nil\n case \"#microsoft.graph.iosCompliancePolicy\":\n return NewIosCompliancePolicy(), nil\n case \"#microsoft.graph.macOSCompliancePolicy\":\n return NewMacOSCompliancePolicy(), nil\n case \"#microsoft.graph.windows10CompliancePolicy\":\n return NewWindows10CompliancePolicy(), nil\n case \"#microsoft.graph.windows10MobileCompliancePolicy\":\n return NewWindows10MobileCompliancePolicy(), nil\n case \"#microsoft.graph.windows81CompliancePolicy\":\n return NewWindows81CompliancePolicy(), nil\n case \"#microsoft.graph.windowsPhone81CompliancePolicy\":\n return NewWindowsPhone81CompliancePolicy(), nil\n }\n }\n }\n }\n return NewDeviceCompliancePolicy(), nil\n}",
"func CreateWindowsMalwareInformationFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsMalwareInformation(), nil\n}",
"func CreateWindowsKioskProfileFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsKioskProfile(), nil\n}",
"func CreateWindowsInformationProtectionDataRecoveryCertificateFromDiscriminatorValue(parseNode i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.ParseNode)(i878a80d2330e89d26896388a3f487eef27b0a0e6c010c493bf80be1452208f91.Parsable, error) {\n return NewWindowsInformationProtectionDataRecoveryCertificate(), nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetCheck32BitOn64System gets the check32BitOn64System property value. A value indicating whether this registry path is for checking 32bit app on 64bit system
|
func (m *Win32LobAppRegistryDetection) GetCheck32BitOn64System()(*bool) {
val, err := m.GetBackingStore().Get("check32BitOn64System")
if err != nil {
panic(err)
}
if val != nil {
return val.(*bool)
}
return nil
}
|
[
"func (m *Win32LobAppRegistryRule) GetCheck32BitOn64System()(*bool) {\n return m.check32BitOn64System\n}",
"func (m *Win32LobAppFileSystemDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryRule) SetCheck32BitOn64System(value *bool)() {\n m.check32BitOn64System = value\n}",
"func (m *Win32LobAppRegistryDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppFileSystemDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}",
"func Is64BitOS() bool {\n\t// TODO: implement logic of this method when linux support will be added\n\treturn true\n}",
"func Is64BitCPU() bool {\n\treturn strconv.IntSize == 64\n}",
"func Is32BitWindows(image string) bool {\n\treturn strings.Contains(image, \"-x86\")\n}",
"func (br *bitReader) ReadBitsLE64(bits uint) (n uint64) {\n\tfor bits > br.bits {\n\t\tb, err := br.r.ReadByte()\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\tif err != nil {\n\t\t\tbr.err = err\n\t\t\treturn 0\n\t\t}\n\t\tbr.n <<= 8\n\t\tbr.n |= uint64(b)\n\t\tbr.bits += 8\n\t}\n\tn = (br.n >> (br.bits - bits)) & ((1 << bits) - 1)\n\tbr.bits -= bits\n\treturn\n}",
"func Xlstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_LSTAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"lstat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}",
"func (m *MacOSMinimumOperatingSystem) GetV1012()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_12\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func SysInt64(name string) int64 {\r\n\treturn converter.StrToInt64(SysString(name))\r\n}",
"func Is64(t *Type) bool",
"func (r *AMD64Registers) Get(n int) (uint64, error) {\n\treg := x86asm.Reg(n)\n\tconst (\n\t\tmask8 = 0x000f\n\t\tmask16 = 0x00ff\n\t\tmask32 = 0xffff\n\t)\n\n\tswitch reg {\n\t// 8-bit\n\tcase x86asm.AL:\n\t\treturn r.rax & mask8, nil\n\tcase x86asm.CL:\n\t\treturn r.rcx & mask8, nil\n\tcase x86asm.DL:\n\t\treturn r.rdx & mask8, nil\n\tcase x86asm.BL:\n\t\treturn r.rbx & mask8, nil\n\tcase x86asm.AH:\n\t\treturn (r.rax >> 8) & mask8, nil\n\tcase x86asm.CH:\n\t\treturn (r.rcx >> 8) & mask8, nil\n\tcase x86asm.DH:\n\t\treturn (r.rdx >> 8) & mask8, nil\n\tcase x86asm.BH:\n\t\treturn (r.rbx >> 8) & mask8, nil\n\tcase x86asm.SPB:\n\t\treturn r.rsp & mask8, nil\n\tcase x86asm.BPB:\n\t\treturn r.rbp & mask8, nil\n\tcase x86asm.SIB:\n\t\treturn r.rsi & mask8, nil\n\tcase x86asm.DIB:\n\t\treturn r.rdi & mask8, nil\n\tcase x86asm.R8B:\n\t\treturn r.r8 & mask8, nil\n\tcase x86asm.R9B:\n\t\treturn r.r9 & mask8, nil\n\tcase x86asm.R10B:\n\t\treturn r.r10 & mask8, nil\n\tcase x86asm.R11B:\n\t\treturn r.r11 & mask8, nil\n\tcase x86asm.R12B:\n\t\treturn r.r12 & mask8, nil\n\tcase x86asm.R13B:\n\t\treturn r.r13 & mask8, nil\n\tcase x86asm.R14B:\n\t\treturn r.r14 & mask8, nil\n\tcase x86asm.R15B:\n\t\treturn r.r15 & mask8, nil\n\n\t// 16-bit\n\tcase x86asm.AX:\n\t\treturn r.rax & mask16, nil\n\tcase x86asm.CX:\n\t\treturn r.rcx & mask16, nil\n\tcase x86asm.DX:\n\t\treturn r.rdx & mask16, nil\n\tcase x86asm.BX:\n\t\treturn r.rbx & mask16, nil\n\tcase x86asm.SP:\n\t\treturn r.rsp & mask16, nil\n\tcase x86asm.BP:\n\t\treturn r.rbp & mask16, nil\n\tcase x86asm.SI:\n\t\treturn r.rsi & mask16, nil\n\tcase x86asm.DI:\n\t\treturn r.rdi & mask16, nil\n\tcase x86asm.R8W:\n\t\treturn r.r8 & mask16, nil\n\tcase x86asm.R9W:\n\t\treturn r.r9 & mask16, nil\n\tcase x86asm.R10W:\n\t\treturn r.r10 & mask16, nil\n\tcase x86asm.R11W:\n\t\treturn r.r11 & mask16, nil\n\tcase x86asm.R12W:\n\t\treturn r.r12 & mask16, nil\n\tcase x86asm.R13W:\n\t\treturn r.r13 & mask16, nil\n\tcase x86asm.R14W:\n\t\treturn r.r14 & mask16, nil\n\tcase x86asm.R15W:\n\t\treturn r.r15 & mask16, nil\n\n\t// 32-bit\n\tcase x86asm.EAX:\n\t\treturn r.rax & mask32, nil\n\tcase x86asm.ECX:\n\t\treturn r.rcx & mask32, nil\n\tcase x86asm.EDX:\n\t\treturn r.rdx & mask32, nil\n\tcase x86asm.EBX:\n\t\treturn r.rbx & mask32, nil\n\tcase x86asm.ESP:\n\t\treturn r.rsp & mask32, nil\n\tcase x86asm.EBP:\n\t\treturn r.rbp & mask32, nil\n\tcase x86asm.ESI:\n\t\treturn r.rsi & mask32, nil\n\tcase x86asm.EDI:\n\t\treturn r.rdi & mask32, nil\n\tcase x86asm.R8L:\n\t\treturn r.r8 & mask32, nil\n\tcase x86asm.R9L:\n\t\treturn r.r9 & mask32, nil\n\tcase x86asm.R10L:\n\t\treturn r.r10 & mask32, nil\n\tcase x86asm.R11L:\n\t\treturn r.r11 & mask32, nil\n\tcase x86asm.R12L:\n\t\treturn r.r12 & mask32, nil\n\tcase x86asm.R13L:\n\t\treturn r.r13 & mask32, nil\n\tcase x86asm.R14L:\n\t\treturn r.r14 & mask32, nil\n\tcase x86asm.R15L:\n\t\treturn r.r15 & mask32, nil\n\n\t// 64-bit\n\tcase x86asm.RAX:\n\t\treturn r.rax, nil\n\tcase x86asm.RCX:\n\t\treturn r.rcx, nil\n\tcase x86asm.RDX:\n\t\treturn r.rdx, nil\n\tcase x86asm.RBX:\n\t\treturn r.rbx, nil\n\tcase x86asm.RSP:\n\t\treturn r.rsp, nil\n\tcase x86asm.RBP:\n\t\treturn r.rbp, nil\n\tcase x86asm.RSI:\n\t\treturn r.rsi, nil\n\tcase x86asm.RDI:\n\t\treturn r.rdi, nil\n\tcase x86asm.R8:\n\t\treturn r.r8, nil\n\tcase x86asm.R9:\n\t\treturn r.r9, nil\n\tcase x86asm.R10:\n\t\treturn r.r10, nil\n\tcase x86asm.R11:\n\t\treturn r.r11, nil\n\tcase x86asm.R12:\n\t\treturn r.r12, nil\n\tcase x86asm.R13:\n\t\treturn r.r13, nil\n\tcase x86asm.R14:\n\t\treturn r.r14, nil\n\tcase x86asm.R15:\n\t\treturn r.r15, nil\n\t}\n\n\treturn 0, proc.ErrUnknownRegister\n}",
"func (m *MacOSMinimumOperatingSystem) GetV110()(*bool) {\n val, err := m.GetBackingStore().Get(\"v11_0\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (h *ZipDirEntry) isZip64() bool {\n\treturn h.CompressedSize64 >= uint32max || h.UncompressedSize64 >= uint32max\n}",
"func (s *SupportedInstanceType) SetIs64BitsOnly(v bool) *SupportedInstanceType {\n\ts.Is64BitsOnly = &v\n\treturn s\n}",
"func (m *MacOSMinimumOperatingSystem) GetV1011()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_11\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (m *MacOSMinimumOperatingSystem) GetV108()(*bool) {\n val, err := m.GetBackingStore().Get(\"v10_8\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetDetectionType gets the detectionType property value. Contains all supported registry data detection type.
|
func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {
val, err := m.GetBackingStore().Get("detectionType")
if err != nil {
panic(err)
}
if val != nil {
return val.(*Win32LobAppRegistryDetectionType)
}
return nil
}
|
[
"func (m *Win32LobAppFileSystemDetection) GetDetectionType()(*Win32LobAppFileSystemDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppFileSystemDetectionType)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *ServicePrincipalRiskDetection) GetDetectionTimingType()(*RiskDetectionTimingType) {\n val, err := m.GetBackingStore().Get(\"detectionTimingType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RiskDetectionTimingType)\n }\n return nil\n}",
"func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (registry *Registry) GetType() string {\n\treturn \"Microsoft.ContainerRegistry/registries\"\n}",
"func (o *RegistryConfiguration) GetRegistryType() string {\n\tif o == nil || o.RegistryType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.RegistryType\n}",
"func (m *RegistryValueEvidence) GetRegistryValueType()(*string) {\n val, err := m.GetBackingStore().Get(\"registryValueType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func GetType() string {\n\treturn kind\n}",
"func (o *HyperflexHealthCheckDefinition) GetSupportedHypervisorType() string {\n\tif o == nil || o.SupportedHypervisorType == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.SupportedHypervisorType\n}",
"func (r *Registration) GetRegistryAuthorizationType() string {\n\tvar auth string\n\tif r.Metadata != nil && r.Metadata.Properties != nil {\n\t\tif v, ok := r.Metadata.Properties[authorizationType]; ok {\n\t\t\tauth = v\n\t\t}\n\t}\n\n\tif auth != authorizationBasic && auth != authorizationBearer {\n\t\tauth = authorizationBasic\n\t}\n\n\treturn auth\n}",
"func GetDiscoveryType(foreignCluster *discoveryv1alpha1.ForeignCluster) discovery.Type {\n\tlabels := foreignCluster.GetLabels()\n\tif l, ok := labels[discovery.DiscoveryTypeLabel]; ok {\n\t\treturn discovery.Type(l)\n\t}\n\treturn discovery.ManualDiscovery\n}",
"func (r Virtual_Guest) GetGpuType() (resp string, err error) {\n\terr = r.Session.DoRequest(\"SoftLayer_Virtual_Guest\", \"getGpuType\", nil, &r.Options, &resp)\n\treturn\n}",
"func GetTypeEnum(val reflect.Type) (ret int, err error) {\n\tswitch val.Kind() {\n\tcase reflect.Int8:\n\t\tret = TypeBitField\n\tcase reflect.Uint8:\n\t\tret = TypePositiveBitField\n\tcase reflect.Int16:\n\t\tret = TypeSmallIntegerField\n\tcase reflect.Uint16:\n\t\tret = TypePositiveSmallIntegerField\n\tcase reflect.Int32:\n\t\tret = TypeInteger32Field\n\tcase reflect.Uint32:\n\t\tret = TypePositiveInteger32Field\n\tcase reflect.Int64:\n\t\tret = TypeBigIntegerField\n\tcase reflect.Uint64:\n\t\tret = TypePositiveBigIntegerField\n\tcase reflect.Int:\n\t\tret = TypeIntegerField\n\tcase reflect.Uint:\n\t\tret = TypePositiveIntegerField\n\tcase reflect.Float32:\n\t\tret = TypeFloatField\n\tcase reflect.Float64:\n\t\tret = TypeDoubleField\n\tcase reflect.Bool:\n\t\tret = TypeBooleanField\n\tcase reflect.String:\n\t\tret = TypeStringField\n\tcase reflect.Struct:\n\t\tswitch val.String() {\n\t\tcase \"time.Time\":\n\t\t\tret = TypeDateTimeField\n\t\tdefault:\n\t\t\tret = TypeStructField\n\t\t}\n\tcase reflect.Slice:\n\t\tret = TypeSliceField\n\tdefault:\n\t\terr = fmt.Errorf(\"unsupport field type:%v\", val.String())\n\t}\n\n\treturn\n}",
"func (m *Device) GetKind() (val string, set bool) {\n\tif m.Kind == nil {\n\t\treturn\n\t}\n\n\treturn *m.Kind, true\n}",
"func (cr *CSIVXFlexOS) GetDriverType() DriverType {\n\treturn \"vxflexos\"\n}",
"func GetBuiltinProcessorType(programHash hashing.HashValue) (string, bool) {\n\tif _, err := core.GetProcessor(programHash); err == nil {\n\t\treturn core.VMType, true\n\t}\n\tif _, ok := native.GetProcessor(programHash); ok {\n\t\treturn native.VMType, true\n\t}\n\treturn \"\", false\n}",
"func (o *MonitorSearchResult) GetClassification() string {\n\tif o == nil || o.Classification == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Classification\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetDetectionValue gets the detectionValue property value. The registry detection value
|
func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {
val, err := m.GetBackingStore().Get("detectionValue")
if err != nil {
panic(err)
}
if val != nil {
return val.(*string)
}
return nil
}
|
[
"func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *RegistryValueEvidence) GetRegistryValue()(*string) {\n val, err := m.GetBackingStore().Get(\"registryValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryRule) GetComparisonValue()(*string) {\n return m.comparisonValue\n}",
"func (m *Win32LobAppRegistryDetection) GetValueName()(*string) {\n val, err := m.GetBackingStore().Get(\"valueName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *DeviceComplianceScriptDeviceState) GetDetectionState()(*RunState) {\n val, err := m.GetBackingStore().Get(\"detectionState\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RunState)\n }\n return nil\n}",
"func (m *DeviceHealthScriptPolicyState) GetDetectionState()(*RunState) {\n val, err := m.GetBackingStore().Get(\"detectionState\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*RunState)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}",
"func (m *FileEvidence) GetDetectionStatus()(*DetectionStatus) {\n val, err := m.GetBackingStore().Get(\"detectionStatus\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*DetectionStatus)\n }\n return nil\n}",
"func (m *RegistryValueEvidence) GetRegistryValueName()(*string) {\n val, err := m.GetBackingStore().Get(\"registryValueName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryRule) GetValueName()(*string) {\n return m.valueName\n}",
"func (rule *GameRule) GetValue() interface{} {\n\treturn rule.value\n}",
"func (m *RegistryValueEvidence) GetRegistryValueType()(*string) {\n val, err := m.GetBackingStore().Get(\"registryValueType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (o CSIIsilonSpecDriverNodeTolerationsOutput) Value() pulumi.StringPtrOutput {\n\treturn o.ApplyT(func(v CSIIsilonSpecDriverNodeTolerations) *string { return v.Value }).(pulumi.StringPtrOutput)\n}",
"func (g *Pin) GetValue()(val bool){\n\tif g.mode == OUTPUT {\n\t\treturn g.value\n\t}\n\tbuf := make([]byte,1,1)\n\tattempts := 0\n\tfor success:=false; success != true; {\n\t\tfile,err := os.OpenFile(g.path+VALUE_FILE_NAME,os.O_RDONLY,os.ModeTemporary)\n\t\tdefer file.Close()\n\t\tattempts++\n\t\tif err != nil {\n\t\t\tif attempts > FILE_ACCESS_BOUND {\n\t\t\t\tlog.Fatal(err)\n\t\t\t}\n\t\t} else {\n\t\t\tfile.Read(buf)\n\t\t\tsuccess = true\n\t\t}\n\t}\n\tfile_val,_ := strconv.Atoi(string(buf[0]))\n\n\tif g.activeLow {\n\t\tif file_val == 1 {\n\t\t\tval = true\n\t\t} else {\n\t\t\tval = false\n\t\t}\n\t} else {\n\t\tif file_val == 1 {\n\t\t\tval = false\n\t\t} else {\n\t\t\tval = true\n\t\t}\n\t}\n\n\tg.value = val\n\treturn val\n}",
"func (g UGaugeSnapshot) Value() uint64 { return uint64(g) }",
"func (dv *BoolDecisionValue) Value() ref.Val {\n\treturn dv.value\n}",
"func (a *Awaitility) GetMetricValue(t *testing.T, family string, labelAndValues ...string) float64 {\n\tvalue, err := metrics.GetMetricValue(a.RestConfig, a.MetricsURL, family, labelAndValues)\n\trequire.NoError(t, err)\n\treturn value\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetKeyPath gets the keyPath property value. The registry key path to detect Win32 Line of Business (LoB) app
|
func (m *Win32LobAppRegistryDetection) GetKeyPath()(*string) {
val, err := m.GetBackingStore().Get("keyPath")
if err != nil {
panic(err)
}
if val != nil {
return val.(*string)
}
return nil
}
|
[
"func (m *Win32LobAppRegistryRule) GetKeyPath()(*string) {\n return m.keyPath\n}",
"func (m *Win32LobAppRegistryRule) SetKeyPath(value *string)() {\n m.keyPath = value\n}",
"func (m *WindowsKioskDesktopApp) GetPath()(*string) {\n val, err := m.GetBackingStore().Get(\"path\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (_this *IDBObjectStore) KeyPath() js.Value {\n\tvar ret js.Value\n\tvalue := _this.Value_JS.Get(\"keyPath\")\n\tret = value\n\treturn ret\n}",
"func (m *Win32LobAppRegistryDetection) SetKeyPath(value *string)() {\n err := m.GetBackingStore().Set(\"keyPath\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppFileSystemDetection) GetPath()(*string) {\n val, err := m.GetBackingStore().Get(\"path\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func getKeyPath(name string) string {\n\treturn configDir + \"/hil-vpn-\" + name + \".key\"\n}",
"func GetBinaryPathKey(cookie uint32, path string) (unsafe.Pointer, error) {\n\tbpk := BinaryPathKey{\n\t\tCookie: cookie,\n\t}\n\tcopy(bpk.Path[:], path)\n\tkey, err := utils.InterfaceToBytes(bpk)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn unsafe.Pointer(&key[0]), nil\n}",
"func GetKeysPath() string {\n\treturn path.Join(viper.GetString(\"ca_root\"), \"keys\")\n}",
"func (u Unit) pathKey(inputPath string) string {\n\troot := path.Clean(u.Proto.GetWorkingDirectory())\n\tif root == \"\" {\n\t\troot = \"/\"\n\t}\n\n\tif path.IsAbs(inputPath) {\n\t\tinputPath = path.Clean(inputPath)\n\t} else {\n\t\tinputPath = path.Join(root, inputPath)\n\t}\n\n\tvar prefix string\n\tif root == \"/\" {\n\t\tprefix = root\n\t} else {\n\t\tprefix = root + \"/\"\n\t}\n\treturn strings.TrimPrefix(inputPath, prefix)\n}",
"func PathKey(fn string) string {\n\treturn fn[:len(fn)-len(filepath.Ext(fn))]\n}",
"func KeyFromPath(p string) string {\n\t_, name := filepath.Split(p)\n\treturn name\n}",
"func (_this *IDBIndex) KeyPath() js.Value {\n\tvar ret js.Value\n\tvalue := _this.Value_JS.Get(\"keyPath\")\n\tret = value\n\treturn ret\n}",
"func (rc RC) Path(key string) (string, bool) {\n\tv, ok := rc[key]\n\tif !ok {\n\t\treturn \"\", false\n\t} else if t := strings.TrimPrefix(v, \"~\"); t != v && (t == \"\" || t[0] == '/') {\n\t\treturn os.Getenv(\"HOME\") + t, true\n\t}\n\treturn v, true\n}",
"func (pp *ProcessProfile) GetPathKeyValue(cookie keyvalue.Cookie) *keyvalue.KeyValue {\n\tpathB := [kernel.PathMax]byte{}\n\tcopy(pathB[:], pp.BinaryPath)\n\treturn &keyvalue.KeyValue{\n\t\tKey: &keyvalue.BinaryPathKey{\n\t\t\tCookie: cookie,\n\t\t\tPath: pathB,\n\t\t},\n\t\tValue: &keyvalue.CookieValue{\n\t\t\tCookie: pp.binaryPathID,\n\t\t},\n\t}\n}",
"func GetKeysPath() string {\n\tlocation := os.Getenv(\"SSH_KEYS_LOCATION\")\n\tif !strings.HasSuffix(location, fmt.Sprintf(\"%c\", os.PathSeparator)) {\n\t\tlocation += fmt.Sprintf(\"%c\", os.PathSeparator)\n\t}\n\treturn location\n}",
"func getRegistryStringKey(path string, key string) (string, error) {\n\tk, err := registry.OpenKey(registry.LOCAL_MACHINE, path, registry.QUERY_VALUE)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer k.Close()\n\n\ts, _, err := k.GetStringValue(key)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\treturn s, nil\n}",
"func GetKeyPath(u *user.User) (path string, err error) {\n\tif u == nil {\n\t\tif u, err = user.Current(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t}\n\n\tpath = filepath.Join(u.HomeDir, DefaultKeyDir)\n\tif _, err := os.Stat(path); os.IsNotExist(err) {\n\t\treturn \"\", err\n\t}\n\n\treturn path, nil\n}",
"func (m *RegistryValueEvidence) GetRegistryKey()(*string) {\n val, err := m.GetBackingStore().Get(\"registryKey\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetValueName gets the valueName property value. The registry value name
|
func (m *Win32LobAppRegistryDetection) GetValueName()(*string) {
val, err := m.GetBackingStore().Get("valueName")
if err != nil {
panic(err)
}
if val != nil {
return val.(*string)
}
return nil
}
|
[
"func (m *Win32LobAppRegistryRule) GetValueName()(*string) {\n return m.valueName\n}",
"func (m *RegistryValueEvidence) GetRegistryValueName()(*string) {\n val, err := m.GetBackingStore().Get(\"registryValueName\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *RegistryKeyState) GetValueName()(*string) {\n return m.valueName\n}",
"func GetNameVal(obj PdfObject) (val string, found bool) {\n\tname, found := TraceToDirectObject(obj).(*PdfObjectName)\n\tif found {\n\t\treturn string(*name), true\n\t}\n\treturn\n}",
"func (p ByName) ValueName() string { return p.valueName }",
"func (m *Win32LobAppRegistryRule) SetValueName(value *string)() {\n m.valueName = value\n}",
"func (s *Identity) GetValue(name string) *Identity {\n\tfor _, v := range s.Values {\n\t\tif v.Name == name {\n\t\t\treturn v\n\t\t}\n\t}\n\treturn nil\n}",
"func (typeGlobal) GetName(th *Thread, name string) Value {\n\treturn Global.Get(th, Global.Num(name))\n}",
"func (ru reflectionUtil) GetValueByName(target interface{}, fieldName string) interface{} {\n\ttargetValue := ru.ReflectValue(target)\n\tfield := targetValue.FieldByName(fieldName)\n\treturn field.Interface()\n}",
"func (r *Record) Get(name string) (Value, bool) {\n\tvalue, ok := r.nameValueMap[name]\n\treturn value, ok\n}",
"func getResourceNameByValue(value interface{}) string {\n\t// assume it's ResourceNamer -- get resource name\n\tif inter, ok := value.(admin.ResourceNamer); value != nil && ok {\n\t\treturn inter.ResourceName()\n\t}\n\n\t// last resort: raw struct name\n\treturn reflect.Indirect(reflect.ValueOf(value)).Type().String()\n}",
"func (values *Values) GetNamed(v interface{}, name string) error {\n\tinstanceSetter, err := GetNamedSetter(v, name)\n\tif err != nil {\n\t\treturn err\n\t}\n\ttyp := instanceSetter.Type()\n\tinstance := values.get(typ, name)\n\tif instance == nil {\n\t\tif instance = values.getParent(typ, name); instance == nil {\n\t\t\treturn errInstanceNotFound(typ, name)\n\t\t}\n\t}\n\tinstanceSetter.Set(*instance)\n\treturn nil\n}",
"func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() {\n err := m.GetBackingStore().Set(\"valueName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (er *Registry) GetName() string {\n\treturn er.name\n}",
"func (v *Variable) GetValue() interface{} {\n\treturn v.GetName()\n}",
"func (t *Target) GetValue(name string) string {\n\treturn t.labels.Get(name)\n}",
"func (reg *Registry) GetName() string {\n\treturn reg.apiRegistry.GetName()\n}",
"func (s *Section) GetValue(name string) (string, bool) {\n\tfor _, e := range s.Entries {\n\t\tif e.Key == name {\n\t\t\treturn e.Value, true\n\t\t}\n\t}\n\treturn \"\", false\n}",
"func (v Value) Name() string {\n\treturn v.name\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetCheck32BitOn64System sets the check32BitOn64System property value. A value indicating whether this registry path is for checking 32bit app on 64bit system
|
func (m *Win32LobAppRegistryDetection) SetCheck32BitOn64System(value *bool)() {
err := m.GetBackingStore().Set("check32BitOn64System", value)
if err != nil {
panic(err)
}
}
|
[
"func (m *Win32LobAppRegistryRule) SetCheck32BitOn64System(value *bool)() {\n m.check32BitOn64System = value\n}",
"func (m *Win32LobAppFileSystemDetection) SetCheck32BitOn64System(value *bool)() {\n err := m.GetBackingStore().Set(\"check32BitOn64System\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryRule) GetCheck32BitOn64System()(*bool) {\n return m.check32BitOn64System\n}",
"func (m *Win32LobAppRegistryDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func (m *Win32LobAppFileSystemDetection) GetCheck32BitOn64System()(*bool) {\n val, err := m.GetBackingStore().Get(\"check32BitOn64System\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*bool)\n }\n return nil\n}",
"func Is64BitOS() bool {\n\t// TODO: implement logic of this method when linux support will be added\n\treturn true\n}",
"func (s *SupportedInstanceType) SetIs64BitsOnly(v bool) *SupportedInstanceType {\n\ts.Is64BitsOnly = &v\n\treturn s\n}",
"func Is64BitCPU() bool {\n\treturn strconv.IntSize == 64\n}",
"func (br *bitReader) ReadBitsLE64(bits uint) (n uint64) {\n\tfor bits > br.bits {\n\t\tb, err := br.r.ReadByte()\n\t\tif err == io.EOF {\n\t\t\terr = io.ErrUnexpectedEOF\n\t\t}\n\t\tif err != nil {\n\t\t\tbr.err = err\n\t\t\treturn 0\n\t\t}\n\t\tbr.n <<= 8\n\t\tbr.n |= uint64(b)\n\t\tbr.bits += 8\n\t}\n\tn = (br.n >> (br.bits - bits)) & ((1 << bits) - 1)\n\tbr.bits -= bits\n\treturn\n}",
"func Xlstat64(tls TLS, file, buf uintptr) int32 {\n\tr, _, err := syscall.Syscall(syscall.SYS_LSTAT64, file, buf, 0)\n\tif strace {\n\t\tfmt.Fprintf(TraceWriter, \"lstat(%q, %#x) %v %v\\n\", GoString(file), buf, r, err)\n\t}\n\tif err != 0 {\n\t\ttls.setErrno(err)\n\t}\n\treturn int32(r)\n}",
"func SetArm64(strArch string, bigEndian bool) Machine {\n var mc Machine\n mc.bit = 64\n mc.sp = uc.ARM64_REG_SP\n mc.bp = uc.ARM64_REG_X29\n mc.start = 0x0000\n\n if bigEndian {\n // fixme: arm64be assemble mode with keystone\n// mc.ks, _ = keystone.New(keystone.ARCH_ARM, keystone.MODE_BIG_ENDIAN)\n mc.ks, _ = keystone.New(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)\n mc.mu, _ = uc.NewUnicorn(uc.ARCH_ARM64, uc.MODE_ARM + uc.MODE_BIG_ENDIAN)\n mc.oldMu, _ = uc.NewUnicorn(uc.ARCH_ARM64, uc.MODE_ARM + uc.MODE_BIG_ENDIAN)\n\n mc.cs, _ = gapstone.New(\n gapstone.CS_ARCH_ARM64,\n gapstone.CS_MODE_BIG_ENDIAN,\n )\n } else {\n mc.ks, _ = keystone.New(keystone.ARCH_ARM64, keystone.MODE_LITTLE_ENDIAN)\n mc.mu, _ = uc.NewUnicorn(uc.ARCH_ARM64, uc.MODE_ARM + uc.MODE_LITTLE_ENDIAN)\n mc.oldMu, _ = uc.NewUnicorn(uc.ARCH_ARM64, uc.MODE_ARM + uc.MODE_LITTLE_ENDIAN)\n\n mc.cs, _ = gapstone.New(\n gapstone.CS_ARCH_ARM64,\n gapstone.CS_MODE_LITTLE_ENDIAN,\n )\n }\n mc.Prompt = \"(\" + strArch + \")> \"\n\n mc.mu.MemMap(0x0000, 0x2000)\n mc.mu.RegWrite(mc.sp, 0x1000)\n mc.mu.RegWrite(mc.bp, 0x8000)\n\n mc.oldCtx, _ = mc.mu.ContextSave(nil)\n\n mc.regOrder = []string{\n \"x0\", \" x8\", \"x1\", \" x9\",\n \"x2\", \"x10\", \"x3\", \"x11\",\n \"x4\", \"x12\", \"x5\", \"x13\",\n \"x6\", \" sp\", \"x7\", \" pc\",\n \"nzcv\",\n }\n mc.regs = map[string]int{\n \"x0\" : uc.ARM64_REG_X0,\n \"x1\" : uc.ARM64_REG_X1,\n \"x2\" : uc.ARM64_REG_X2,\n \"x3\" : uc.ARM64_REG_X3,\n \"x4\" : uc.ARM64_REG_X4,\n \"x5\" : uc.ARM64_REG_X5,\n \"x6\" : uc.ARM64_REG_X6,\n \"x7\" : uc.ARM64_REG_X7,\n \" x8\" : uc.ARM64_REG_X8,\n \" x9\" : uc.ARM64_REG_X9,\n \"x10\" : uc.ARM64_REG_X10,\n \"x11\" : uc.ARM64_REG_X11,\n \"x12\" : uc.ARM64_REG_X12,\n \"x13\" : uc.ARM64_REG_X13,\n \"x14\" : uc.ARM64_REG_X14,\n \"x15\" : uc.ARM64_REG_X15,\n \"x16\" : uc.ARM64_REG_X16,\n \"x17\" : uc.ARM64_REG_X17,\n \"x18\" : uc.ARM64_REG_X18,\n \"x19\" : uc.ARM64_REG_X19,\n \"x20\" : uc.ARM64_REG_X20,\n \"x21\" : uc.ARM64_REG_X21,\n \"x22\" : uc.ARM64_REG_X22,\n \"x23\" : uc.ARM64_REG_X23,\n \"x24\" : uc.ARM64_REG_X24,\n \"x25\" : uc.ARM64_REG_X25,\n \"x26\" : uc.ARM64_REG_X26,\n \"x27\" : uc.ARM64_REG_X27,\n \"x28\" : uc.ARM64_REG_X28,\n \"x29\" : uc.ARM64_REG_X29, // fix: frame(base) pointer?\n \"x30\" : uc.ARM64_REG_X30,\n \" sp\" : uc.ARM64_REG_SP,\n \" pc\" : uc.ARM64_REG_PC,\n \"nzcv\" : uc.ARM64_REG_NZCV,\n }\n return mc\n}",
"func Is32BitWindows(image string) bool {\n\treturn strings.Contains(image, \"-x86\")\n}",
"func PtraceSetRegSetArm64(pid, addr int, regs *PtraceRegsArm64) error {\n\tiovec := Iovec{(*byte)(unsafe.Pointer(regs)), uint64(unsafe.Sizeof(*regs))}\n\treturn ptracePtr(PTRACE_SETREGSET, pid, uintptr(addr), unsafe.Pointer(&iovec))\n}",
"func Is64(t *Type) bool",
"func PtraceSetRegsMips64le(pid int, regs *PtraceRegsMips64le) error {\r\n\treturn ptrace(PTRACE_SETREGS, pid, 0, uintptr(unsafe.Pointer(regs)))\r\n}",
"func PtraceGetRegSetArm64(pid, addr int, regsout *PtraceRegsArm64) error {\n\tiovec := Iovec{(*byte)(unsafe.Pointer(regsout)), uint64(unsafe.Sizeof(*regsout))}\n\treturn ptracePtr(PTRACE_GETREGSET, pid, uintptr(addr), unsafe.Pointer(&iovec))\n}",
"func (nb *Nbin) Add64(val uint64, nbits uint) {\n\tt := new(big.Int)\n\tt.SetUint64(val)\n\to := nb.Bites.Lsh(&nb.Bites, nbits)\n\tnb.Bites = *nb.Bites.Add(o, t)\n}",
"func TestSet64(t *testing.T) {\n\thm, _ := NewHashMap(64)\n\ttestSetN(testN, hm)\n}",
"func test64BitConstMult(t *testing.T) {\n\twant := int64(103079215109)\n\tif got := test64BitConstMult_ssa(1, 2); want != got {\n\t\tt.Errorf(\"test64BitConstMult failed, wanted %d got %d\", want, got)\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetDetectionType sets the detectionType property value. Contains all supported registry data detection type.
|
func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {
err := m.GetBackingStore().Set("detectionType", value)
if err != nil {
panic(err)
}
}
|
[
"func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *ServicePrincipalRiskDetection) SetDetectionTimingType(value *RiskDetectionTimingType)() {\n err := m.GetBackingStore().Set(\"detectionTimingType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (I *Detector) setRuleType() {\n\tif len(I.KDict) == 0 && len(I.KReg) == 0 { // no key rules means RuleType is VALUE\n\t\tI.RuleType = RULE_TYPE_VALUE\n\t} else { // RyleType is KV\n\t\tI.RuleType = RULE_TYPE_KV\n\t}\n}",
"func SetDiscoveryType(foreignCluster *discoveryv1alpha1.ForeignCluster, discoveryType discovery.Type) {\n\tlabels := foreignCluster.GetLabels()\n\tif labels == nil {\n\t\tlabels = map[string]string{}\n\t}\n\tlabels[discovery.DiscoveryTypeLabel] = string(discoveryType)\n\tforeignCluster.SetLabels(labels)\n}",
"func (m *Win32LobAppRegistryDetection) GetDetectionType()(*Win32LobAppRegistryDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppRegistryDetectionType)\n }\n return nil\n}",
"func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (n *Node) SetType(t provider.ResourceType) {\n\tn.nodeType = &t\n}",
"func (m *DeviceComplianceScriptDeviceState) SetDetectionState(value *RunState)() {\n err := m.GetBackingStore().Set(\"detectionState\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *FileEvidence) SetDetectionStatus(value *DetectionStatus)() {\n err := m.GetBackingStore().Set(\"detectionStatus\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *DeviceManagementApplicabilityRuleOsEdition) SetRuleType(value *DeviceManagementApplicabilityRuleType)() {\n err := m.GetBackingStore().Set(\"ruleType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func DetectType(typ api.CQLinterType, project api.Project) bool {\n\tlinter, ok := ByType[typ]\n\treturn ok && DetectLinter(linter, project)\n}",
"func (n *node) SetType(t string) {\n\tn.nodeType = t\n}",
"func (i *CreationInfo) SetType(str string) {\n\tC.alt_IResource_CreationInfo_SetType(i.altInfoPtr, C.CString(str))\n\ti.Type = str\n}",
"func (m *Win32LobAppFileSystemDetection) GetDetectionType()(*Win32LobAppFileSystemDetectionType) {\n val, err := m.GetBackingStore().Get(\"detectionType\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*Win32LobAppFileSystemDetectionType)\n }\n return nil\n}",
"func (m *SensitiveType) SetClassificationMethod(value *ClassificationMethod)() {\n err := m.GetBackingStore().Set(\"classificationMethod\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (s UserSet) SetType(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Type\", \"type\"), value)\n}",
"func (d UserData) SetType(value string) m.UserData {\n\td.ModelData.Set(models.NewFieldName(\"Type\", \"type\"), value)\n\treturn d\n}",
"func (m *ItemReference) SetDriveType(value *string)() {\n m.driveType = value\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetDetectionValue sets the detectionValue property value. The registry detection value
|
func (m *Win32LobAppRegistryDetection) SetDetectionValue(value *string)() {
err := m.GetBackingStore().Set("detectionValue", value)
if err != nil {
panic(err)
}
}
|
[
"func (m *Win32LobAppFileSystemDetection) SetDetectionValue(value *string)() {\n err := m.GetBackingStore().Set(\"detectionValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *DeviceComplianceScriptDeviceState) SetDetectionState(value *RunState)() {\n err := m.GetBackingStore().Set(\"detectionState\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *RegistryValueEvidence) SetRegistryValue(value *string)() {\n err := m.GetBackingStore().Set(\"registryValue\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryDetection) SetDetectionType(value *Win32LobAppRegistryDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *DeviceHealthScriptPolicyState) SetDetectionState(value *RunState)() {\n err := m.GetBackingStore().Set(\"detectionState\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *FileEvidence) SetDetectionStatus(value *DetectionStatus)() {\n err := m.GetBackingStore().Set(\"detectionStatus\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryRule) SetComparisonValue(value *string)() {\n m.comparisonValue = value\n}",
"func (m *Win32LobAppFileSystemDetection) SetDetectionType(value *Win32LobAppFileSystemDetectionType)() {\n err := m.GetBackingStore().Set(\"detectionType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func setValue(value []byte) error {\n\terr := recognizersStore.Set(recognizersKey, string(value))\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\n\thashVal := md5.Sum(value)\n\tcalculatedHash := hex.EncodeToString(hashVal[:])\n\tlog.Info(\"Updating hash: \" + calculatedHash)\n\terr = recognizersStore.Set(hashKey, calculatedHash)\n\tif err != nil {\n\t\tlog.Error(err.Error())\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func (m *DetectionRule) SetDetectionAction(value DetectionActionable)() {\n err := m.GetBackingStore().Set(\"detectionAction\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *RegistryValueEvidence) SetRegistryValueType(value *string)() {\n err := m.GetBackingStore().Set(\"registryValueType\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *RegistryValueEvidence) SetRegistryValueName(value *string)() {\n err := m.GetBackingStore().Set(\"registryValueName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func SetFaceDetection(faceDetection bool) {\n\tif faceDetection == settings.FaceDetectionSetting {\n\t\treturn\n\t}\n\tsettings.FaceDetectionSetting = faceDetection\n\n\tgo saveToFile()\n}",
"func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() {\n err := m.GetBackingStore().Set(\"valueName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *WindowsMalwareCategoryCount) SetActiveMalwareDetectionCount(value *int32)() {\n err := m.GetBackingStore().Set(\"activeMalwareDetectionCount\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (r *DNSResolvers) SetValue(val interface{}) {\n\t*r = val.(DNSResolvers)\n}",
"func (m *Win32LobAppFileSystemDetection) GetDetectionValue()(*string) {\n val, err := m.GetBackingStore().Get(\"detectionValue\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *ServicePrincipalRiskDetection) SetDetectionTimingType(value *RiskDetectionTimingType)() {\n err := m.GetBackingStore().Set(\"detectionTimingType\", value)\n if err != nil {\n panic(err)\n }\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetKeyPath sets the keyPath property value. The registry key path to detect Win32 Line of Business (LoB) app
|
func (m *Win32LobAppRegistryDetection) SetKeyPath(value *string)() {
err := m.GetBackingStore().Set("keyPath", value)
if err != nil {
panic(err)
}
}
|
[
"func (m *Win32LobAppRegistryRule) SetKeyPath(value *string)() {\n m.keyPath = value\n}",
"func (m *WindowsKioskDesktopApp) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}",
"func SetKeysPath(s string) func(*SAMMultiProxy) error {\n\treturn func(c *SAMMultiProxy) error {\n\t\tc.Conf.KeyFilePath = s\n\t\treturn nil\n\t}\n}",
"func (m *Win32LobAppFileSystemDetection) SetPath(value *string)() {\n err := m.GetBackingStore().Set(\"path\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (k *Keys) SealedKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\n\treturn path.Join(k.dir, SealedKeysetPath)\n}",
"func (k *Keys) PBEKeysetPath() string {\n\tif k.dir == \"\" {\n\t\treturn \"\"\n\t}\n\treturn path.Join(k.dir, PBEKeysetPath)\n}",
"func SetKey(manifestPath string) error {\n\treg := registry.CURRENT_USER\n\tregKey := `SOFTWARE\\Google\\Chrome\\NativeMessagingHosts\\com.wtfender.ask`\n\tk, _, err := registry.CreateKey(reg, regKey, registry.QUERY_VALUE|registry.SET_VALUE|registry.WRITE)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error creating registry key: \" + regKey)\n\t}\n\terr = k.SetStringValue(\"\", manifestPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"Error setting registry key value: \" + regKey)\n\t}\n\treturn nil\n}",
"func (m *Win32LobAppRegistryRule) GetKeyPath()(*string) {\n return m.keyPath\n}",
"func SetPath(p string) {\n\tcurrentPath = \"\"\n\tbeginPath = p\n\tdirsAmount = 0\n}",
"func (m *Win32LobAppRegistryDetection) GetKeyPath()(*string) {\n val, err := m.GetBackingStore().Get(\"keyPath\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.(*string)\n }\n return nil\n}",
"func (m *RegistryKeyState) SetKey(value *string)() {\n m.key = value\n}",
"func (c *DiskCache) KeyPath(ctx context.Context, repo *gitalypb.Repository, req proto.Message) (string, error) {\n\treturn c.keyer.keyPath(ctx, repo, req)\n}",
"func (u Unit) pathKey(inputPath string) string {\n\troot := path.Clean(u.Proto.GetWorkingDirectory())\n\tif root == \"\" {\n\t\troot = \"/\"\n\t}\n\n\tif path.IsAbs(inputPath) {\n\t\tinputPath = path.Clean(inputPath)\n\t} else {\n\t\tinputPath = path.Join(root, inputPath)\n\t}\n\n\tvar prefix string\n\tif root == \"/\" {\n\t\tprefix = root\n\t} else {\n\t\tprefix = root + \"/\"\n\t}\n\treturn strings.TrimPrefix(inputPath, prefix)\n}",
"func CertPathKey(key string) Option {\n\treturn func(ec *Envcfg) {\n\t\tec.certPathKey = key\n\t}\n}",
"func getKeyPath(name string) string {\n\treturn configDir + \"/hil-vpn-\" + name + \".key\"\n}",
"func (v *VisConfig) SetPath(path string) {\n\tif path == \"\" {\n\t\tv.path = datastore.Key{}\n\t} else {\n\t\tv.path = datastore.NewKey(path)\n\t}\n}",
"func (_this *IDBObjectStore) KeyPath() js.Value {\n\tvar ret js.Value\n\tvalue := _this.Value_JS.Get(\"keyPath\")\n\tret = value\n\treturn ret\n}",
"func SetPath(p string) {\n\tpath = filepath.FromSlash(p)\n}",
"func GetKeysPath() string {\n\treturn path.Join(viper.GetString(\"ca_root\"), \"keys\")\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetValueName sets the valueName property value. The registry value name
|
func (m *Win32LobAppRegistryDetection) SetValueName(value *string)() {
err := m.GetBackingStore().Set("valueName", value)
if err != nil {
panic(err)
}
}
|
[
"func (m *RegistryValueEvidence) SetRegistryValueName(value *string)() {\n err := m.GetBackingStore().Set(\"registryValueName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *Win32LobAppRegistryRule) SetValueName(value *string)() {\n m.valueName = value\n}",
"func (m *DeviceManagementConfigurationPolicy) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *ExtensionSchemaProperty) SetName(value *string)() {\n m.name = value\n}",
"func (m *ExtensionProperty) SetName(value *string)() {\n m.name = value\n}",
"func (m *CalendarGroup) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *WorkbookWorksheet) SetName(value *string)() {\n m.name = value\n}",
"func (m *CertificationControl) SetName(value *string)() {\n m.name = value\n}",
"func (m *WorkbookPivotTable) SetName(value *string)() {\n m.name = value\n}",
"func (cli *SetWrapper) SetName(name string) error {\n\treturn cli.set.SetValue(fieldSetName, name)\n}",
"func (m *ItemReference) SetName(value *string)() {\n m.name = value\n}",
"func (m *ParentLabelDetails) SetName(value *string)() {\n err := m.GetBackingStore().Set(\"name\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (v VirtualSwitch) SetName(newName string) error {\n\t// Get fresh settings info\n\tswitchSettingsResult, err := v.virtualSwitch.Get(\"associators_\", nil, VMSwitchSettings)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"associators_\")\n\t}\n\n\tresult, err := switchSettingsResult.ItemAtIndex(0)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"ItemAtIndex\")\n\t}\n\n\tif err := result.Set(\"ElementName\", newName); err != nil {\n\t\treturn errors.Wrap(err, \"ElementName\")\n\t}\n\n\ttext, err := result.GetText(1)\n\tif err != nil {\n\t\treturn errors.Wrap(err, \"GetText\")\n\t}\n\tif err := v.modifySwitchSettings(text); err != nil {\n\t\treturn errors.Wrap(err, \"modifySwitchSettings\")\n\t}\n\n\tif err := v.setInternalPortName(newName); err != nil {\n\t\treturn errors.Wrap(err, \"setInternalPortName\")\n\t}\n\treturn nil\n}",
"func (request *DomainRegisterRequest) SetName(value *string) {\n\trequest.SetStringProperty(\"Name\", value)\n}",
"func (m *DeviceCompliancePolicySettingStateSummary) SetSettingName(value *string)() {\n err := m.GetBackingStore().Set(\"settingName\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (m *IdentityProvider) SetName(value *string)() {\n m.name = value\n}",
"func (s UserSet) SetName(value string) {\n\ts.RecordCollection.Set(models.NewFieldName(\"Name\", \"name\"), value)\n}",
"func (m *ExternalConnection) SetName(value *string)() {\n m.name = value\n}",
"func (m *RegistryKeyState) SetOldValueName(value *string)() {\n m.oldValueName = value\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
/ FormURL creates a URL that you can use for making API requests or authenticating your users.
|
func FormURL(baseURL string, method string, params map[string]string) *url.URL {
u, err := url.Parse(baseURL)
if err != nil {
log.Fatalf("Failed to set root URL: %s\n", err)
}
params["method"] = method
params["format"] = "json"
log.WithField("params", params).Debug("got arguments for request")
query := u.Query()
for key, value := range params {
query.Set(key, value)
}
query.Set("api_sig", SignRequest(params))
u.RawQuery = query.Encode()
log.Debugf("creating URL: %s", u)
return u
}
|
[
"func URLform(url, body string) (result string) {\n\tresult = fmt.Sprintf(`[%s](%s)`, body, url)\n\treturn\n}",
"func (c *Client) URLFormCall(ctx context.Context, endpoint string, qv url.Values, resp interface{}) error {\n\tif len(qv) == 0 {\n\t\treturn fmt.Errorf(\"URLFormCall() requires qv to have non-zero length\")\n\t}\n\n\tif err := c.checkResp(reflect.ValueOf(resp)); err != nil {\n\t\treturn err\n\t}\n\n\tu, err := url.Parse(endpoint)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse path URL(%s): %w\", endpoint, err)\n\t}\n\n\theaders := http.Header{}\n\theaders.Set(\"Content-Type\", \"application/x-www-form-urlencoded; charset=utf-8\")\n\taddStdHeaders(headers)\n\n\tenc := qv.Encode()\n\n\treq := &http.Request{\n\t\tMethod: http.MethodPost,\n\t\tURL: u,\n\t\tHeader: headers,\n\t\tContentLength: int64(len(enc)),\n\t\tBody: io.NopCloser(strings.NewReader(enc)),\n\t\tGetBody: func() (io.ReadCloser, error) {\n\t\t\treturn io.NopCloser(strings.NewReader(enc)), nil\n\t\t},\n\t}\n\n\tdata, err := c.do(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv := reflect.ValueOf(resp)\n\tif err := c.checkResp(v); err != nil {\n\t\treturn err\n\t}\n\n\tvar unmarshal = json.Unmarshal\n\tif _, ok := v.Elem().Type().FieldByName(\"AdditionalFields\"); ok {\n\t\tunmarshal = customJSON.Unmarshal\n\t}\n\tif resp != nil {\n\t\tif err := unmarshal(data, resp); err != nil {\n\t\t\treturn fmt.Errorf(\"json decode error: %w\\nraw message was: %s\", err, string(data))\n\t\t}\n\t}\n\treturn nil\n}",
"func (h *HttpClient) CreateUrl(requrl string, parameters map[string]string)(string) {\n baseUrl, _ := url.Parse(requrl)\n params := url.Values{}\n for k, v := range parameters {\n params.Add(k, v)\n }\n baseUrl.RawQuery = params.Encode()\n return baseUrl.String()\n}",
"func PostURL(w http.ResponseWriter, r *http.Request) {\n\tlog.Println(\"POST URL\")\n\n\t// Generate key for storage\n\turlKey := GenerateKey(false)\n\n\twriteURLInfo(w, r, urlKey, http.StatusCreated)\n}",
"func (r AccountsRequest) BuildURL() (endpoint string, err error) {\n\n\tnParams := countParams(r.Signer, r.Asset, r.Sponsor, r.LiquidityPool)\n\n\tif nParams <= 0 {\n\t\terr = errors.New(\"invalid request: no parameters - Signer, Asset, Sponsor, or LiquidityPool must be provided\")\n\t}\n\n\tif nParams > 1 {\n\t\terr = errors.New(\"invalid request: too many parameters - Multiple filters provided, provide a single filter\")\n\t}\n\n\tif err != nil {\n\t\treturn endpoint, err\n\t}\n\tquery := url.Values{}\n\tswitch {\n\tcase len(r.Signer) > 0:\n\t\tquery.Add(\"signer\", r.Signer)\n\n\tcase len(r.Asset) > 0:\n\t\tquery.Add(\"asset\", r.Asset)\n\n\tcase len(r.Sponsor) > 0:\n\t\tquery.Add(\"sponsor\", r.Sponsor)\n\n\tcase len(r.LiquidityPool) > 0:\n\t\tquery.Add(\"liquidity_pool\", r.LiquidityPool)\n\t}\n\n\tendpoint = fmt.Sprintf(\n\t\t\"accounts?%s\",\n\t\tquery.Encode(),\n\t)\n\n\tif pageParams := addQueryParams(cursor(r.Cursor), limit(r.Limit), r.Order); len(pageParams) > 0 {\n\t\tendpoint = fmt.Sprintf(\n\t\t\t\"%s&%s\",\n\t\t\tendpoint,\n\t\t\tpageParams,\n\t\t)\n\t}\n\n\t_, err = url.Parse(endpoint)\n\tif err != nil {\n\t\terr = errors.Wrap(err, \"failed to parse endpoint\")\n\t}\n\n\treturn endpoint, err\n}",
"func (r *Request) URLf(format string, args ...interface{}) *Request {\n\tr.url = fmt.Sprintf(format, args...)\n\treturn r\n}",
"func MakeURL(email string) string {\n\tur := \"/api/v1/user/confirm-email/\"\n\tur += generateToken(email)\n\treturn ur\n}",
"func (a AuthURI) URL() *url.URL {\n\tu := &url.URL{\n\t\tScheme: a.Scheme,\n\t\tHost: a.Type,\n\t}\n\tq := url.Values{}\n\tif len(a.Label) > 0 {\n\t\tu.Path = fmt.Sprintf(\"/%s\", a.Label)\n\t}\n\tswitch a.Algorithm {\n\tcase totp.SHA1:\n\t\tq.Add(\"algorithm\", \"SHA1\")\n\tcase totp.SHA256:\n\t\tq.Add(\"algorithm\", \"SHA256\")\n\tcase totp.SHA512:\n\t\tq.Add(\"algorithm\", \"SHA512\")\n\t}\n\tq.Add(\"digits\", strconv.Itoa(a.Digits))\n\tq.Add(\"period\", strconv.Itoa(a.Period))\n\tq.Add(\"secret\", string(a.Secret))\n\tif len(a.Issuer) > 0 {\n\t\tq.Add(\"issuer\", a.Issuer)\n\t}\n\n\tu.RawQuery = q.Encode()\n\treturn u\n}",
"func (usr *User) CreateUrl(r *http.Request) (url *Url, errMsg template.HTML) {\n\tip := ipAddr(r)\n\n\tfmt.Println(\"Raw Header IP:\", r.Header.Get(\"X-Forwarded-For\"))\n\tfmt.Println(\"Formatted IP:\", ip)\n\n\tif usr.exceedUrlLmit(ip) {\n\t\treturn nil,\n\t\t\t\"Public url limits exceeded.<br><a href='/signin'><strong>Sign-in</strong></a> for more urls\"\n\t}\n\n\t// format the \"source\" form value to valid url address\n\tr.ParseForm()\n\tr.PostForm.Set(\"source\", formatUrl(r.PostFormValue(\"source\")))\n\n\t// If Url already exists in the database, return the exising Url.\n\turl = UrlBySource(r.PostFormValue(\"source\"))\n\tif url != nil {\n\t\tfmt.Println(\"previous url found.\", url)\n\t\treturn url, \"\"\n\t}\n\n\t// Extract Url from POST form\n\turl = UrlFromPost(r, usr)\n\n\t// Communicate error with client if database error occurs.\n\tif err := insertUrl(url); err != nil {\n\t\terrMsg = \"There was a problem connecting to the database.\"\n\t}\n\n\treturn url, errMsg\n}",
"func CreateURL(base string, args map[string][]string) string {\r\n\tu, _ := url.Parse(base)\r\n\tq := u.Query()\r\n\r\n\tfor arg, vals := range args {\r\n\t\tfor _, val := range vals {\r\n\t\t\tq.Add(arg, val)\r\n\t\t}\r\n\t}\r\n\r\n\tu.RawQuery = q.Encode()\r\n\treturn u.String()\r\n}",
"func (config *TOTPConfig) generateURL(label string) string {\n\tsecret := config.ExportKey()\n\tu := url.URL{}\n\tv := url.Values{}\n\tu.Scheme = \"otpauth\"\n\tu.Host = \"totp\"\n\tu.Path = label\n\tv.Add(\"secret\", secret)\n\tif config.Size != totpDefaultDigits {\n\t\tv.Add(\"digits\", fmt.Sprintf(\"%d\", config.Size))\n\t}\n\n\t// If other hash algorithms become supported in Google\n\t// Authenticator, enable these.\n\t// switch {\n\t// case config.Algo == crypto.SHA256:\n\t// \tv.Add(\"algorithm\", \"SHA256\")\n\t// case config.Algo == crypto.SHA512:\n\t// \tv.Add(\"algorithm\", \"SHA512\")\n\t// }\n\n\tif config.Provider != \"\" {\n\t\tv.Add(\"provider\", config.Provider)\n\t}\n\n\tu.RawQuery = v.Encode()\n\treturn u.String()\n}",
"func (c *client) createURL(urlPath string, query url.Values) string {\n\tu := c.endpoint\n\tu.Path = urlPath\n\tif query != nil {\n\t\tu.RawQuery = query.Encode()\n\t}\n\treturn u.String()\n}",
"func generateUrl(endpoint, parameters string) (string, error) {\n\tif viper.GetString(\"FUID_IP_ADDRESS\") == \"\" {\n\t\treturn \"\", errors.New(\"The FUID API IP address is not provided\")\n\t}\n\tif viper.GetInt(\"FUID_PORT\") == 0 {\n\t\treturn \"\", errors.New(\"The FUID API port number is not provided\")\n\t}\n\tgeneratedUrl := fmt.Sprintf(\"https://%s:%d/api/uid/v1.0/%s\", viper.GetString(\"FUID_IP_ADDRESS\"), viper.GetInt(\"FUID_PORT\"), endpoint)\n\tif parameters != \"\" {\n\t\tgeneratedUrl = fmt.Sprintf(\"%s?%s\", generatedUrl, parameters)\n\t}\n\treturn generatedUrl, nil\n}",
"func MakeForm(method string, base, path string, params url.Values, headers http.Header) *http.Request {\n\treturn EncodeForm(&http.Request{\n\t\tMethod: method,\n\t\tURL: URL(base, path, nil),\n\t\tHeader: headers,\n\t}, params)\n}",
"func formatSignInURL(signInToken string) (*url.URL, error) {\n\tissuer := defaultIssuer\n\n\tsignInFederationURL, err := url.Parse(federationEndpointURL)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsigninParams := url.Values{}\n\n\tsigninParams.Add(\"Action\", \"login\")\n\tsigninParams.Add(\"Destination\", awsConsoleURL)\n\tsigninParams.Add(\"Issuer\", issuer)\n\tsigninParams.Add(\"SigninToken\", signInToken)\n\n\tsignInFederationURL.RawQuery = signinParams.Encode()\n\n\treturn signInFederationURL, nil\n}",
"func formatSigninTokenURL(reqLogger logr.Logger, federationEndpointURL string, jsonFederatedCredentials []byte) (*url.URL, error) {\n\t// Build URL to request Signin Token via Federation end point\n\tbaseFederationURL, err := url.Parse(federationEndpointURL)\n\n\tif err != nil {\n\t\treqLogger.Error(err, fmt.Sprintf(\"Malformed URL: %s\", err.Error()))\n\t\treturn baseFederationURL, err\n\t}\n\n\tfederationParams := url.Values{}\n\n\tfederationParams.Add(\"Action\", \"getSigninToken\")\n\tfederationParams.Add(\"SessionType\", \"json\")\n\tfederationParams.Add(\"Session\", string(jsonFederatedCredentials))\n\n\tbaseFederationURL.RawQuery = federationParams.Encode()\n\n\treturn baseFederationURL, nil\n\n}",
"func BuildURL(url string) string {\n\treturn apiBase + url\n}",
"func (s Client) makeURL(method string) string {\n\treturn fmt.Sprintf(\"http://%s/rest/%s.view?u=%s&p=%s&c=%s&v=%s&f=json\",\n\t\ts.Host, method, s.Username, s.Password, CLIENT, APIVERSION)\n}",
"func (c Client) AuthURL(state string) string {\n\tvalues := url.Values{\"client_id\": {c.ISS}, \"state\": {\"state\"}, \"response_type\": {\"code\"}}\n\treturn fmt.Sprintf(\"%s?%s\", c.Endpoint.AuthURL, values.Encode())\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Given an array of positive integers target and an array initial of same size with all zeros. Return the minimum number of operations to form a target array from initial if you are allowed to do the following operation: Choose any subarray from initial and increment each value by one. The answer is guaranteed to fit within the range of a 32bit signed integer. Example 1: Input: target = [1,2,3,2,1] Output: 3 Explanation: We need at least 3 operations to form the target array from the initial array. [0,0,0,0,0] increment 1 from index 0 to 4 (inclusive). [1,1,1,1,1] increment 1 from index 1 to 3 (inclusive). [1,2,2,2,1] increment 1 at index 2. [1,2,3,2,1] target array is formed. Example 2: Input: target = [3,1,1,2] Output: 4 Explanation: (initial)[0,0,0,0] > [1,1,1,1] > [1,1,1,2] > [2,1,1,2] > [3,1,1,2] (target). Example 3: Input: target = [3,1,5,4,2] Output: 7 Explanation: (initial)[0,0,0,0,0] > [1,1,1,1,1] > [2,1,1,1,1] > [3,1,1,1,1] > [3,1,2,2,2] > [3,1,3,3,2] > [3,1,4,4,2] > [3,1,5,4,2] (target). Example 4: Input: target = [1,1,1,1] Output: 1 Constraints: 1 <= target.length <= 10^5 1 <= target[i] <= 10^5 simple O(n) solution:
|
func minNumberOperationsOn(target []int) int {
sum := target[0]
for i:=1; i<len(target); i++ {
// it's easy to understand:
// every larger number than prev need to increase by its own
// every smaller number than prev can be covered by prev larger number
if target[i]>target[i-1] {
sum += target[i]-target[i-1]
}
}
return sum
}
|
[
"func minOperations(nums []int, x int) int {\n\tsum := 0\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t}\n\tif x == sum {\n\t\treturn len(nums)\n\t}\n\ttarget := sum - x // find the longest subarray that sum is target\n\tsum = 0\n\tmapp := make(map[int]int)\n\tmapp[0] = -1\n\tans := -1\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t\tif v, ok := mapp[sum-target]; ok {\n\t\t\tif i-v > ans {\n\t\t\t\tans = i - v\n\t\t\t}\n\t\t}\n\t\tmapp[sum] = i\n\t}\n\tif ans == -1 {\n\t\treturn -1\n\t}\n\treturn len(nums) - ans\n}",
"func findTargetSumWays(nums []int, S int) int {\n\t// let c[i, j] be the number of ways to get sum j for nums[0...i]\n\t// then c[i, j] = c[i-1, j+nums[i]] + c[i-1, j-nums[i]]\n\t// base case c[0, ±nums[0]] = 1, c[x, 0] = 0\n\tsum := 0\n\tfor i := range nums {\n\t\tsum += nums[i]\n\t}\n\tif S > sum || S < -sum {\n\t\treturn 0\n\t}\n\tc0 := make([]int, 2*sum+1)\n\tc1 := make([]int, 2*sum+1)\n\tif nums[0] != 0 {\n\t\tc0[nums[0]+sum] = 1\n\t\tc0[-nums[0]+sum] = 1\n\t} else {\n\t\tc0[sum] = 2\n\t}\n\tfmt.Println(c0)\n\tfor i := 1; i < len(nums); i++ {\n\t\tfor j := -sum; j <= sum; j++ {\n\t\t\tc1[j+sum] = 0 // clear c1\n\t\t\tif j+nums[i] <= sum {\n\t\t\t\tc1[j+sum] += c0[j+nums[i]+sum]\n\t\t\t}\n\t\t\tif j-nums[i] >= -sum {\n\t\t\t\tc1[j+sum] += c0[j-nums[i]+sum]\n\t\t\t}\n\t\t}\n\t\tfmt.Println(c1)\n\t\tc0, c1 = c1, c0\n\t}\n\treturn c0[S+sum]\n}",
"func MinimumOperations(arr []int) {\n\ti := 0\n\tvar count int\n\tj := len(arr) - 1\n\tfor i < j {\n\t\tif arr[i] != arr[j] {\n\t\t\tif arr[i] < arr[j] {\n\t\t\t\tarr[i+1] += arr[i]\n\t\t\t\ti++\n\t\t\t} else {\n\t\t\t\tarr[j-1] += arr[j]\n\t\t\t\tj--\n\t\t\t}\n\t\t\tcount++\n\t\t} else {\n\t\t\ti++\n\t\t\tj--\n\t\t}\n\t}\n\tfmt.Println(count)\n\n}",
"func LeastOpsExpressTarget(x int, target int) int {\n\tvar visited map[float64]bool = make(map[float64]bool)\n\tvar q list.List\n\tq.PushBack(float64(x))\n\tvar steps int = 0\n\tfor q.Len() > 0{\n\t\tvar l int = q.Len()\n\t\tfor i := 0;i < l;i++{\n\t\t\tvar n float64 = q.Front().Value.(float64)\n\t\t\tq.Remove(q.Front())\n\t\t\tif math.Abs(n - float64(target)) <= 1e-6{\n\t\t\t\treturn steps\n\t\t\t}\n\t\t\tadd := n + float64(x)\n\t\t\tif _,ok := visited[add];!ok{\n\t\t\t\tq.PushBack(add)\n\t\t\t\tvisited[add] = true\n\t\t\t}\n\t\t\tminus := math.Abs(n - float64(x))\n\t\t\tif _,ok := visited[minus];!ok{\n\t\t\t\tq.PushBack(minus)\n\t\t\t\tvisited[minus] = true\n\t\t\t}\n\t\t\ttimes := n * float64(x)\n\t\t\tif _,ok := visited[times];!ok{\n\t\t\t\tq.PushBack(times)\n\t\t\t\tvisited[times] = true\n\t\t\t}\n\t\t\tdivide1 := n / float64(x)\n\t\t\tif _,ok := visited[divide1];!ok{\n\t\t\t\tq.PushBack(divide1)\n\t\t\t\tvisited[divide1] = true\n\t\t\t}\n\t\t\tif n != 0{\n\t\t\t\tdivide2 := float64(x)/n\n\t\t\t\tif _,ok := visited[divide2];!ok{\n\t\t\t\t\tq.PushBack(divide2)\n\t\t\t\t\tvisited[divide2] = true\n\t\t\t\t}\n\t\t\t}\n\n\t\t}\n\t\tsteps++\n\t}\n\treturn steps\n}",
"func minSizeSubArraySum(input []int, targetSum int) int {\n\n\t// check for entry conditions\n\tif len(input) == 0 {\n\t\treturn 0\n\t}\n\n\n\t// Return value should be MIN, so by default set to Max\n\tresult := len(input)\n\n\t// start two pointers starts and end \n\tleftIndex := 0\n\tvalueSum := 0\n\t\n\t// loop on the input array\n\tfor i:=0; i< len(input); i++{\n\n\t\tvalueSum += input[i]\n\n\t\tfor valueSum >= targetSum{\n\t\n\t\t\tresult = min(result, i + 1 - leftIndex )\n\t\t\t\n\t\t\tvalueSum -= input[leftIndex]\n\t\t\tleftIndex++\n\t\t}\t\n\t}\n\n\tif result != len(input){\n\t\treturn result\n\t}\n\treturn 0\n}",
"func bestSum(target int, numbers []int) []int {\n\tdp := make([][]int, target+1)\n\tfor i := 1; i <= target; i++ {\n\t\tvar smallestCombination []int\n\t\tfor _, number := range numbers {\n\t\t\tcandidate := i - number\n\t\t\tif candidate < 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif candidate == 0 {\n\t\t\t\tdp[i] = []int{number}\n\t\t\t\tsmallestCombination = dp[i]\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif len(dp[candidate]) == 0 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif len(smallestCombination) == 0 || len(dp[candidate])+1 < len(smallestCombination) {\n\t\t\t\tsmallestCombination = append(dp[candidate], number)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\tdp[i] = smallestCombination\n\t}\n\treturn dp[target]\n}",
"func findTargetSumWays(nums []int, S int) int {\n if len(nums) == 0 {\n if S == 0 {\n return 1\n } else {\n return 0\n }\n }\n\n return findTargetSumWays(nums[:len(nums)-1], S + nums[len(nums)-1]) + findTargetSumWays(nums[:len(nums)-1], S - nums[len(nums)-1])\n}",
"func numRollsToTarget(d int, f int, target int) int {\n\tdp := make([]int, target+1)\n\tdp[0] = 1\n\n\tfor i := 1; i <= d; i++ {\n\t\tnow := make([]int, target+1)\n\t\tfor j := 1; j <= f; j++ {\n\t\t\tfor k := j; k <= target; k++ {\n\t\t\t\tnow[k] = (now[k] + dp[k-j]) % 1000000007\n\t\t\t}\n\t\t}\n\t\tdp = now\n\t}\n\n\treturn dp[target]\n}",
"func Change(coins []int, target int) (expectedChange []int, err error) {\n\tif target < 0 {\n\t\terr = fmt.Errorf(\"no change available for negative value %v\", target)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif target < coins[0] && target != 0 {\n\t\terr = fmt.Errorf(\"target change %v is smaller than the smallest coin %v\", target, coins[0])\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\tif target == 0 {\n\t\texpectedChange = make([]int, 0)\n\t\tlog.Println(expectedChange)\n\t\treturn\n\t}\n\tvar table [][]int\n\tvar targetArray = make([]int, target+1)\n\tdst := make([]int, len(targetArray))\n\tcopy(dst, targetArray)\n\ttable = append(table, dst)\n\tfor _, coin := range coins {\n\t\tfor tempTarget := 0; tempTarget <= target; tempTarget++ {\n\t\t\tif tempTarget >= coin {\n\t\t\t\tif targetArray[tempTarget-coin] == 0 && tempTarget%coin != 0 {\n\t\t\t\t} else if (targetArray[tempTarget-coin]+1) < targetArray[tempTarget] || targetArray[tempTarget] == 0 {\n\t\t\t\t\ttargetArray[tempTarget] = targetArray[tempTarget-coin] + 1\n\t\t\t\t}\n\t\t\t} else if tempTarget == 0 {\n\t\t\t\ttargetArray[tempTarget] = 0\n\t\t\t}\n\n\t\t}\n\t\tdst := make([]int, len(targetArray))\n\t\tcopy(dst, targetArray)\n\t\ttable = append(table, dst)\n\t}\n\tnumberOfCoins := table[len(coins)][target]\n\tchangeIsAvailable := false\n\tfor i := 0; i < len(table); i++ {\n\t\tif table[i][target] != 0 {\n\t\t\tchangeIsAvailable = true\n\t\t\tbreak\n\t\t}\n\t}\n\tif !changeIsAvailable {\n\t\terr = fmt.Errorf(\"no combination of coins %v can make the change %v\", coins, target)\n\t\tlog.Println(err)\n\t\treturn\n\t}\n\texpectedChange = make([]int, numberOfCoins)\n\trow := len(coins)\n\tcol := target\n\ti := 0\n\tfor i < len(expectedChange) {\n\t\tif table[row][col] < table[row-1][col] || table[row-1][col] == 0 {\n\t\t\texpectedChange[i] = coins[row-1]\n\t\t\ti++\n\t\t\tcol = col - coins[row-1]\n\t\t} else if table[row][col] == table[row-1][col] {\n\t\t\trow = row - 1\n\t\t}\n\t}\n\tsort.Ints(expectedChange)\n\tlog.Println(expectedChange)\n\treturn expectedChange, err\n}",
"func FourSum(seq []int, target int) [][]int {\n res := [][]int{}\n seqPairMap := map[int][]int{} // { sum1: [i1, j1, i2, j2, ...], sum2: [i3, j3, i4, j4, ...], ... }\n for i := 0; i < len(seq) - 1; i++ {\n for j := i + 1; j < len(seq); j++ {\n sum := seq[i] + seq[j]\n if _, ok := seqPairMap[sum]; !ok { seqPairMap[sum] = []int{}; }\n seqPairMap[sum] = append(seqPairMap[sum], i)\n seqPairMap[sum] = append(seqPairMap[sum], j)\n }\n }\n // example: target = 14, sums are 5 + 9, 3 + 11 (map on smaller of the two i.e. 5, 3; other is implicit)\n sumMap := map[int][][]int{} // { 5: [[i1, j1, ...],[i5, j5, ...]], ...} 5 <-- [i1, j1, ...], 9 <-- [i5, j5, ...]\n for k, _ := range seqPairMap {\n if _, ok := seqPairMap[target-k]; ok {\n if k < target - k {\n sumMap[k] = [][]int{[]int{}, []int{}}\n sumMap[k][0] = seqPairMap[k]; sumMap[k][1] = seqPairMap[target-k];\n } else {\n sumMap[target-k] = [][]int{[]int{}, []int{}}\n sumMap[target-k][0] = seqPairMap[target-k]; sumMap[target-k][1] = seqPairMap[k];\n }\n }\n }\n \n for _, indexArr := range sumMap {\n arr0 := indexArr[0]; arr1 := indexArr[1]\n for m := 0; m < len(arr0); m += 2 {\n for n := 0; n < len(arr1); n += 2 {\n // check for distinctness of arr0[m], arr0[m+1], arr1[n], arr1[n+1]\n if arr0[m] != arr1[n] && arr0[m] != arr1[n+1] &&\n arr0[m+1] != arr1[n] && arr0[m+1] != arr1[n+1] {\n // still allows some dups to go through e.g. indexes [2 5 7 10], [2 7 5 10]\n res = append(res, []int{arr0[m], arr0[m+1], arr1[n], arr1[n+1]})\n }\n }\n }\n }\n // returns arrays of indices, convert to actual values as seq[i] for each i \n return res\n}",
"func fourSum(nums []int, target int) [][]int {\n\tif len(nums) < 4 {\n\t\treturn nil\n\t}\n\tif len(nums) == 4 {\n\t\tif sum(nums) == target {\n\t\t\treturn [][]int{nums}\n\t\t} else {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tsort(nums)\n\n\tvar (\n\t\ta, b int\n\t\tlength = len(nums)\n\t\tc, d = 2, length - 1\n\t\tdp = make([][]int, length)\n\t)\n\tfor i := range dp {\n\t\tdp[i] = make([]int, length)\n\t}\n\tfor ; c < d; c++ {\n\t\tfor ; d > c; d-- {\n\t\t\tdp[c][d] = nums[c] + nums[d]\n\t\t}\n\t\td = length - 1\n\t}\n\tfmt.Println(\"dp: \", dp)\n\n\tvar (\n\t\ttemp1, temp2 int\n\t\tresult = make([][]int, 0, 20)\n\t)\n\tfor ; a < length-3; a++ {\n\t\ttemp1 = target - nums[a]\n\t\tfor b = a + 1; b < length-2; b++ {\n\t\t\ttemp2 = temp1 - nums[b]\n\t\t\tfor c = b + 1; c < d; c++ {\n\t\t\t\tfor ; d > c; d-- {\n\t\t\t\t\tif dp[c][d] == temp2 {\n\t\t\t\t\t\tresult = append(result, []int{nums[a], nums[b], nums[c], nums[d]})\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\td = length - 1\n\t\t\t\tfor c < d && nums[c] == nums[c+1] {\n\t\t\t\t\tc++\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor b < length-2 && nums[b] == nums[b+1] {\n\t\t\t\tb++\n\t\t\t}\n\t\t}\n\t\tfor a < length-3 && nums[a] == nums[a+1] {\n\t\t\ta++\n\t\t}\n\t}\n\n\treturn result\n}",
"func minimumSwaps(arr []int) int {\n\tvar changeRequest bool = true\n\tvar changes int\n\tvar newArr []int = arr\n\n\tfor changeRequest == true {\n\t\tchangeRequest = false\n\n\t\tfor idx, elem := range arr {\n\t\t\tif idx+1 != elem {\n\t\t\t\tchangeRequest = true\n\n\t\t\t\tnewArr[idx] = idx + 1 // the correct value\n\n\t\t\t\ttargetIdx, _ := findIndex(arr, idx+1)\n\t\t\t\tnewArr[targetIdx] = elem\n\t\t\t\tchanges++\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tarr = newArr\n\t}\n\treturn changes\n}",
"func findTargetSumWays(nums []int, S int) int {\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\tsum := 0\n\tfor _, v := range nums {\n\t\tsum += v\n\t}\n\tif (sum+S)%2 != 0 {\n\t\treturn 0\n\t}\n\tif S > sum {\n\t\treturn 0\n\t}\n\tdp := make([]int, (sum+S)/2+1)\n\tdp[0] = 1\n\tfor i := 1; i <= len(nums); i++ {\n\t\tfor j := (sum + S) / 2; j >= nums[i-1]; j-- {\n\t\t\tdp[j] += dp[j-nums[i-1]]\n\t\t}\n\t}\n\treturn dp[(sum+S)/2]\n}",
"func threeSumMulti(arr []int, target int) int {\n\tconst MaxVal = 100\n\tconst Mod = 1_000_000_007\n\n\tcnt := make([]int, MaxVal+1)\n\tuniqueCnt := 0\n\tfor _, v := range arr {\n\t\tcnt[v]++\n\t\tif cnt[v] == 1 {\n\t\t\tuniqueCnt++\n\t\t}\n\t}\n\n\tkeys := make([]int, uniqueCnt)\n\tpk := 0\n\tfor i, c := range cnt {\n\t\tif c > 0 {\n\t\t\tkeys[pk] = i\n\t\t\tpk++\n\t\t}\n\t}\n\n\tvar ans int64 = 0\n\t// reduce to 3-sum on \"keys\" for i <= j <= k\n\t// note that the \"<=\" being used here because of multiplicity of original array\n\tfor i, x := range keys {\n\t\tt := target - x\n\t\tj, k := i, len(keys)-1\n\t\t// reduce to 2-sum with target=t\n\t\tfor j <= k {\n\t\t\ty, z := keys[j], keys[k]\n\t\t\tif y+z < t {\n\t\t\t\tj++\n\t\t\t} else if y+z > t {\n\t\t\t\tk--\n\t\t\t} else { // y + z = t, so x + y + z = target\n\t\t\t\tif i < j && j < k {\n\t\t\t\t\tans += int64(cnt[x] * cnt[y] * cnt[z])\n\t\t\t\t} else if i == j && j < k {\n\t\t\t\t\tans += int64(cnt[x] * (cnt[x] - 1) / 2 * cnt[z])\n\t\t\t\t} else if i < j && j == k {\n\t\t\t\t\tans += int64(cnt[x] * cnt[y] * (cnt[y] - 1) / 2)\n\t\t\t\t} else { // i == j == k\n\t\t\t\t\tans += int64(cnt[x] * (cnt[x] - 1) * (cnt[x] - 2) / 6)\n\t\t\t\t}\n\t\t\t\tans %= Mod\n\t\t\t\tj++\n\t\t\t\tk--\n\t\t\t}\n\t\t}\n\t}\n\n\treturn int(ans)\n}",
"func Union(a, b, target []int) []int {\n\tlenA, lenB := len(a), len(b)\n\n\tvar union []int\n\tif target == nil {\n\t\tunion = make([]int, 0, ints.Max(lenA, lenB))\n\t} else {\n\t\tunion = target[:0]\n\t}\n\n\tidx1, idx2 := 0, 0\n\tfor {\n\t\tif idx1 == lenA {\n\t\t\tunion = append(union, b[idx2:]...)\n\t\t\tbreak\n\t\t} else if idx2 == lenB {\n\t\t\tunion = append(union, a[idx1:]...)\n\t\t\tbreak\n\t\t}\n\n\t\taVal, bVal := a[idx1], b[idx2]\n\n\t\tif aVal < bVal {\n\t\t\tunion = append(union, aVal)\n\t\t\tidx1++\n\t\t} else if bVal < aVal {\n\t\t\tunion = append(union, bVal)\n\t\t\tidx2++\n\t\t} else {\n\t\t\tunion = append(union, aVal)\n\t\t\tidx1++\n\t\t\tidx2++\n\t\t}\n\t}\n\n\treturn union\n}",
"func combinationSum(candidates []int, target int) [][]int {\n var res [][]int\n for i, val := range candidates {\n diff := target - val\n if diff > 0 {\n for _, arr := range combinationSum(candidates[i:], diff) {\n\t\t\t\t// Adding dots after second slice can let you pass multiple arguments to a variadic function from a slice\n tmp := append([]int{val}, arr...)\n res = append(res, tmp)\n } \n } else if diff == 0 {\n res = append(res, []int{val})\n }\n }\n \n return res\n}",
"func minimumSize(nums []int, maxOperations int) int {\n\tmaxe := 0\n\tfor _, v := range nums {\n\t\tif v > maxe {\n\t\t\tmaxe = v\n\t\t}\n\t}\n\tl, r := 1, maxe\n\tfor l < r {\n\t\tmid := (l + r) / 2\n\t\tall := 0\n\t\t// count how many ops we need to make the max number of balls as mid\n\t\t// to divide x balls into some parts where each part <= t,\n\t\t// we need ceiling(x/t)-1 = (x-1)/t times of divide.\n\t\tfor _, v := range nums {\n\t\t\tall += (v - 1) / mid\n\t\t}\n\t\tif all > maxOperations {\n\t\t\tl = mid + 1\n\t\t} else {\n\t\t\tr = mid\n\t\t}\n\t}\n\treturn l\n}",
"func minOperations1827(nums []int) int {\n\tres := 0\n\tfor i := 1; i < len(nums); i++ {\n\t\ta := nums[i-1]\n\t\tb := nums[i]\n\t\tif a >= b {\n\t\t\tres += a + 1 - b\n\t\t\tnums[i] = a + 1\n\t\t}\n\t}\n\treturn res\n}",
"func NumSubmatrixSumTarget(matrix [][]int, target int) int {\n\tvar rows int = len(matrix)\n\tvar columns int = len(matrix[0])\n\tvar prefix [][]int = make([][]int,rows + 1)//prefix[i][j] = sum from 0,0 to i - 1,j - 1\n\tfor i := 0;i <= rows;i++{\n\t\tprefix[i] = make([]int,columns + 1)\n\t}\n\tfor i := 1;i <= rows;i++{\n\t\tfor j := 1;j <= columns;j++{\n\t\t\tprefix[i][j] = matrix[i - 1][j - 1] + prefix[i - 1][j] + prefix[i][j - 1] - prefix[i - 1][j - 1]\n\t\t}\n\t}\n\tvar res int = 0\n\tfor i := 0;i <= rows;i++{\n\t\tfor j := 0;j <= columns;j++{\n\t\t\tfor r := i + 1;r <= rows;r++{\n\t\t\t\tfor c := j + 1;c <= columns;c++{\n\t\t\t\t\tarea := prefix[r][c] - prefix[r][j] - prefix[i][c] + prefix[i][j]\n\t\t\t\t\tif area == target{\n\t\t\t\t\t\tres++\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn res\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
MiddleRow takes a slice of 3 string slices (each representing a row in a 2d matrix, with each element position respresenting a column), and interpolates "nan" values as the average of nondiagonal adjacent values, which must be string representations of numbers, or "nan". There must be 3 rows. All rows must be equal length. It returns a copy of the middle row with any "nan" values interpolated and rounded to decimalPlaces decimal places.
|
func MiddleRow(rows [][]string, decimalPlaces int) []string {
middleRow := rows[1]
result := make([]string, len(middleRow))
for i, val := range middleRow {
if isNaN(val) {
result[i] = averageOf(
decimalPlaces,
valueAt(rows[0], i),
valueAt(rows[2], i),
valueLeftOf(middleRow, i),
valueRightOf(middleRow, i),
)
} else {
result[i] = val
}
}
return result
}
|
[
"func GetMiddleValue(array []float64) float64 {\n\t//Create a variable of float64 (it will be middle value)\n\tvar number float64\n\t//This a loop like foreach(...) in C#\n\t//renge return index and value of each element from time row\n\t//here number will had a sum of all element\n\tfor _, v := range array {\n\t\tnumber += v\n\t}\n\t//here we will divide a sum on count\n\tnumber /= float64(len(array))\n\treturn number\n}",
"func (d *dataBuffer) Trimean(firstquartile, median, thirdquartile float64) float64 {\n\treturn (firstquartile + (median * 2) + thirdquartile) / 4\n}",
"func Average(slice []float64) (float64, error) {\n\n\tif len(slice) == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Empty\")\n\t}\n\n\tvar sum float64\n\tfor _, n := range slice {\n\t\tsum += n\n\t}\n\n\tavg := sum / float64(len(slice))\n\t// log.Println(\"Slice average\", avg)\n\treturn math.Round(avg*100) / 100, nil\n}",
"func ReduceMedian(values []interface{}) interface{} {\n\tvar data []float64\n\t// Collect all the data points\n\tfor _, value := range values {\n\t\tif value == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdata = append(data, value.([]float64)...)\n\t}\n\n\tlength := len(data)\n\tif length < 2 {\n\t\tif length == 0 {\n\t\t\treturn nil\n\t\t}\n\t\treturn data[0]\n\t}\n\tmiddle := length / 2\n\tvar sortedRange []float64\n\tif length%2 == 0 {\n\t\tsortedRange = getSortedRange(data, middle-1, 2)\n\t\tvar low, high = sortedRange[0], sortedRange[1]\n\t\treturn low + (high-low)/2\n\t} else {\n\t\tsortedRange = getSortedRange(data, middle, 1)\n\t\treturn sortedRange[0]\n\t}\n}",
"func Middle(img image.Image) (int, error) {\n\trect := img.Bounds()\n\treturn (rect.Max.X - rect.Min.X) / 2, nil\n}",
"func SliceMeanRounded(nums []int) int {\n\tif len(nums) == 0 {\n\t\treturn 0\n\t}\n\ttotal := 0\n\tfor _, num := range nums {\n\t\ttotal += num\n\t}\n\treturn int(total / len(nums))\n}",
"func (q *QQwry) getMiddleOffset(start uint32, end uint32) uint32 {\n\trecords := ((end - start) / INDEX_LEN) >> 1\n\treturn start + records*INDEX_LEN\n}",
"func getMiddle(x int, y int) int {\n\tif x > y {\n\t\treturn ((x - y) / 2) + y\n\t} else {\n\t\treturn ((y - x) / 2) + x\n\t}\n}",
"func (ii *interpolatingIterator) midTimestamp() int64 {\n\tif !ii.isValid() {\n\t\tpanic(fmt.Sprintf(\"midTimestamp called on invalid interpolatingIterator: %v\", ii))\n\t}\n\tdsi := ii.nextReal\n\treturn dsi.underlyingData.startNanos + (int64(ii.offset) * dsi.sampleNanos) + (dsi.sampleNanos / 2)\n}",
"func calcRowMeans(mtxX, mtxRes [][]float64, c, r int) {\n\tfor k := 0; k < r; k++ {\n\t\tvar fSum float64\n\t\tfor i := 0; i < c; i++ {\n\t\t\tfSum += mtxX[i][k]\n\t\t}\n\t\tmtxRes[k][0] = fSum / float64(c)\n\t}\n}",
"func initializeMiddleZone() [][]Piece {\n\trows := make([][]Piece, 3)\n\tfor i := range rows {\n\t\trows[i] = []Piece{nil, nil, nil, nil, nil, nil, nil, nil, nil}\n\t}\n\treturn rows\n}",
"func (m *Matf32) Avg(args ...int) float32 {\n\tvar sum float32\n\tswitch len(args) {\n\tcase 0:\n\t\tfor i := range m.vals {\n\t\t\tsum += m.vals[i]\n\t\t}\n\t\tsum /= float32(len(m.vals))\n\tcase 2:\n\t\taxis, slice := args[0], args[1]\n\t\tif axis == 0 {\n\t\t\tif (slice >= m.r) || (slice < 0) {\n\t\t\t\ts := \"\\nIn %s the row %d is outside of bounds [0, %d)\\n\"\n\t\t\t\ts = fmt.Sprintf(s, \"Avg()\", slice, m.r)\n\t\t\t\tprintErr(s)\n\t\t\t}\n\t\t\tfor i := 0; i < m.c; i++ {\n\t\t\t\tsum += m.vals[slice*m.c+i]\n\t\t\t}\n\t\t\tsum /= float32(m.c)\n\t\t} else if axis == 1 {\n\t\t\tif (slice >= m.c) || (slice < 0) {\n\t\t\t\ts := \"\\nIn %s the column %d is outside of bounds [0, %d)\\n\"\n\t\t\t\ts = fmt.Sprintf(s, \"Avg()\", slice, m.c)\n\t\t\t\tprintErr(s)\n\t\t\t}\n\t\t\tfor i := 0; i < m.r; i++ {\n\t\t\t\tsum += m.vals[i*m.c+slice]\n\t\t\t}\n\t\t\tsum /= float32(m.r)\n\t\t} else {\n\t\t\ts := \"\\nIn %s, the first argument must be 0 or 1, however %d \"\n\t\t\ts += \"was received.\\n\"\n\t\t\ts = fmt.Sprintf(s, \"Avg()\", axis)\n\t\t\tprintErr(s)\n\t\t}\n\tdefault:\n\t\ts := \"\\nIn %s, 0 or 2 arguments expected, but %d was received.\\n\"\n\t\ts = fmt.Sprintf(s, \"Avg()\", len(args))\n\t\tprintErr(s)\n\t}\n\treturn sum\n}",
"func (a *Array64) NaNMean(axis ...int) *Array64 {\n\tswitch {\n\tcase a.valAxis(&axis, \"Sum\"):\n\t\treturn a\n\t}\n\treturn a.NaNSum(axis...).Div(a.NaNCount(axis...))\n}",
"func CenteredAvg(xi []int) float64 {\n\tsort.Ints(xi) //=> arrange in ascending order\n\txi = xi[1 : len(xi)-1] //=> select whole data Except: first, last\n\n\tn := 0 //=> total\n\tfor _, v := range xi {\n\t\tn += v\n\t}\n\n\tf := float64(n) / float64(len(xi)) //=> total/number\n\treturn f\n}",
"func (m *Mantle) truncatedMidGap() uint64 {\n\tmidGap := midGap(m.book(), rateStep)\n\treturn truncate(int64(midGap), int64(rateStep))\n}",
"func trimLeadingEmptyRows(pxMatrix Matrix, limit int) Matrix {\n\tif len(pxMatrix) < 1 {\n\t\treturn pxMatrix\n\t}\n\tfor i := 0; i < limit; i++ {\n\t\tsum := 0\n\t\tfor _, n := range pxMatrix[0] {\n\t\t\tsum += n\n\t\t}\n\t\tif len(pxMatrix) > 0 && sum == 0 {\n\t\t\tpxMatrix = pxMatrix[1:]\n\t\t} else {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn pxMatrix\n}",
"func (o *WObj) GetMiddle() (float64, float64, int8) {\n\tpnt := o.Hitbox.GetMiddle()\n\treturn pnt.X, pnt.Y, o.layer\n}",
"func SquareMiddle(x, numDigits int) int {\n\tstringX := strconv.Itoa(x * x)\n\tif numDigits%2 != 0 || CountNumDigits(x) > 2*numDigits || x < 0 || numDigits <= 0 {\n\t\tpanic(\"Error! Please check your arguments\")\n\t}\n\tskipper := numDigits / 2\n\tbeginner := skipper\n\tend := len(stringX) - skipper\n\tfmt.Println(stringX)\n\tif len(stringX) == (2*numDigits)-1 {\n\t\tbeginner = skipper - 1\n\t}\n\tfmt.Println(len(stringX))\n\tres, err := strconv.Atoi(stringX[beginner:end])\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn res\n}",
"func Mean(values []float64) float64 {\n\tvar sum float64 = 0.0\n\tcount := 0\n\tfor _, d := range values {\n\t\tif !math.IsNaN(d) {\n\t\t\tsum += d\n\t\t\tcount++\n\t\t}\n\t}\n\treturn sum / float64(count)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
isNaN returns true if the given string can't be interpreted as a number.
|
func isNaN(val string) bool {
if val == nan {
return true
}
_, err := strconv.ParseFloat(val, 64)
return err != nil
}
|
[
"func isNumeric(s string) bool {\n _, err := strconv.ParseFloat(s, 64)\n return err == nil\n}",
"func isNum(str string) bool {\n\t_, err := strconv.Atoi(str)\n\treturn err == nil\n}",
"func IsNumber(s string) bool {\n\tif len(s) == 0 {\n\t\treturn false\n\t}\n\tfor _, r := range s {\n\t\tif !unicode.IsDigit(r) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func IsNumeric(str string) bool {\n\tif IsNull(str) {\n\t\treturn true\n\t}\n\treturn rxNumeric.MatchString(str)\n}",
"func IsNumeric(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\treturn err == nil\n}",
"func isnumberstring(a string) bool {\n\tif _, err := strconv.Atoi(a); err == nil {\n\t\treturn true\n\t}\n\tif _, err := strconv.ParseFloat(a, 64); err == nil {\n\t\treturn true\n\t}\n\treturn false\n}",
"func StringIsNumeric(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\treturn err == nil\n}",
"func IsNumber(str string) bool {\n\treg, _ := regexp.Compile(`^(\\-)?\\d+(\\.)?(\\d+)?$`)\n\treturn reg.MatchString(str)\n}",
"func IsNumeric(v any) bool {\n\tif v == nil {\n\t\treturn false\n\t}\n\n\tif s, err := strutil.ToString(v); err == nil {\n\t\treturn s != \"\" && rxNumber.MatchString(s)\n\t}\n\treturn false\n}",
"func IsStringNumber(s string) bool {\n\treturn s != \"\" && rxNumeric.MatchString(s)\n}",
"func isNum(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\tisFloat := (err == nil)\n\t_, err = strconv.ParseInt(s, 0, 64)\n\tisInt := (err == nil)\n\treturn isFloat || isInt\n}",
"func isNumber(s string) bool {\n\tfor _, r := range s {\n\t\tif !unicode.IsNumber(r) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func IsNumeric(str string) bool {\n\tfor _, c := range str {\n\t\tif !unicode.IsDigit(c) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}",
"func (s String) IsNumeric() bool {\n\treturn govalidator.IsFloat(s.String())\n}",
"func IsNumber(v any) bool {\n\tif v == nil {\n\t\treturn false\n\t}\n\n\tif s, err := strutil.ToString(v); err == nil {\n\t\treturn s != \"\" && rxNumber.MatchString(s)\n\t}\n\treturn false\n}",
"func IsStringNumber(s string) bool {\n\treturn s != \"\" && rxNumber.MatchString(s)\n}",
"func IsNumericValue(s string) bool {\n\t_, err := strconv.ParseFloat(s, 64)\n\treturn err == nil\n}",
"func ValidateStrNumeric(str string) bool { //\n\tvar re = regexp.MustCompile(`^[0-9]+$`)\n\tif len(re.FindStringIndex(str)) > 0 {\n\t\treturn true\n\t}\n\treturn false\n}",
"func isNumeric(b byte) bool {\n\treturn '0' <= b && b <= '9' ||\n\t\tb == ' '\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
averageOf returns the average of the given floats as a string, rounded to decimalPlaces decimal places. You can supply nil floats and they will be ignored. If you only supply nils, nan will be returned.
|
func averageOf(decimalPlaces int, floats ...*float64) string {
var total, num float64
for _, f := range floats {
if f == nil {
continue
}
num++
total += *f
}
if num == 0 {
return nan
}
return strconv.FormatFloat(total/num, 'f', decimalPlaces, 64)
}
|
[
"func meanFloat(data []float64) float64 {\n\t// sumFloat finds the sum of a list of floats. Exciting, I know.\n\tsumFloat := func(data []float64) (sum float64) {\n\t\tfor _, i := range data {\n\t\t\tsum += i\n\t\t}\n\t\treturn sum\n\t}\n\treturn sumFloat(data) / float64(len(data))\n}",
"func Average(slice []float64) (float64, error) {\n\n\tif len(slice) == 0 {\n\t\treturn math.NaN(), fmt.Errorf(\"Empty\")\n\t}\n\n\tvar sum float64\n\tfor _, n := range slice {\n\t\tsum += n\n\t}\n\n\tavg := sum / float64(len(slice))\n\t// log.Println(\"Slice average\", avg)\n\treturn math.Round(avg*100) / 100, nil\n}",
"func average(arr []float64) float64 {\n\treturn sum(arr) / float64(len(arr))\n}",
"func Average(input []float64) float64 {\n\treturn SumFloat64s(input) / float64(len(input))\n}",
"func ComputeAverage(dataPoints []float64) (float64, error) {\n\tif !(len(dataPoints) > 0) {\n\t\treturn 0.0, fmt.Errorf(\"Must provide a non empty collection of data points\")\n\t}\n\n\treturn stat.Mean(dataPoints, nil), nil\n}",
"func Average(items []Value) float64 {\n\tif len(items) == 0 {\n\t\treturn 0\n\t}\n\treturn float64(Sum(items)) / float64(len(items))\n}",
"func Average(x []float64) float64 {\n\treturn Sum(x) / float64(len(x))\n}",
"func average(sf ...float64) float64 {\n\t//Print the sf variable\n\tfmt.Println(sf)\n\t//Print the type of sf []float64\n\tfmt.Printf(\"%T \\n\", sf)\n\t//Create an accumulator\n\tvar total float64\n\t//For range loop through each item in sf\n\t//_ blank identifier used to throw away id from range\n\t//v for the value returned from range\n\tfor _, v := range sf {\n\t\ttotal += v\n\t}\n\t//Print how many arguments are taken in\n\tfmt.Println(len(sf))\n\treturn total / float64(len(sf))\n}",
"func (a *AggregateResult) Avg(field string) float64 {\n\tsum := a.Sum(field)\n\treturn sum / float64(len(a.reduction))\n}",
"func Average(nums []float64) float64 {\n\ttotal := float64(0)\n\tfor _, num := range nums {\n\t\ttotal += num\n\t}\n\treturn total / float64(len(nums))\n}",
"func average(arg1, arg2, arg3 float64) float64 {\n\ttotal := arg1 + arg2 + arg3\n\treturn total/3\n}",
"func Float64Average(attributePath string) (*aggregation.Float64Average, error) {\n\treturn aggregation.NewFloat64Average(attributePath)\n}",
"func (m *Model) FieldAvg(column string, as ...string) *Model {\n\tasStr := \"\"\n\tif len(as) > 0 && as[0] != \"\" {\n\t\tasStr = fmt.Sprintf(` AS %s`, m.db.GetCore().QuoteWord(as[0]))\n\t}\n\treturn m.appendFieldsByStr(fmt.Sprintf(`AVG(%s)%s`, m.QuoteWord(column), asStr))\n}",
"func TestAverageSingleValue(t *testing.T) {\n\tvar v float64\n\tv = Average([]float64{1, 2})\n\tif v != 1.5 {\n\t\tt.Error(\"expected 1.5, got \", v)\n\t}\n}",
"func Average(arr []float64) float64 {\n\tvar total float64\n\tfor _, value := range arr {\n\t\ttotal += value\n\t}\n\treturn total / float64(len(arr))\n}",
"func TestAverageRating(t *testing.T) {\n\t// List of ratings\n\ttests := []struct {\n\t\tinput Rating\n\t\texpected float64\n\t}{\n\t\t{Rating{0, 0, 0, 4, 0}, float64(4)},\n\t\t{Rating{0, 0, 0, 0, 0}, float64(0)},\n\t\t{Rating{0, 0, 0, 2, 2}, 4.5},\n\t\t{Rating{1, 2, 5, 2, 1}, float64(3)},\n\t}\n\n\t// Test\n\tfor _, test := range tests {\n\t\tif output := AverageRating(test.input); output != test.expected {\n\t\t\tt.Error(\"Test failed: {} inputted, {} expected, {} received\", test.input, test.expected, output)\n\t\t}\n\t}\n}",
"func (s Scores) Average() float32 {\n\tvar tot float32\n\tfor _, v := range s {\n\t\ttot += v\n\t}\n\treturn tot / float32(len(s))\n}",
"func Average(series []Series) (Series, error) {\n\treturn applyOperator(series, OperatorAverage)\n}",
"func FloatOrPanic(s string) float64 {\n\tf, err := strconv.ParseFloat(s, 64)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn f\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
valueAt returns the stringToFloat() of the value in the row at the given index position. If row is nil, returns nil.
|
func valueAt(row []string, position int) *float64 {
if row == nil {
return nil
}
return stringToFloat(row[position])
}
|
[
"func getValueAt(index int, colName string, header *[]string, content *[][]string) (string, error) {\n\n\tif index == -1 {\n\t\treturn \"0.0\", nil\n\t}\n\tindexCol := findIndex(colName, header)\n\tif indexCol < 0 {\n\t\treturn \"\", fmt.Errorf(\"column %s not found\", colName)\n\t}\n\tval := (*content)[index][indexCol]\n\tvalF, err := strconv.ParseFloat(val, 64)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn fmt.Sprintf(\"%.2f\", valF), nil\n}",
"func (vr VoltRows) GetFloat(colIndex int16) (interface{}, error) {\n\tbs, err := vr.table().getBytes(vr.table().rowIndex, colIndex)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(bs) != 8 {\n\t\treturn nil, fmt.Errorf(\"Did not find at FLOAT column at index %d\\n\", colIndex)\n\t}\n\tf := bytesToFloat(bs)\n\tif f == -1.7e+308 {\n\t\treturn nil, nil\n\t}\n\treturn f, nil\n}",
"func valueLeftOf(row []string, position int) *float64 {\n\tif position <= 0 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position-1])\n}",
"func valueRightOf(row []string, position int) *float64 {\n\tif position >= len(row)-1 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position+1])\n}",
"func (card *Card) ValueAt(cellName string) (int, error) {\n\tcell, err := card.cellAt(cellName)\n\tif err != nil {\n\t\treturn nan, err\n\t}\n\treturn cell.value, nil\n}",
"func (r Row) Value(column string) interface{} {\n\tif value, ok := r.Values[column]; ok {\n\t\treturn value\n\t}\n\treturn nil\n}",
"func (r ResultTable) GetFloat(rowIndex int, columnIndex int) float32 {\n\tval, _ := (r.Rows[rowIndex][columnIndex]).(json.Number).Float64()\n\treturn float32(val)\n}",
"func (seq Sequence) ValueAt(period int, e expr.Expr) (val float64, found bool) {\n\tif e.IsConstant() {\n\t\tval, found, _ = e.Get(nil)\n\t\treturn\n\t}\n\tif len(seq) == 0 {\n\t\treturn 0, false\n\t}\n\tif period < 0 {\n\t\treturn 0, false\n\t}\n\treturn seq.ValueAtOffset(period*e.EncodedWidth(), e)\n}",
"func (rows VoltRows) GetStringValue(valtype int8, colIndex int16) (string, error) {\n\tswitch valtype {\n\tcase 3:\n\t\ti, err := rows.GetTinyInt(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif i == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%d\", i.(int8)), nil\n\tcase 4:\n\t\ti, err := rows.GetSmallInt(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif i == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%d\", i.(int16)), nil\n\tcase 5:\n\t\ti, err := rows.GetInteger(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif i == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%d\", i.(int32)), nil\n\tcase 6:\n\t\ti, err := rows.GetBigInt(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif i == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%d\", i.(int64)), nil\n\tcase 8:\n\t\ti, err := rows.GetFloat(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif i == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%f\", i.(float64)), nil\n\tcase 11:\n\t\tt, err := rows.GetTimestamp(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif t == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn t.(time.Time).String(), nil\n\tcase 22:\n\t\tt, err := rows.GetDecimal(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif t == nil {\n\t\t\treturn \"0\", nil\n\t\t}\n\t\treturn fmt.Sprintf(\"%v\", t.(big.Float)), nil\n\tcase 25:\n\t\tt, err := rows.GetVarbinary(colIndex)\n\t\tif err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\tif t == nil {\n\t\t\treturn \"\", nil\n\t\t}\n\t\treturn string(t.([]byte)), nil\n\t}\n\tif valtype != 9 {\n\t\treturn \"\", errors.New(\"Unsupported type for GetStringValue\")\n\t}\n\t// type 9 is string\n\ts, err := rows.GetString(colIndex)\n\tif err != nil || s == nil {\n\t\treturn \"\", err\n\t}\n\treturn s.(string), nil\n}",
"func (r *sparseRow) Value(feature int) float64 {\n\ti := search(r.ind, feature)\n\tif i >= 0 {\n\t\treturn r.val[i]\n\t}\n\treturn 0\n}",
"func (v valuer) Value(i int) float64 {\n\treturn v.data[i]\n}",
"func (vm *VirtualMachine) getValueForElement(e quads.Element) interface{} {\n\tif strings.Contains(e.ID(), \"ptr_\") {\n\t\tmemblock := vm.getMemBlockForAddr(e.GetAddr())\n\t\tptrAddr, ok := memblock.Get(e.GetAddr()).(float64)\n\t\tif !ok {\n\t\t\tlog.Fatalf(\"Error: (getValueForElement) couldn't cast index to float64\")\n\t\t}\n\n\t\tauxElement := quads.NewElement(int(ptrAddr), e.ID(), e.Type(), \"\")\n\t\tmemblock = vm.getMemBlockForElement(auxElement)\n\t\trealValue := memblock.Get(int(ptrAddr))\n\t\treturn realValue\n\t}\n\tmemblock := vm.getMemBlockForElement(e)\n\treturn memblock.Get(e.GetAddr())\n}",
"func (d Datapoints) ValueAt(n int) float64 { return d[n].Value }",
"func (f *Field) FloatAt(idx int) (float64, error) {\n\tswitch f.Type() {\n\tcase FieldTypeInt8:\n\t\treturn float64(f.At(idx).(int8)), nil\n\tcase FieldTypeNullableInt8:\n\t\tiv := f.At(idx).(*int8)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt16:\n\t\treturn float64(f.At(idx).(int16)), nil\n\tcase FieldTypeNullableInt16:\n\t\tiv := f.At(idx).(*int16)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt32:\n\t\treturn float64(f.At(idx).(int32)), nil\n\tcase FieldTypeNullableInt32:\n\t\tiv := f.At(idx).(*int32)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeInt64:\n\t\treturn float64(f.At(idx).(int64)), nil\n\tcase FieldTypeNullableInt64:\n\t\tiv := f.At(idx).(*int64)\n\t\tif iv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*iv), nil\n\n\tcase FieldTypeUint8:\n\t\treturn float64(f.At(idx).(uint8)), nil\n\tcase FieldTypeNullableUint8:\n\t\tuiv := f.At(idx).(*uint8)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeUint16:\n\t\treturn float64(f.At(idx).(uint16)), nil\n\tcase FieldTypeNullableUint16:\n\t\tuiv := f.At(idx).(*uint16)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeUint32:\n\t\treturn float64(f.At(idx).(uint32)), nil\n\tcase FieldTypeNullableUint32:\n\t\tuiv := f.At(idx).(*uint32)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\t// TODO: third param for loss of precision?\n\t// Maybe something in math/big can help with this (also see https://github.com/golang/go/issues/29463).\n\tcase FieldTypeUint64:\n\t\treturn float64(f.At(idx).(uint64)), nil\n\tcase FieldTypeNullableUint64:\n\t\tuiv := f.At(idx).(*uint64)\n\t\tif uiv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*uiv), nil\n\n\tcase FieldTypeFloat32:\n\t\treturn float64(f.At(idx).(float32)), nil\n\tcase FieldTypeNullableFloat32:\n\t\tfv := f.At(idx).(*float32)\n\t\tif fv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(*fv), nil\n\n\tcase FieldTypeFloat64:\n\t\treturn f.At(idx).(float64), nil\n\tcase FieldTypeNullableFloat64:\n\t\tfv := f.At(idx).(*float64)\n\t\tif fv == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn *fv, nil\n\n\tcase FieldTypeString:\n\t\ts := f.At(idx).(string)\n\t\tft, err := strconv.ParseFloat(s, 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn ft, nil\n\tcase FieldTypeNullableString:\n\t\ts := f.At(idx).(*string)\n\t\tif s == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\tft, err := strconv.ParseFloat(*s, 64)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn ft, nil\n\n\tcase FieldTypeBool:\n\t\tif f.At(idx).(bool) {\n\t\t\treturn 1, nil\n\t\t}\n\t\treturn 0, nil\n\n\tcase FieldTypeNullableBool:\n\t\tb := f.At(idx).(*bool)\n\t\tif b == nil || !*b {\n\t\t\treturn 0, nil\n\t\t}\n\t\treturn 1, nil\n\n\tcase FieldTypeTime:\n\t\treturn float64(f.At(idx).(time.Time).UnixNano() / int64(time.Millisecond)), nil\n\tcase FieldTypeNullableTime:\n\t\tt := f.At(idx).(*time.Time)\n\t\tif t == nil {\n\t\t\treturn math.NaN(), nil\n\t\t}\n\t\treturn float64(t.UnixNano() / int64(time.Millisecond)), nil\n\t}\n\treturn 0, fmt.Errorf(\"unsupported field type %T\", f.Type())\n}",
"func (seq Sequence) ValueAtOffset(offset int, e expr.Expr) (val float64, found bool) {\n\tif e.IsConstant() {\n\t\tval, found, _ = e.Get(nil)\n\t\treturn\n\t}\n\tif len(seq) == 0 {\n\t\treturn 0, false\n\t}\n\toffset = offset + Width64bits\n\tif offset >= len(seq) {\n\t\treturn 0, false\n\t}\n\tval, wasSet, _ := e.Get(seq[offset:])\n\treturn val, wasSet\n}",
"func (t *TSMReader) ReadFloatBlockAt(entry *IndexEntry, vals *[]FloatValue) ([]FloatValue, error) {\n\tt.mu.RLock()\n\tv, err := t.accessor.readFloatBlock(entry, vals)\n\tt.mu.RUnlock()\n\treturn v, err\n}",
"func (this *Row) StringAtIndex(i int) string {\n\tif i >= len(this.values) {\n\t\treturn \"<nil>\"\n\t} else {\n\t\treturn fmt.Sprint(this.values[i])\n\t}\n}",
"func (tr Row) FloatErr(nn int) (val float64, err error) {\n\tswitch data := tr[nn].(type) {\n\tcase nil:\n\t\t// nop\n\tcase float64, float32:\n\t\tval = reflect.ValueOf(data).Float()\n\tcase int64, int32, int16, int8:\n\t\ti := reflect.ValueOf(data).Int()\n\t\tif i >= 2<<53 || i <= -(2<<53) {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(i)\n\t\t}\n\tcase uint64, uint32, uint16, uint8:\n\t\tu := reflect.ValueOf(data).Uint()\n\t\tif u >= 2<<53 {\n\t\t\terr = strconv.ErrRange\n\t\t} else {\n\t\t\tval = float64(u)\n\t\t}\n\tcase []byte:\n\t\tval, err = strconv.ParseFloat(string(data), 64)\n\tdefault:\n\t\terr = os.ErrInvalid\n\t}\n\treturn\n}",
"func (r *Resultset) GetValue(row, column int) (interface{}, error) {\n\tif row >= len(r.Values) || row < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid row index %d\", row)\n\t}\n\n\tif column >= len(r.Fields) || column < 0 {\n\t\treturn nil, fmt.Errorf(\"invalid column index %d\", column)\n\t}\n\n\treturn r.Values[row][column], nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
stringToFloat converts the given string to a float. If the string is "nan", or otherwise not interpretable as a float, returns nil.
|
func stringToFloat(num string) *float64 {
if num == nan {
return nil
}
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return nil
}
return &f
}
|
[
"func StringToFloat(s string) (float64, error) {\n\tif s == \"\" {\n\t\treturn 0, errors.New(\"string is not f\u0001loat\")\n\t}\n\n\tif f, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn f, nil\n\t}\n\n\treturn 0, errors.New(\"string is not float\")\n}",
"func StringToFloat(str String) Float {\n\tv := &stringToFloat{from: str}\n\tstr.AddListener(v)\n\treturn v\n}",
"func StringToFloat(input string) float64 {\n\tvalue, err := strconv.ParseFloat(input, 64)\n\tif err != nil {\n\t\treturn 0\n\t}\n\n\treturn value\n}",
"func StringToFloat(str string) float64 {\r\n\r\n\tf, _ := strconv.ParseFloat(str, 8)\r\n\r\n\treturn f\r\n}",
"func strToFloat(str string) float64 {\n\tf, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tpanic(\"Fail\")\n\t}\n\treturn f\n}",
"func (u *Util) StringToFloat(value interface{}) (number float32, err error) {\n number = -999\n if s,ok := value.(string); ok {\n price, err := strconv.ParseFloat(s, 32)\n if err == nil { number = float32(price) }\n } else {\n err = errors.New(\"variable is not string\")\n }\n return number, err\n}",
"func ConvertStringToFloat(str string) float64 {\n\ts, err := strconv.ParseFloat(str, 64)\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn s\n}",
"func StrToFloat(s string) float64 {\n\tif n, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn n\n\t}\n\treturn float64(0.0)\n}",
"func strToFloatKind(value string, kind reflect.Kind) (float64, error) {\n\tvar min, max float64\n\n\t// For empty string returns zero.\n\tif len(value) == 0 {\n\t\treturn 0.0, nil\n\t}\n\n\t// Convert string to Float64.\n\tr, err := strconv.ParseFloat(value, 64)\n\tif err != nil {\n\t\treturn 0.0, err\n\t}\n\n\t// Out of range checking.\n\tswitch kind {\n\tcase reflect.Float32:\n\t\tmin, max = -math.MaxFloat32, math.MaxFloat32\n\tcase reflect.Float64:\n\t\tmin, max = -math.MaxFloat64, math.MaxFloat64\n\tdefault:\n\t\treturn 0.0, fmt.Errorf(\"incorrect kind %v\", kind)\n\t}\n\n\tif r < min || r > max {\n\t\treturn 0.0, fmt.Errorf(\"%f is out of range for %v\", r, kind)\n\t}\n\n\treturn r, nil\n}",
"func ParseToFloat(data string) (float64, error) {\n\treturn strconv.ParseFloat(data, 0)\n}",
"func StringToFloatWithFormat(str String, format string) Float {\n\tif format == \"%f\" { // Same as not using custom format.\n\t\treturn StringToFloat(str)\n\t}\n\n\tv := &stringToFloat{from: str, format: format}\n\tstr.AddListener(v)\n\treturn v\n}",
"func toFloat(str string) (float64, error) {\n\tres, err := strconv.ParseFloat(str, 64)\n\tif err != nil {\n\t\tres = 0.0\n\t}\n\treturn res, err\n}",
"func StringAsFloat(s string, decimalSeparator, thousandsSeparator rune) float64 {\n\tif s == \"\" {\n\t\treturn 0.0\n\t}\n\n\tconst maxLength = 20\n\n\tif len([]rune(s)) > maxLength {\n\t\ts = s[0:maxLength]\n\t}\n\n\ts = strings.Replace(s, string(thousandsSeparator), \"\", -1)\n\n\ts = strings.Replace(s, string(decimalSeparator), \".\", -1)\n\n\tif f, err := strconv.ParseFloat(s, 64); err == nil {\n\t\treturn f\n\t}\n\n\treturn 0.0\n}",
"func TestStrToFloat(t *testing.T) {\n\tstrList := []StrToFloatTest{\n\t\t{\"1\", 1.0},\n\t\t{\"2,234.5 \", 2234.5},\n\t\t{\" 3,345,456.123\", 3345456.123},\n\t\t{\"-9234.43\", -9234.43},\n\t\t{\"asd\", 0},\n\t}\n\n\tfor i, str := range strList {\n\t\tnumFloat := StrToFloat(str.NumStr)\n\t\tif !reflect.DeepEqual(str.NumFloat, numFloat) {\n\t\t\tt.Errorf(\"StrToFloat(%v) failed: expected %v got %v\", i, str.NumFloat, numFloat)\n\t\t}\n\t}\n}",
"func IsFloat(str string) bool {\n\treturn str != \"\" && rxFloat.MatchString(str)\n}",
"func (app *AppCtx) ConvertPercentageStringToFloat(value string) (float64, error) {\n\tvar f float64\n\tvar err error\n\n\tif value[len(value)-1:] != \"%\" {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s that did not end with '%%' character\", value)\n\t}\n\tif f, err = strconv.ParseFloat(value[0:len(value)-1], 64); err != nil {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s with a non-numerical value before the %%\", value)\n\t}\n\tif f < 0 {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s with a negative percentage\", value)\n\t}\n\tif f > 100 {\n\t\treturn -1.0, fmt.Errorf(\"expected PERCENTAGE value but got %s which is over 100%%\", value)\n\t}\n\treturn f, err\n}",
"func StringToFloat32(val interface{}) interface{} {\n\tv, ok := val.(string)\n\tif !ok {\n\t\treturn val\n\t}\n\trs, err := strconv.ParseFloat(v, 32)\n\tif err != nil {\n\t\treturn 0\n\t}\n\treturn rs\n}",
"func ParseFloat(s string, base int, prec uint, mode RoundingMode) (f *Float, b int, err error) {}",
"func LooksLikeAFloat(inputStr string) (matched bool, value float64) {\n\tmatched = floatRe.MatchString(inputStr)\n\tif matched {\n\t\tvalue, _ = strconv.ParseFloat(inputStr, 64)\n\t\treturn true, value\n\t}\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
valueLeftOf returns the stringToFloat() of the value to the left of the given index in the row. If i is 0, returns nil.
|
func valueLeftOf(row []string, position int) *float64 {
if position <= 0 {
return nil
}
return stringToFloat(row[position-1])
}
|
[
"func valueRightOf(row []string, position int) *float64 {\n\tif position >= len(row)-1 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position+1])\n}",
"func (o *WorkbookChart) GetLeft() AnyOfnumberstringstring {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret\n\t}\n\treturn *o.Left\n}",
"func (b *Bound) Left() float64 {\n\treturn b.sw[0]\n}",
"func (f fieldElement) leftShift(i uint) (result fieldElement) {\n\t// 0 <= i < 128\n\tif i < 64 {\n\t\tcopy(result[:], f[:])\n\t} else if i < 128 {\n\t\tresult[1] = f[0]\n\t\tresult[2] = f[1]\n\t\tresult[3] = f[2]\n\t\ti -= 64\n\t} else {\n\t\tpanic(\"leftShift argument out of range\")\n\t}\n\n\tresult[3] = result[3]<<i | result[2]>>(64-i)\n\tresult[2] = result[2]<<i | result[1]>>(64-i)\n\tresult[1] = result[1]<<i | result[0]>>(64-i)\n\tresult[0] = result[0] << i\n\n\treturn result\n}",
"func valueAt(row []string, position int) *float64 {\n\tif row == nil {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position])\n}",
"func (self SimpleInterval) Left() float64 {\n\treturn self.LR[0]\n}",
"func (rect *simpleRectangle) Left() float32 {\n\treturn rect[0]\n}",
"func (proof *RangeProof) LeftIndex() int64 {\n\tif proof == nil {\n\t\treturn -1\n\t}\n\treturn proof.LeftPath.Index()\n}",
"func (o *TileBounds) GetLeft() int32 {\n\tif o == nil || o.Left == nil {\n\t\tvar ret int32\n\t\treturn ret\n\t}\n\treturn *o.Left\n}",
"func (o *WorkbookChart) GetLeftOk() (AnyOfnumberstringstring, bool) {\n\tif o == nil || o.Left == nil {\n\t\tvar ret AnyOfnumberstringstring\n\t\treturn ret, false\n\t}\n\treturn *o.Left, true\n}",
"func ColumnLeft(name string) {\n\tidx := colIndex(name)\n\tif idx > 0 {\n\t\tswapCols(idx, idx-1)\n\t}\n}",
"func (m *Memory) Left() {\n\tm.CurrentCell--\n\t// return m.GetCurrentCell().Value\n}",
"func (this *Tuple) Left(n int) *Tuple {\n\treturn this.Slice(0, n)\n}",
"func getValueOfLeftmostNode(node *Node) int {\n\tcurrentNode := node\n\n\t// traverse as far left into the tree\n\t// to find the leftmost node\n\tfor currentNode.left != nil {\n\t\tcurrentNode = currentNode.left\n\t}\n\n\treturn currentNode.value\n}",
"func Command_Left(script *rex.Script, params []*rex.Value) {\n\tif len(params) != 2 {\n\t\trex.ErrorParamCount(\"str:left\", \"2\")\n\t}\n\n\tindex := int(params[1].Int64())\n\tstr := params[0].String()\n\tif len(str) < index {\n\t\tscript.RetVal = rex.NewValueString(str)\n\t\tscript.Error = true\n\t\treturn\n\t}\n\tscript.RetVal = rex.NewValueString(string([]byte(str))[:index])\n}",
"func (p Point) Left() int32 {\n\treturn p.X\n}",
"func (r *Reader) LeftBytes() []byte {\n\tskip := r.idx >> 3\n\tif skip >= r.size {\n\t\treturn r.src[:0]\n\t}\n\treturn r.src[skip:r.size]\n}",
"func (b *TestDriver) Left(val int) error {\n\tlog.Printf(\"Left: %d\", val)\n\treturn nil\n}",
"func (me *BitStream) Left() int {\n\treturn me.Bits - me.Index\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
valueRightOf returns the stringToFloat() of the value to the right of the given index in the row. If i is the last element, returns nil.
|
func valueRightOf(row []string, position int) *float64 {
if position >= len(row)-1 {
return nil
}
return stringToFloat(row[position+1])
}
|
[
"func valueLeftOf(row []string, position int) *float64 {\n\tif position <= 0 {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position-1])\n}",
"func (b *Bound) Right() float64 {\n\treturn b.ne[0]\n}",
"func (self SimpleInterval) Right() float64 {\n\treturn self.LR[1]\n}",
"func Command_Right(script *rex.Script, params []*rex.Value) {\n\tif len(params) != 2 {\n\t\trex.ErrorParamCount(\"str:right\", \"2\")\n\t}\n\n\tindex := int(params[1].Int64())\n\tstr := params[0].String()\n\tif len(str) < index {\n\t\tscript.RetVal = rex.NewValueString(str)\n\t\tscript.Error = true\n\t\treturn\n\t}\n\tscript.RetVal = rex.NewValueString(string([]byte(str))[len(str)-index:])\n}",
"func Right(value string, length int) string {\n\ts := max(0, len([]rune(value))-length)\n\treturn value[s:]\n}",
"func (rect *simpleRectangle) Right() float32 {\n\treturn rect[2]\n}",
"func (this *Tuple) Right(n int) *Tuple {\n\tlength := this.Len()\n\tn = max(0, length-n)\n\treturn this.Slice(n, length)\n}",
"func (matrix Matrix4) Right() vector.Vector {\n\treturn vector.Vector{\n\t\tmatrix[0][0],\n\t\tmatrix[0][1],\n\t\tmatrix[0][2],\n\t}.Unit()\n}",
"func (H *Heap) Right(i *int) *int {\n\tr := 2 * (*i)\n\tr = r + 2\n\treturn &r\n}",
"func (q Quat) Right() Vec3f {\n\treturn q.RotateVec(Vec3f{1, 0, 0})\n}",
"func ColumnRight(name string) {\n\tidx := colIndex(name)\n\tif idx < len(GlobalColumns)-1 {\n\t\tswapCols(idx, idx+1)\n\t}\n}",
"func valueAt(row []string, position int) *float64 {\n\tif row == nil {\n\t\treturn nil\n\t}\n\n\treturn stringToFloat(row[position])\n}",
"func (s Square) Right() int {\n\treturn s.left + s.width\n}",
"func (m *Memory) Right() {\n\tm.CurrentCell++\n\t// return m.GetCurrentCell().Value\n}",
"func (v *TypePair) GetRight() (o *Type) {\n\tif v != nil {\n\t\to = v.Right\n\t}\n\treturn\n}",
"func (d *Deque) Right() interface{} {\n\tif d.rightOff > 0 {\n\t\treturn d.right[d.rightOff-1]\n\t} else {\n\t\treturn d.blocks[(d.rightIdx-1+len(d.blocks))%len(d.blocks)][blockSize-1]\n\t}\n}",
"func Right(i interface{}) Either {\n\treturn RightType{i}\n}",
"func (b *TestDriver) Right(val int) error {\n\tlog.Printf(\"Right: %d\", val)\n\n\treturn nil\n}",
"func (_this *TextMetrics) ActualBoundingBoxRight() float64 {\n\tvar ret float64\n\tvalue := _this.Value_JS.Get(\"actualBoundingBoxRight\")\n\tret = (value).Float()\n\treturn ret\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NextRow returns the next row of CSV data as a slice of strings, with any nan values in the input data replaced with interpreted values.
|
func (c *CSVInterpolator) NextRow() ([]string, error) {
c.row++
rowsToGet := c.numRows()
rows, err := c.rp.GetRows(c.rowToStartWith(), rowsToGet)
if err != nil {
return nil, err
}
if rowsToGet != rowsNeededToInterpolate {
rows = [][]string{nil, rows[0], rows[1]}
}
if rows[1] == nil {
return nil, io.EOF
}
return MiddleRow(rows, c.decimalPlaces), nil
}
|
[
"func (sv *sorterValues) NextRow() sqlbase.EncDatumRow {\n\tif len(sv.rows) == 0 {\n\t\treturn nil\n\t}\n\n\tx := heap.Pop(sv)\n\treturn *x.(*sqlbase.EncDatumRow)\n}",
"func TableNextRow() {\n\tTableNextRowV(0, 0.0)\n}",
"func (rr *rowReader) Next() (err error) {\n\tif rr.done {\n\t\treturn nil\n\t}\n\n\trr.row, err = rr.reader.ReadRow()\n\tif err != nil {\n\t\tif err.Error() == \"EOF\" {\n\t\t\trr.done = true\n\t\t\treturn nil\n\t\t}\n\t}\n\trr.i++\n\treturn\n}",
"func (pr *newPartialResult) Next() (data []types.Datum, err error) {\n\tchunk := pr.getChunk()\n\tif chunk == nil {\n\t\treturn nil, nil\n\t}\n\tdata = make([]types.Datum, pr.rowLen)\n\tfor i := 0; i < pr.rowLen; i++ {\n\t\tvar l []byte\n\t\tl, chunk.RowsData, err = codec.CutOne(chunk.RowsData)\n\t\tif err != nil {\n\t\t\treturn nil, errors.Trace(err)\n\t\t}\n\t\tdata[i].SetRaw(l)\n\t}\n\treturn\n}",
"func (itr *doltTableRowIter) Next() (sql.Row, error) {\n\treturn itr.reader.ReadSqlRow(itr.ctx)\n}",
"func (q *QueryTableResult) Next() bool {\n\tvar row []string\n\t// set closing query in case of preliminary return\n\tcloser := func() {\n\t\tif err := q.Close(); err != nil {\n\t\t\tmessage := err.Error()\n\t\t\tif q.err != nil {\n\t\t\t\tmessage = fmt.Sprintf(\"%s,%s\", message, q.err.Error())\n\t\t\t}\n\t\t\tq.err = errors.New(message)\n\t\t}\n\t}\n\tdefer func() {\n\t\tcloser()\n\t}()\n\tparsingState := parsingStateNormal\n\tq.tableChanged = false\n\tdataTypeAnnotationFound := false\nreadRow:\n\trow, q.err = q.csvReader.Read()\n\tif q.err == io.EOF {\n\t\tq.err = nil\n\t\treturn false\n\t}\n\tif q.err != nil {\n\t\treturn false\n\t}\n\n\tif len(row) <= 1 {\n\t\tgoto readRow\n\t}\n\tif len(row[0]) > 0 && row[0][0] == '#' {\n\t\tif parsingState == parsingStateNormal {\n\t\t\tq.table = query.NewFluxTableMetadata(q.tablePosition)\n\t\t\tq.tablePosition++\n\t\t\tq.tableChanged = true\n\t\t\tfor i := range row[1:] {\n\t\t\t\tq.table.AddColumn(query.NewFluxColumn(i))\n\t\t\t}\n\t\t\tparsingState = parsingStateAnnotation\n\t\t}\n\t}\n\tif q.table == nil {\n\t\tq.err = errors.New(\"parsing error, annotations not found\")\n\t\treturn false\n\t}\n\tif len(row)-1 != len(q.table.Columns()) {\n\t\tq.err = fmt.Errorf(\"parsing error, row has different number of columns than the table: %d vs %d\", len(row)-1, len(q.table.Columns()))\n\t\treturn false\n\t}\n\tswitch row[0] {\n\tcase \"\":\n\t\tswitch parsingState {\n\t\tcase parsingStateAnnotation:\n\t\t\tif !dataTypeAnnotationFound {\n\t\t\t\tq.err = errors.New(\"parsing error, datatype annotation not found\")\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tparsingState = parsingStateNameRow\n\t\t\tfallthrough\n\t\tcase parsingStateNameRow:\n\t\t\tif row[1] == \"error\" {\n\t\t\t\tparsingState = parsingStateError\n\t\t\t} else {\n\t\t\t\tfor i, n := range row[1:] {\n\t\t\t\t\tif q.table.Column(i) != nil {\n\t\t\t\t\t\tq.table.Column(i).SetName(n)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tparsingState = parsingStateNormal\n\t\t\t}\n\t\t\tgoto readRow\n\t\tcase parsingStateError:\n\t\t\tvar message string\n\t\t\tif len(row) > 1 && len(row[1]) > 0 {\n\t\t\t\tmessage = row[1]\n\t\t\t} else {\n\t\t\t\tmessage = \"unknown query error\"\n\t\t\t}\n\t\t\treference := \"\"\n\t\t\tif len(row) > 2 && len(row[2]) > 0 {\n\t\t\t\treference = fmt.Sprintf(\",%s\", row[2])\n\t\t\t}\n\t\t\tq.err = fmt.Errorf(\"%s%s\", message, reference)\n\t\t\treturn false\n\t\t}\n\t\tvalues := make(map[string]interface{})\n\t\tfor i, v := range row[1:] {\n\t\t\tif q.table.Column(i) != nil {\n\t\t\t\tvalues[q.table.Column(i).Name()], q.err = toValue(stringTernary(v, q.table.Column(i).DefaultValue()), q.table.Column(i).DataType(), q.table.Column(i).Name())\n\t\t\t\tif q.err != nil {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tq.record = query.NewFluxRecord(q.table.Position(), values)\n\tcase \"#datatype\":\n\t\tdataTypeAnnotationFound = true\n\t\tfor i, d := range row[1:] {\n\t\t\tif q.table.Column(i) != nil {\n\t\t\t\tq.table.Column(i).SetDataType(d)\n\t\t\t}\n\t\t}\n\t\tgoto readRow\n\tcase \"#group\":\n\t\tfor i, g := range row[1:] {\n\t\t\tif q.table.Column(i) != nil {\n\t\t\t\tq.table.Column(i).SetGroup(g == \"true\")\n\t\t\t}\n\t\t}\n\t\tgoto readRow\n\tcase \"#default\":\n\t\tfor i, c := range row[1:] {\n\t\t\tif q.table.Column(i) != nil {\n\t\t\t\tq.table.Column(i).SetDefaultValue(c)\n\t\t\t}\n\t\t}\n\t\tgoto readRow\n\t}\n\t// don't close query\n\tcloser = func() {}\n\treturn true\n}",
"func (s *orderedSynchronizer) NextRow() (sqlbase.EncDatumRow, error) {\n\tif !s.initialized {\n\t\tif err := s.initHeap(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts.initialized = true\n\t} else {\n\t\t// Last row returned was from the source at the root of the heap; get\n\t\t// the next row for that source.\n\t\tif err := s.advanceRoot(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif len(s.heap) == 0 {\n\t\treturn nil, nil\n\t}\n\treturn s.sources[s.heap[0]].row, nil\n}",
"func (r *result) Next(dest []driver.Value) error {\n\tif r.data == nil {\n\t\tif err := r.readNext(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tfor i := 0; i < len(r.columns); i++ {\n\t\tkey := r.columns[i]\n\t\tval := r.data[key]\n\t\tdest[i] = val\n\t}\n\tr.data = nil\n\tr.offset++\n\treturn nil\n}",
"func (p *postgreStreamCopy) Next() (copyData, error) {\n\tvar row copyData\n\t// the current field being read.\n\tvar field []byte\n\n\taddField := func() error {\n\t\t// COPY does its backslash removal after the entire field has been extracted\n\t\t// so it can compare to the NULL setting earlier.\n\t\tif string(field) == p.null {\n\t\t\trow = append(row, nil)\n\t\t} else {\n\t\t\t// Use the same backing store since we are guaranteed to only remove\n\t\t\t// characters.\n\t\t\tnf := field[:0]\n\t\t\tfor i := 0; i < len(field); i++ {\n\t\t\t\tif field[i] == '\\\\' {\n\t\t\t\t\ti++\n\t\t\t\t\tif len(field) <= i {\n\t\t\t\t\t\treturn errors.New(\"unmatched escape\")\n\t\t\t\t\t}\n\t\t\t\t\t// See https://www.postgresql.org/docs/current/static/sql-copy.html\n\t\t\t\t\tc := field[i]\n\t\t\t\t\tswitch c {\n\t\t\t\t\tcase 'b':\n\t\t\t\t\t\tnf = append(nf, '\\b')\n\t\t\t\t\tcase 'f':\n\t\t\t\t\t\tnf = append(nf, '\\f')\n\t\t\t\t\tcase 'n':\n\t\t\t\t\t\tnf = append(nf, '\\n')\n\t\t\t\t\tcase 'r':\n\t\t\t\t\t\tnf = append(nf, '\\r')\n\t\t\t\t\tcase 't':\n\t\t\t\t\t\tnf = append(nf, '\\t')\n\t\t\t\t\tcase 'v':\n\t\t\t\t\t\tnf = append(nf, '\\v')\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tif c == 'x' || (c >= '0' && c <= '9') {\n\t\t\t\t\t\t\t// Handle \\xNN and \\NNN hex and octal escapes.)\n\t\t\t\t\t\t\tif len(field) <= i+2 {\n\t\t\t\t\t\t\t\treturn errors.Errorf(\"unsupported escape sequence: \\\\%s\", field[i:])\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tbase := 8\n\t\t\t\t\t\t\tidx := 0\n\t\t\t\t\t\t\tif c == 'x' {\n\t\t\t\t\t\t\t\tbase = 16\n\t\t\t\t\t\t\t\tidx = 1\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tv, err := strconv.ParseInt(string(field[i+idx:i+3]), base, 8)\n\t\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti += 2\n\t\t\t\t\t\t\tnf = append(nf, byte(v))\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tnf = append(nf, string(c)...)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnf = append(nf, field[i])\n\t\t\t\t}\n\t\t\t}\n\t\t\tns := string(nf)\n\t\t\trow = append(row, &ns)\n\t\t}\n\t\tfield = field[:0]\n\t\treturn nil\n\t}\n\n\t// Attempt to read an entire line.\n\tscanned := p.s.Scan()\n\tif err := p.s.Err(); err != nil {\n\t\tif errors.Is(err, bufio.ErrTooLong) {\n\t\t\terr = wrapWithLineTooLongHint(\n\t\t\t\terrors.New(\"line too long\"),\n\t\t\t)\n\t\t}\n\t\treturn nil, err\n\t}\n\tif !scanned {\n\t\treturn nil, io.EOF\n\t}\n\t// Check for the copy done marker.\n\tif bytes.Equal(p.s.Bytes(), []byte(`\\.`)) {\n\t\treturn nil, errCopyDone\n\t}\n\treader := bytes.NewReader(p.s.Bytes())\n\n\tvar sawBackslash bool\n\t// Start by finding field delimiters.\n\tfor {\n\t\tc, w, err := reader.ReadRune()\n\t\tif err == io.EOF {\n\t\t\tbreak\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif c == unicode.ReplacementChar && w == 1 {\n\t\t\treturn nil, errors.New(\"error decoding UTF-8 Rune\")\n\t\t}\n\n\t\t// We only care about backslashes here if they are followed by a field\n\t\t// delimiter. Otherwise we pass them through. They will be escaped later on.\n\t\tif sawBackslash {\n\t\t\tsawBackslash = false\n\t\t\tif c == p.delimiter {\n\t\t\t\tfield = append(field, string(p.delimiter)...)\n\t\t\t} else {\n\t\t\t\tfield = append(field, '\\\\')\n\t\t\t\tfield = append(field, string(c)...)\n\t\t\t}\n\t\t\tcontinue\n\t\t} else if c == '\\\\' {\n\t\t\tsawBackslash = true\n\t\t\tcontinue\n\t\t}\n\n\t\tconst rowSeparator = '\\n'\n\t\t// Are we done with the field?\n\t\tif c == p.delimiter || c == rowSeparator {\n\t\t\tif err := addField(); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\tfield = append(field, string(c)...)\n\t\t}\n\t}\n\tif sawBackslash {\n\t\treturn nil, errors.Errorf(\"unmatched escape\")\n\t}\n\t// We always want to call this because there's at least 1 field per row. If\n\t// the row is empty we should return a row with a single, empty field.\n\tif err := addField(); err != nil {\n\t\treturn nil, err\n\t}\n\treturn row, nil\n}",
"func (r *Recordset) Next() (row *ast.Row, err error) {\n\tif r.cursor == len(r.rows) {\n\t\treturn\n\t}\n\trow = &ast.Row{Data: r.rows[r.cursor]}\n\tr.cursor++\n\treturn\n}",
"func (tr *tableReader) nextRow() (sqlbase.EncDatumRow, error) {\n\tfor {\n\t\tfetcherRow, err := tr.fetcher.NextRow()\n\t\tif err != nil || fetcherRow == nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// TODO(radu): we are defeating the purpose of EncDatum here - we\n\t\t// should modify RowFetcher to return EncDatums directly and avoid\n\t\t// the cost of decoding/reencoding.\n\t\tfor i := range fetcherRow {\n\t\t\tif fetcherRow[i] != nil {\n\t\t\t\ttr.row[i].SetDatum(tr.desc.Columns[i].Type.Kind, fetcherRow[i])\n\t\t\t}\n\t\t}\n\t\tpassesFilter, err := sqlbase.RunFilter(tr.filter, tr.evalCtx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif passesFilter {\n\t\t\tbreak\n\t\t}\n\t}\n\toutRow := tr.rowAlloc.AllocRow(len(tr.outputCols))\n\tfor i, col := range tr.outputCols {\n\t\toutRow[i] = tr.row[col]\n\t}\n\treturn outRow, nil\n}",
"func CursorToNextRow() string {\n\tout := \"\"\n\tout += fmt.Sprint(cursorDown(1))\n\tout += fmt.Sprint(cursorLeft(2))\n\n\treturn out\n}",
"func (itr *RoaringIterator) Next() (rowID, columnID uint64, eof bool) {\n\tv, eof := itr.itr.Next()\n\treturn v / SliceWidth, v % SliceWidth, eof\n}",
"func (s *TransactionRows) NextRaw() ([]byte, bool) {\n\tsnap, err := s.iter.Next()\n\tif err != nil {\n\t\ts.lastError = err\n\t\treturn nil, false\n\t}\n\tdata := snap.Data()\n\tb, err := json.Marshal(data)\n\tif err == nil {\n\t\treturn b, true\n\t}\n\treturn nil, false\n}",
"func (r *Reader) readRow() (err error) {\n r.line++\n\n r.row, err = r.r.ReadString(r.EOL)\n if err != nil && err != io.EOF {\n r.error(err)\n }\n\n return\n}",
"func (d *Demo) Next() (result string, err error) {\n\tif !d.scanner.Scan() {\n\t\tif err := d.scanner.Err(); err != nil {\n\t\t\treturn \"\", err\n\t\t}\n\t\treturn \"\", io.EOF\n\t}\n\treturn Eval(d.scanner.Text())\n}",
"func (l *Rline) Next() ([]rune, error) {\n\tif l.N != nil {\n\t\treturn l.N()\n\t}\n\n\treturn nil, io.EOF\n}",
"func nextDataLine(scanner *bufio.Scanner) string {\n\tfor scanner.Scan() {\n\t\tline := trimComment(scanner.Text())\n\t\tif line != \"\" {\n\t\t\treturn line\n\t\t}\n\t}\n\treturn \"\"\n}",
"func (dr *SeparatedReaders) Next() (err error) {\n\tdr.Count++\n\tif !dr.delimiterFound {\n\t\t// read and discard remains of section.\n\t\t// TODO could read directly any unused, reducing copying taking place\n\t\tbuf := make([]byte, bytes.MinRead)\n\t\tfor {\n\t\t\t_, err = dr.Read(buf)\n\t\t\tif err != nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t}\n\tdr.delimiterFound = false\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
numRows returns 3, except at start.
|
func (c *CSVInterpolator) numRows() int64 {
if c.row == 1 {
return rowsNeededToInterpolate - 1
}
return rowsNeededToInterpolate
}
|
[
"func Rows() (rows int, err error) {\n\t_, rows, err = terminal.GetSize(1)\n\treturn\n}",
"func (c ColDecimal64) Rows() int {\n\treturn len(c)\n}",
"func (m Matrix) Rows() int {\n\treturn len(m)\n}",
"func SQLRowCount(rows *sql.Rows) int {\n\tcount := 0\n\tfor rows.Next() {\n\t\tcount++\n\t}\n\n\tfmt.Println(strconv.Itoa(count))\n\treturn count\n\n}",
"func (c ColDate) Rows() int {\n\treturn len(c)\n}",
"func (c *Chunk) NumRows() int {\n\tif c.NumCols() == 0 {\n\t\treturn c.numVirtualRows\n\t}\n\treturn c.columns[0].length\n}",
"func (b Board) NumRows() int {\n\treturn b.nrows\n}",
"func (fw *Writer) NumRows() int { return fw.nrows }",
"func (qr *QueryResult) NumRows() int64 {\n\treturn int64(len(qr.values))\n}",
"func (d *AddressCacheItem) NumRows() (int, *BlockID) {\n\td.mtx.RLock()\n\tdefer d.mtx.RUnlock()\n\tif d.rows == nil {\n\t\treturn -1, nil\n\t}\n\treturn len(d.rows), d.blockID()\n}",
"func (b *Bitmap) Rows() int {\n\treturn int(b.handle.rows)\n}",
"func (*mySQL) GetRowCount(r RequestAgGrid, rows int) int64 {\n\tif rows == 0 {\n\t\treturn 0\n\t}\n\n\tcurrentLastRow := r.StartRow + int64(rows)\n\n\tif currentLastRow <= r.EndRow {\n\t\treturn currentLastRow\n\t}\n\treturn -1\n}",
"func (g *NormalGrid) Rows() int {\n\treturn g.rows\n}",
"func NumRows(count int) Option {\n\treturn optionFunc(func(s *settingsType) {\n\t\ts.numRows = count\n\t})\n}",
"func (t *Table) Rows() int {\n\treturn len(t.Row)\n}",
"func (ac *AddressCache) NumRows(addr string) (int, *BlockID) {\n\taci := ac.addressCacheItem(addr)\n\tif aci == nil {\n\t\treturn -1, nil\n\t}\n\treturn aci.NumRows()\n}",
"func checkRows(game Game) []int {\n\tvar out []int\n\n\tfor i, card := range game.Cards {\n\t\tfor _, row := range card.Rows {\n\t\t\tif row.Squares[0].Called && row.Squares[1].Called && row.Squares[2].Called && row.Squares[3].Called && row.Squares[4].Called {\n\t\t\t\tout = append(out, i)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn out\n}",
"func (c *Chart) NumRows() int {\n\treturn c.numRows\n}",
"func (qr *queryResult) numRow() int {\n\tif qr.fieldValues == nil {\n\t\treturn 0\n\t}\n\treturn len(qr.fieldValues) / len(qr.fields)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
rowToStartWith returns c.row1, except at start.
|
func (c *CSVInterpolator) rowToStartWith() int64 {
if c.row == 1 {
return 1
}
return c.row - 1
}
|
[
"func StartRow(row int) ParseOption {\r\n\treturn func(p *Parser) error {\r\n\t\tif row <= p.tableNameRow {\r\n\t\t\treturn errors.New(\"Start row must be greater than the table name row\")\r\n\t\t}\r\n\t\tp.startRow = row\r\n\t\treturn nil\r\n\t}\r\n}",
"func rowFromPosition(pos int) int {\n return pos / 8\n}",
"func (rk *rowKey) firstIndex() int64 { return rk.index - rk.count + 1 }",
"func (s *Scan) GetStartRow() []byte {\n\treturn s.startRow\n}",
"func (p *HbaseClient) GetRowOrBefore(tableName Text, row Text, family Text) (r []*TCell, err error) {\n\tif err = p.sendGetRowOrBefore(tableName, row, family); err != nil {\n\t\treturn\n\t}\n\treturn p.recvGetRowOrBefore()\n}",
"func findBeginOfLine(r io.ReaderAt, offset int64) (first int64, err error) {\n\tfor i := offset; i >= 0; i-- {\n\t\tif i == 0 {\n\t\t\tfirst = 0\n\t\t\tbreak\n\t\t}\n\n\t\tbuf := make([]byte, 1)\n\t\tif _, err = r.ReadAt(buf, i); err != nil {\n\t\t\treturn\n\t\t}\n\n\t\tif i == offset && rune(buf[0]) == '\\n' {\n\t\t\tcontinue\n\t\t}\n\t\tif rune(buf[0]) == '\\n' {\n\t\t\tfirst = i + 1\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn\n}",
"func (f *File) LineStart(line int) Pos {\n\t// possible: panic(\"illegal line number (line numbering starts at 1)\")\n\t// possible: panic(\"illegal line number\")\n}",
"func buildXRefTableStartingAt(ctx *model.Context, offset *int64) error {\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: begin\")\n\n\trs := ctx.Read.RS\n\tconf := ctx.Configuration\n\thv, eolCount, err := headerVersion(rs, conf.HeaderBufSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tctx.HeaderVersion = hv\n\tctx.Read.EolCount = eolCount\n\toffs := map[int64]bool{}\n\txrefSectionCount := 0\n\n\tfor offset != nil {\n\n\t\tif offs[*offset] {\n\t\t\toffset, err = offsetLastXRefSection(ctx, ctx.Read.FileSize-*offset)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif offs[*offset] {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\n\t\toffs[*offset] = true\n\n\t\toff, err := tryXRefSection(ctx, rs, offset, &xrefSectionCount)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif off == nil || *off != 0 {\n\t\t\toffset = off\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Read.Println(\"buildXRefTableStartingAt: found xref stream\")\n\t\tctx.Read.UsingXRefStreams = true\n\t\trd, err := newPositionedReader(rs, offset)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif offset, err = parseXRefStream(rd, offset, ctx); err != nil {\n\t\t\tlog.Read.Printf(\"bypassXRefSection after %v\\n\", err)\n\t\t\t// Try fix for corrupt single xref section.\n\t\t\treturn bypassXrefSection(ctx)\n\t\t}\n\n\t}\n\n\tpostProcess(ctx, xrefSectionCount)\n\n\tlog.Read.Println(\"buildXRefTableStartingAt: end\")\n\n\treturn nil\n}",
"func (c Coordinate) Row() int { return c.row }",
"func (file *File) SearchFromStart(searchTerm string) (row, col int, err error) {\n\tloop := false\n\tcursor := cursor.MakeCursor(0, -1)\n\trow, col, err = file.buffer.Search(searchTerm, cursor, loop)\n\treturn\n}",
"func (p *partitionImpl) getRow(row *rowImpl, rowNum int) sif.Row {\n\trow.rowNum = rowNum\n\trow.partition = p\n\treturn row\n}",
"func (gdt *Basis) GetRow(row Int) Vector3 {\n\targ0 := gdt.getBase()\n\targ1 := row.getBase()\n\n\tret := C.go_godot_basis_get_row(GDNative.api, arg0, arg1)\n\n\treturn Vector3{base: &ret}\n\n}",
"func (c *Chunk) LowerBound(colIdx int, d *types.Datum) (index int, match bool) {\n\tindex = sort.Search(c.NumRows(), func(i int) bool {\n\t\tcmp := Compare(c.GetRow(i), colIdx, d)\n\t\tif cmp == 0 {\n\t\t\tmatch = true\n\t\t}\n\t\treturn cmp >= 0\n\t})\n\treturn\n}",
"func (pi *PixelIterator) GetPreviousIteratorRow() (pws []*PixelWand) {\n\tnum := C.size_t(0)\n\tpp := C.PixelGetPreviousIteratorRow(pi.pi, &num)\n\tif pp == nil {\n\t\treturn\n\t}\n\tfor i := 0; i < int(num); i++ {\n\t\tcpw := C.get_pw_at(pp, C.size_t(i))\n\t\t// PixelWand is a private pointer, borrowed from the pixel\n\t\t// iterator. We don't want to reference count it. It will\n\t\t// get destroyed by C API when PixelIterator is destroyed.\n\t\tpws = append(pws, &PixelWand{pw: cpw})\n\t}\n\truntime.KeepAlive(pi)\n\treturn\n}",
"func (t *Table) Row() *Table {\n\tif len(t.cells) > 0 {\n\t\tt.curRow++\n\t}\n\tt.curCol = 0\n\treturn t\n}",
"func CursorToNextRow() string {\n\tout := \"\"\n\tout += fmt.Sprint(cursorDown(1))\n\tout += fmt.Sprint(cursorLeft(2))\n\n\treturn out\n}",
"func (l Line) Start() Pos {\n\treturn l[0]\n}",
"func (card *Card) getRow(rowNum int) (error, []*cell) {\n\tif card.isValidRow(rowNum) {\n\t\treturn nil, card.rows[rowNum]\n\t}\n\treturn fmt.Errorf(\"Invalid row number: %d from %d\", rowNum, len(card.rows)), []*cell{}\n}",
"func (p *SASQueryParameters) StartRowKey() string {\n\treturn p.startRk\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GetVendor vendor company name only, in text format. return "" for any errors
|
func (c *Client) GetVendor(term string) string {
c.Output = "vendor"
result := ""
httpResp, err := c.sendRequest("GET", term, nil)
if err != nil {
return result
}
if httpResp.StatusCode == http.StatusOK {
defer httpResp.Body.Close()
body, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return result
}
result = string(body)
}
return result
}
|
[
"func (d UserData) CommercialCompanyName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\"))\n\tif !d.Has(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}",
"func (o *Wireless) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}",
"func (s UserSet) CommercialCompanyName() string {\n\tres, _ := s.RecordCollection.Get(models.NewFieldName(\"CommercialCompanyName\", \"commercial_company_name\")).(string)\n\treturn res\n}",
"func (o *Wireless) GetVendorOk() (string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret, false\n\t}\n\treturn *o.Vendor, true\n}",
"func (this *metaUsbSvc) VendorName(vid string) (string, error) {\n\tif vendor, err := this.GetVendor(vid); err != nil {\n\t\treturn ``, err\n\t} else {\n\t\treturn vendor.String(), nil\n\t}\n}",
"func Vendorless(p string) string {\n\tif pos := strings.LastIndex(p, \"/vendor/\"); pos != -1 {\n\t\treturn p[pos+len(\"/vendor/\"):]\n\t}\n\treturn p\n}",
"func Company() string {\n\treturn lookup(lang, \"companies\", true)\n}",
"func (m *M1000e) Vendor() (vendor string) {\n\treturn dell.VendorID\n}",
"func (o OrderContactOutput) CompanyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v OrderContact) string { return v.CompanyName }).(pulumi.StringOutput)\n}",
"func (o *FirmwareBaseDistributableAllOf) GetVendor() string {\n\tif o == nil || o.Vendor == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.Vendor\n}",
"func (o LookupUserResultOutput) CompanyName() pulumi.StringOutput {\n\treturn o.ApplyT(func(v LookupUserResult) string { return v.CompanyName }).(pulumi.StringOutput)\n}",
"func (client *XenClient) SMGetVendor(self string) (result string, err error) {\n\tobj, err := client.APICall(\"SM.get_vendor\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}",
"func (native *OpenGL) GetVendorName() string {\n\treturn gl.GoStr(gl.GetString(gl.VENDOR))\n}",
"func (o *EquipmentIdentityAllOf) GetVendorOk() (*string, bool) {\n\tif o == nil || o.Vendor == nil {\n\t\treturn nil, false\n\t}\n\treturn o.Vendor, true\n}",
"func (o *VirtualizationBaseHostPciDeviceAllOf) GetVendorNameOk() (*string, bool) {\n\tif o == nil || o.VendorName == nil {\n\t\treturn nil, false\n\t}\n\treturn o.VendorName, true\n}",
"func (a Annotations) Vendor() (string, bool) {\n\treturn a.Get(VendorAnnotation)\n}",
"func (o *VirtualizationBaseHostPciDeviceAllOf) GetVendorName() string {\n\tif o == nil || o.VendorName == nil {\n\t\tvar ret string\n\t\treturn ret\n\t}\n\treturn *o.VendorName\n}",
"func (client *XenClient) HostGetAPIVersionVendor(self string) (result string, err error) {\n\tobj, err := client.APICall(\"host.get_API_version_vendor\", self)\n\tif err != nil {\n\t\treturn\n\t}\n\tresult = obj.(string)\n\treturn\n}",
"func (d UserData) CompanyName() string {\n\tval := d.ModelData.Get(models.NewFieldName(\"CompanyName\", \"company_name\"))\n\tif !d.Has(models.NewFieldName(\"CompanyName\", \"company_name\")) {\n\t\treturn *new(string)\n\t}\n\treturn val.(string)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
TransformAccount converts an account from the history archive ingestion system into a form suitable for BigQuery
|
func TransformAccount(ledgerChange ingestio.Change) (AccountOutput, error) {
ledgerEntry, outputDeleted, err := utils.ExtractEntryFromChange(ledgerChange)
if err != nil {
return AccountOutput{}, err
}
accountEntry, accountFound := ledgerEntry.Data.GetAccount()
if !accountFound {
return AccountOutput{}, fmt.Errorf("Could not extract account data from ledger entry; actual type is %s", ledgerEntry.Data.Type)
}
outputID, err := accountEntry.AccountId.GetAddress()
if err != nil {
return AccountOutput{}, err
}
outputBalance := int64(accountEntry.Balance)
if outputBalance < 0 {
return AccountOutput{}, fmt.Errorf("Balance is negative (%d) for account: %s", outputBalance, outputID)
}
//The V1 struct is the first version of the extender from accountEntry. It contains information on liabilities, and in the future
//more extensions may contain extra information
accountExtensionInfo, V1Found := accountEntry.Ext.GetV1()
var outputBuyingLiabilities, outputSellingLiabilities int64
if V1Found {
liabilities := accountExtensionInfo.Liabilities
outputBuyingLiabilities, outputSellingLiabilities = int64(liabilities.Buying), int64(liabilities.Selling)
if outputBuyingLiabilities < 0 {
return AccountOutput{}, fmt.Errorf("The buying liabilities count is negative (%d) for account: %s", outputBuyingLiabilities, outputID)
}
if outputSellingLiabilities < 0 {
return AccountOutput{}, fmt.Errorf("The selling liabilities count is negative (%d) for account: %s", outputSellingLiabilities, outputID)
}
}
outputSequenceNumber := int64(accountEntry.SeqNum)
if outputSequenceNumber < 0 {
return AccountOutput{}, fmt.Errorf("Account sequence number is negative (%d) for account: %s", outputSequenceNumber, outputID)
}
outputNumSubentries := uint32(accountEntry.NumSubEntries)
inflationDestAccountID := accountEntry.InflationDest
var outputInflationDest string
if inflationDestAccountID != nil {
outputInflationDest, err = inflationDestAccountID.GetAddress()
if err != nil {
return AccountOutput{}, err
}
}
outputFlags := uint32(accountEntry.Flags)
outputHomeDomain := string(accountEntry.HomeDomain)
outputMasterWeight := int32(accountEntry.MasterKeyWeight())
outputThreshLow := int32(accountEntry.ThresholdLow())
outputThreshMed := int32(accountEntry.ThresholdMedium())
outputThreshHigh := int32(accountEntry.ThresholdHigh())
outputLastModifiedLedger := uint32(ledgerEntry.LastModifiedLedgerSeq)
transformedAccount := AccountOutput{
AccountID: outputID,
Balance: outputBalance,
BuyingLiabilities: outputBuyingLiabilities,
SellingLiabilities: outputSellingLiabilities,
SequenceNumber: outputSequenceNumber,
NumSubentries: outputNumSubentries,
InflationDestination: outputInflationDest,
Flags: outputFlags,
HomeDomain: outputHomeDomain,
MasterWeight: outputMasterWeight,
ThresholdLow: outputThreshLow,
ThresholdMedium: outputThreshMed,
ThresholdHigh: outputThreshHigh,
LastModifiedLedger: outputLastModifiedLedger,
Deleted: outputDeleted,
}
return transformedAccount, nil
}
|
[
"func (acc *BaseAccount) ConvertAccount(cdc codec.Marshaler) interface{} {\n\taccount := sdk.BaseAccount{\n\t\tAddress: acc.Address,\n\t\tAccountNumber: acc.AccountNumber,\n\t\tSequence: acc.Sequence,\n\t}\n\n\tvar pkStr string\n\tif acc.PubKey == nil {\n\t\treturn account\n\t}\n\n\tvar pk crypto.PubKey\n\tif err := cdc.UnpackAny(acc.PubKey, &pk); err != nil {\n\t\treturn sdk.BaseAccount{}\n\t}\n\n\tpkStr, err := sdk.Bech32ifyPubKey(sdk.Bech32PubKeyTypeAccPub, pk)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\taccount.PubKey = pkStr\n\treturn account\n}",
"func (tr BitcoinTranslator) ToAccountMovements(address string, v interface{}) (*domain.AccountMovements, error) {\n\ttxs, _ := v.([]Transaction)\n\tam := domain.NewAccountMovements(address)\n\n\tfor _, tx := range txs {\n\t\t// Inputs will be reflected as a spent\n\t\tfor _, in := range tx.Inputs {\n\t\t\tif in.Addresses[0] != address {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tval, ok := new(big.Int).SetString(in.Value, 10)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"bitcoin translation error, cannot convert in.Value(%s) to bigint\", in.Value)\n\t\t\t}\n\t\t\tam.Spend(tx.BlockHeight, tx.BlockTime, tx.TxID, val, \"\")\n\t\t}\n\n\t\t// Outputs will be reflected as a receive\n\t\tfor _, out := range tx.Outputs {\n\t\t\tif out.Addresses[0] != address {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tval, ok := new(big.Int).SetString(out.Value, 10)\n\t\t\tif !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"bitcoin translation error, cannot convert out.Value(%s) to bigint\", out.Value)\n\t\t\t}\n\t\t\tam.Receive(tx.BlockHeight, tx.BlockTime, tx.TxID, val, \"\")\n\t\t}\n\t}\n\n\treturn am, nil\n}",
"func ToAccount(m map[string]string) (*BankAccount, error) {\n\tif _, ok := m[\"ID\"]; !ok {\n\t\treturn nil, errors.New(\"Missing account ID\")\n\t}\n\n\tbalance, err := strconv.Atoi(m[\"Balance\"])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &BankAccount{\n\t\tID: m[\"ID\"],\n\t\tName: m[\"Name\"],\n\t\tBalance: balance,\n\t}, nil\n}",
"func (m MuxedAccount) ToAccountId() AccountId {\n\tresult := AccountId{Type: PublicKeyTypePublicKeyTypeEd25519}\n\tswitch m.Type {\n\tcase CryptoKeyTypeKeyTypeEd25519:\n\t\ted := m.MustEd25519()\n\t\tresult.Ed25519 = &ed\n\tcase CryptoKeyTypeKeyTypeMuxedEd25519:\n\t\ted := m.MustMed25519().Ed25519\n\t\tresult.Ed25519 = &ed\n\tdefault:\n\t\tpanic(fmt.Errorf(\"Unknown muxed account type: %v\", m.Type))\n\t}\n\treturn result\n}",
"func transformAdvancedToConfig(accountName string, a advancedAccount) (*config.Account, error) {\n\tvar pKey crypto.PrivateKey\n\tvar err error\n\tsigAlgo := crypto.StringToSignatureAlgorithm(a.Key.SigAlgo)\n\thashAlgo := crypto.StringToHashAlgorithm(a.Key.HashAlgo)\n\n\tif a.Key.Type != config.KeyTypeHex && a.Key.Type != config.KeyTypeGoogleKMS {\n\t\treturn nil, fmt.Errorf(\"invalid key type for account %s\", accountName)\n\t}\n\n\tif a.Key.ResourceID != \"\" && a.Key.PrivateKey != \"\" {\n\t\treturn nil, fmt.Errorf(\"only provide value for private key or resource ID on account %s\", accountName)\n\t}\n\n\tif a.Key.Type == config.KeyTypeHex {\n\t\tif a.Key.PrivateKey != \"\" {\n\t\t\tpKey, err = crypto.DecodePrivateKeyHex(\n\t\t\t\tsigAlgo,\n\t\t\t\tstrings.TrimPrefix(a.Key.PrivateKey, \"0x\"),\n\t\t\t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else {\n\t\t\treturn nil, fmt.Errorf(\"missing private key value for hex key type on account %s\", accountName)\n\t\t}\n\t}\n\n\tif sigAlgo == crypto.UnknownSignatureAlgorithm {\n\t\treturn nil, fmt.Errorf(\"invalid signature algorithm for account %s\", accountName)\n\t}\n\n\tif hashAlgo == crypto.UnknownHashAlgorithm {\n\t\treturn nil, fmt.Errorf(\"invalid hash algorithm for account %s\", accountName)\n\t}\n\n\taddress, err := transformAddress(a.Address)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &config.Account{\n\t\tName: accountName,\n\t\tAddress: address,\n\t\tKey: config.AccountKey{\n\t\t\tType: a.Key.Type,\n\t\t\tIndex: a.Key.Index,\n\t\t\tSigAlgo: sigAlgo,\n\t\t\tHashAlgo: hashAlgo,\n\t\t\tResourceID: a.Key.ResourceID,\n\t\t\tPrivateKey: pKey,\n\t\t},\n\t}, nil\n}",
"func TransformPaymentSummaryAccount(mctx libkb.MetaContext, p stellar1.PaymentSummary, oc OwnAccountLookupCache, accountID stellar1.AccountID) (*stellar1.PaymentLocal, error) {\n\treturn transformPaymentSummary(mctx, p, oc, accountID)\n}",
"func (j jsonAccounts) transformToConfig() (config.Accounts, error) {\n\taccounts := make(config.Accounts, 0)\n\n\tfor accountName, a := range j {\n\t\tvar account *config.Account\n\t\tvar err error\n\t\tif a.Simple.Address != \"\" {\n\t\t\taccount, err = transformSimpleToConfig(accountName, a.Simple)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t} else { // advanced format\n\t\t\taccount, err = transformAdvancedToConfig(accountName, a.Advanced)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\taccounts = append(accounts, *account)\n\t}\n\n\treturn accounts, nil\n}",
"func (q *TransactionsQ) ForAccount(ctx context.Context, aid string) *TransactionsQ {\n\tvar account Account\n\tq.Err = q.parent.AccountByAddress(ctx, &account, aid)\n\tif q.Err != nil {\n\t\treturn q\n\t}\n\n\tq.sql = q.sql.\n\t\tJoin(\"history_transaction_participants htp ON htp.history_transaction_id = ht.id\").\n\t\tWhere(\"htp.history_account_id = ?\", account.ID)\n\n\treturn q\n}",
"func (tr EthereumTranslator) ToAccountMovements(address string, v interface{}) (*domain.AccountMovements, error) {\n\ttxs, _ := v.([]Transaction)\n\tam := domain.NewAccountMovements(address)\n\taddress = blockchain.NormalizeEthereumAddress(address)\n\n\tfor _, tx := range txs {\n\t\t// Do not include reverted/failed transactions\n\t\tif tx.EthereumSpecific.Status != transactionStatusSuccess {\n\t\t\tcontinue\n\t\t}\n\n\t\tval, ok := new(big.Int).SetString(tx.Value, 10)\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"blockbook ethereum translation error, cannot convert in.Value(%s) to bigint\", tx.Value)\n\t\t}\n\n\t\t// Any value transfers from this address will be reflected as a spent\n\t\tif blockchain.NormalizeEthereumAddress(tx.Inputs[0].Addresses[0]) == address {\n\t\t\tam.Spend(tx.BlockHeight, tx.BlockTime, tx.TxID, val, tx.Outputs[0].Addresses[0])\n\t\t}\n\n\t\t// Any value transfers to this address will be reflected as a receive\n\t\tif blockchain.NormalizeEthereumAddress(tx.Outputs[0].Addresses[0]) == address {\n\t\t\tam.Receive(tx.BlockHeight, tx.BlockTime, tx.TxID, val, tx.Inputs[0].Addresses[0])\n\t\t}\n\t}\n\n\treturn am, nil\n}",
"func (h *HUOBI) AccountTransferRecords(ctx context.Context, code currency.Pair, transferType string, createDate, pageIndex, pageSize int64) (InternalAccountTransferData, error) {\n\tvar resp InternalAccountTransferData\n\treq := make(map[string]interface{})\n\tcodeValue, err := h.FormatSymbol(code, asset.CoinMarginedFutures)\n\tif err != nil {\n\t\treturn resp, err\n\t}\n\treq[\"contract_code\"] = codeValue\n\tif !common.StringDataCompareInsensitive(validTransferType, transferType) {\n\t\treturn resp, fmt.Errorf(\"invalid transferType received\")\n\t}\n\treq[\"type\"] = transferType\n\tif createDate > 90 {\n\t\treturn resp, fmt.Errorf(\"invalid create date value: only supports up to 90 days\")\n\t}\n\treq[\"create_date\"] = strconv.FormatInt(createDate, 10)\n\tif pageIndex != 0 {\n\t\treq[\"page_index\"] = pageIndex\n\t}\n\tif pageSize > 0 && pageSize <= 50 {\n\t\treq[\"page_size\"] = pageSize\n\t}\n\treturn resp, h.FuturesAuthenticatedHTTPRequest(ctx, exchange.RestFutures, http.MethodPost, huobiSwapInternalTransferRecords, nil, req, &resp)\n}",
"func newAccountFromHorizon(ha horizon.Account) *Account {\n\taccount := newAccount()\n\n\taccount.Address = ha.HistoryAccount.AccountID\n\taccount.HomeDomain = ha.HomeDomain\n\taccount.Sequence = ha.Sequence\n\n\tfor _, b := range ha.Balances {\n\t\tif b.Asset.Type == string(NativeType) {\n\t\t\taccount.NativeBalance = Balance{NativeAsset, b.Balance, \"\"}\n\t\t\tcontinue\n\t\t}\n\n\t\tbalance := Balance{\n\t\t\tAsset: NewAsset(b.Asset.Code, b.Asset.Issuer, AssetType(b.Asset.Type)),\n\t\t\tAmount: b.Balance,\n\t\t\tLimit: b.Limit,\n\t\t}\n\n\t\taccount.Balances = append(account.Balances, balance)\n\t}\n\n\taccount.Signers = []Signer{}\n\tfor _, s := range ha.Signers {\n\t\tsigner := Signer{\n\t\t\tPublicKey: s.PublicKey,\n\t\t\tWeight: s.Weight,\n\t\t\tKey: s.Key,\n\t\t\tType: s.Type,\n\t\t}\n\t\taccount.Signers = append(account.Signers, signer)\n\t}\n\n\taccount.Thresholds.High = ha.Thresholds.HighThreshold\n\taccount.Thresholds.Medium = ha.Thresholds.MedThreshold\n\taccount.Thresholds.Low = ha.Thresholds.LowThreshold\n\n\taccount.Flags.AuthRequired = ha.Flags.AuthRequired\n\taccount.Flags.AuthRevocable = ha.Flags.AuthRevocable\n\n\taccount.Data = map[string]string{}\n\tfor k, v := range ha.Data {\n\t\taccount.Data[k] = v\n\t}\n\n\treturn account\n}",
"func (a Account) ToDTO() AccountDTO {\n\treturn AccountDTO{\n\t\tID: a.ID,\n\t\tUsername: a.Username,\n\t\tOwner: a.Owner,\n\t}\n}",
"func (ga *GenesisAccount) ToAccount() auth.Account {\n\tbacc := &auth.BaseAccount{\n\t\tAddress: ga.Address,\n\t\tCoins: ga.Coins.Sort(),\n\t\tAccountNumber: ga.AccountNumber,\n\t\tSequence: ga.Sequence,\n\t}\n\n\tif !ga.OriginalVesting.IsZero() {\n\t\tbaseVestingAcc := &auth.BaseVestingAccount{\n\t\t\tBaseAccount: bacc,\n\t\t\tOriginalVesting: ga.OriginalVesting,\n\t\t\tDelegatedFree: ga.DelegatedFree,\n\t\t\tDelegatedVesting: ga.DelegatedVesting,\n\t\t\tEndTime: ga.EndTime,\n\t\t}\n\n\t\tif ga.StartTime != 0 && ga.EndTime != 0 {\n\t\t\treturn &auth.ContinuousVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t\tStartTime: ga.StartTime,\n\t\t\t}\n\t\t} else if ga.EndTime != 0 {\n\t\t\treturn &auth.DelayedVestingAccount{\n\t\t\t\tBaseVestingAccount: baseVestingAcc,\n\t\t\t}\n\t\t} else {\n\t\t\tpanic(fmt.Sprintf(\"invalid genesis vesting account: %+v\", ga))\n\t\t}\n\t}\n\n\treturn bacc\n}",
"func AccountHistory(rpc nanostructs.NanoRPC, account string, count string, optional map[string]string) ([]byte, error) {\n\t//Check to see if count is an integer. If not, return an error.\n\tdata := make(map[string]string)\n\n\tif count == \"\" {\n\t\tdata[\"action\"] = \"account_history\"\n\t\tdata[\"account\"] = strings.ToLower(account)\n\t} else {\n\t\t_, err := strconv.Atoi(count)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"Count must be an integer: %s\", count)\n\t\t}\n\n\t\tdata[\"action\"] = \"account_history\"\n\t\tdata[\"account\"] = strings.ToLower(account)\n\t\tdata[\"count\"] = count\n\t}\n\n\t//If the length of optional arguments is > 0, iterate over them and make sure the arguments are valid.\n\t//If they're valid, add to the data map, if not return an error.\n\tif len(optional) > 0 {\n\t\tfor k, v := range optional {\n\t\t\tswitch strings.ToLower(k) {\n\t\t\tcase \"raw\":\n\t\t\t\tif _, ok := data[k]; ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Duplicate key provided: %s\", k)\n\t\t\t\t}\n\t\t\t\t_, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Invalid optional argument value: %s: %s\", k, v)\n\t\t\t\t}\n\t\t\t\tdata[k] = v\n\n\t\t\tcase \"head\":\n\t\t\t\tif _, ok := data[k]; ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Duplicate key provided: %s\", k)\n\t\t\t\t}\n\t\t\t\tdata[k] = v\n\n\t\t\tcase \"offset\":\n\t\t\t\tif _, ok := data[k]; ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Duplicate key provided: %s\", k)\n\t\t\t\t}\n\t\t\t\t_, err := strconv.Atoi(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Invalid optional argument value: %s: %s\", k, v)\n\t\t\t\t}\n\t\t\t\tdata[k] = v\n\n\t\t\tcase \"reverse\":\n\t\t\t\tif _, ok := data[k]; ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Duplicate key provided: %s\", k)\n\t\t\t\t}\n\t\t\t\t_, err := strconv.ParseBool(v)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"Invalid optional argument value: %s: %s\", k, v)\n\t\t\t\t}\n\t\t\t\tdata[k] = v\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"Invalid optional argument key: %s: %s\", k, v)\n\t\t\t}\n\t\t}\n\t}\n\n\tresponse, historyError := RawNodePost(rpc.Host, rpc.Port, &data)\n\tif historyError != nil {\n\t\treturn nil, historyError\n\t}\n\n\treturn response, nil\n}",
"func (db *IndexerDb) processAccount(account *generated.Account) {\n\tif !db.hasTotalRewardsSupport() {\n\t\taccount.Rewards = 0\n\t}\n}",
"func UnmarshalAccount(m map[string]json.RawMessage, result interface{}) (err error) {\n\tobj := new(Account)\n\terr = core.UnmarshalPrimitive(m, \"url\", &obj.URL)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"id\", &obj.ID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"crn\", &obj.CRN)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"parent\", &obj.Parent)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_account_id\", &obj.EnterpriseAccountID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_id\", &obj.EnterpriseID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"enterprise_path\", &obj.EnterprisePath)\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, \"state\", &obj.State)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"owner_iam_id\", &obj.OwnerIamID)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"paid\", &obj.Paid)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"owner_email\", &obj.OwnerEmail)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"is_enterprise_account\", &obj.IsEnterpriseAccount)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_at\", &obj.CreatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"created_by\", &obj.CreatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_at\", &obj.UpdatedAt)\n\tif err != nil {\n\t\treturn\n\t}\n\terr = core.UnmarshalPrimitive(m, \"updated_by\", &obj.UpdatedBy)\n\tif err != nil {\n\t\treturn\n\t}\n\treflect.ValueOf(result).Elem().Set(reflect.ValueOf(obj))\n\treturn\n}",
"func ExportAccount(utcFile string, auth string) ([]byte, error) {\n\tkeyJSON, err := ioutil.ReadFile(utcFile)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tkey, err := keystore.DecryptKey(keyJSON, auth)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tret, err := key.MarshalJSON()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn ret, nil\n}",
"func (acc *BaseAccount) Convert() interface{} {\n\t// error don't use it\n\treturn nil\n}",
"func AccountInfo(ctx context.Context, hq *history.Q, addr string) (*protocol.Account, error) {\n\tvar (\n\t\trecord history.AccountEntry\n\t\tdata []history.Data\n\t\tsigners []history.AccountSigner\n\t\ttrustlines []history.TrustLine\n\t\tresource protocol.Account\n\t)\n\n\trecord, err := hq.GetAccountByID(ctx, addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting history account record\")\n\t}\n\n\tdata, err = hq.GetAccountDataByAccountID(ctx, addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting history account data\")\n\t}\n\n\tsigners, err = hq.GetAccountSignersByAccountID(ctx, addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting history signers\")\n\t}\n\n\ttrustlines, err = hq.GetSortedTrustLinesByAccountID(ctx, addr)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"getting history trustlines\")\n\t}\n\n\tledger, err := getLedgerBySequence(ctx, hq, int32(record.LastModifiedLedger))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = resourceadapter.PopulateAccountEntry(\n\t\tctx,\n\t\t&resource,\n\t\trecord,\n\t\tdata,\n\t\tsigners,\n\t\ttrustlines,\n\t\tledger,\n\t)\n\tif err != nil {\n\t\treturn nil, errors.Wrap(err, \"populating account entry\")\n\t}\n\n\treturn &resource, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DefaultRegions returns the default regions supported by AWS NOTE: in the future this list is subject to change
|
func DefaultRegions() []string {
return []string{
"us-east-2",
"us-east-1",
"us-west-1",
"us-west-2",
"ap-south-1",
"ap-northeast-2",
"ap-southeast-1",
"ap-northeast-1",
"ca-central-1",
"eu-central-1",
"eu-west-1",
"eu-west-2",
"sa-east-1",
}
}
|
[
"func GetRegions() ([]Region, error) {\n\tvar regions []Region\n\tarvanConfig := config.GetConfigInfo()\n\tarvanServer := arvanConfig.GetServer()\n\thttpReq, err := http.NewRequest(\"GET\", arvanServer+apiPrefix+defaultRegion+regionsEndpoint, nil)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\thttpReq.Header.Add(\"accept\", \"application/json\")\n\thttpReq.Header.Add(\"User-Agent\", \"ar-cli\")\n\thttpResp, err := http.DefaultClient.Do(httpReq)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\t// read body\n\tdefer httpResp.Body.Close()\n\tbody, err := ioutil.ReadAll(httpResp.Body)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\t// parse response\n\terr = json.Unmarshal(body, ®ions)\n\tif err != nil {\n\t\treturn regions, err\n\t}\n\n\treturn regions, nil\n}",
"func GetRegions(sess *session.Session) (*ec2.DescribeRegionsOutput, error) {\n // snippet-start:[ec2.go.regions_and_zones.regions]\n svc := ec2.New(sess)\n\n resultRegions, err := svc.DescribeRegions(nil)\n // snippet-end:[ec2.go.regions_and_zones.regions]\n if err != nil {\n return nil, err\n }\n\n return resultRegions, nil\n}",
"func (o *AmazonAccountAccessKeys) GetDefaultRegion() RegionTypes {\n\tif o == nil || o.DefaultRegion == nil {\n\t\tvar ret RegionTypes\n\t\treturn ret\n\t}\n\treturn *o.DefaultRegion\n}",
"func getDefaultRegion(profile string) (string, error) {\n\tif len(os.Getenv(constants.DefaultRegionVariable)) > 0 {\n\t\treturn os.Getenv(constants.DefaultRegionVariable), nil\n\t}\n\n\tfunctions := []func() (*ini.File, error){\n\t\tReadAWSCredentials,\n\t\tReadAWSConfig,\n\t}\n\n\tfor _, f := range functions {\n\t\tcfg, err := f()\n\t\tif err != nil {\n\t\t\treturn constants.EmptyString, err\n\t\t}\n\n\t\tsection, err := cfg.GetSection(profile)\n\t\tif err != nil {\n\t\t\treturn constants.EmptyString, err\n\t\t}\n\n\t\tif _, err := section.GetKey(\"region\"); err == nil && len(section.Key(\"region\").String()) > 0 {\n\t\t\treturn section.Key(\"region\").String(), nil\n\t\t}\n\t}\n\treturn constants.EmptyString, errors.New(\"no aws region configuration exists\")\n}",
"func TestGetAllRegions(t *testing.T) {\n\tawsRegionSample := []string{\"ap-southeast-1\", \"us-west-2\", \"ap-northeast-1\", \"eu-west-2\", \"eu-central-1\"}\n\tawsChinaSample := []string{\"cn-north-1\", \"cn-northwest-1\"}\n\n\tawsRegions := GetAllRegions()\n\tfor _, region := range awsRegionSample {\n\t\tif !stringInSlice(region, awsRegions) {\n\t\t\tt.Errorf(\"Could not find region %s in retrieved list: %v\", region, awsRegions)\n\t\t}\n\t}\n\n\t// Test the same for China\n\tawsRegions = GetAllChinaRegions()\n\tfor _, region := range awsChinaSample {\n\t\tif !stringInSlice(region, awsRegions) {\n\t\t\tt.Errorf(\"Could not find region %s in retrieved list: %v\", region, awsRegions)\n\t\t}\n\t}\n}",
"func GetSupportedRegions() map[string]bool {\n\treturn supportedRegions\n}",
"func (m *VirtualEndpoint) GetSupportedRegions()([]CloudPcSupportedRegionable) {\n val, err := m.GetBackingStore().Get(\"supportedRegions\")\n if err != nil {\n panic(err)\n }\n if val != nil {\n return val.([]CloudPcSupportedRegionable)\n }\n return nil\n}",
"func GetEnabledRegions() ([]string, error) {\n\tvar regionNames []string\n\n\t// We don't want to depend on a default region being set, so instead we\n\t// will choose a region from the list of regions that are enabled by default\n\t// and use that to enumerate all enabled regions.\n\t// Corner case: user has intentionally disabled one or more regions that are\n\t// enabled by default. If that region is chosen, API calls will fail.\n\t// Therefore we retry until one of the regions works.\n\tregions, err := retryDescribeRegions()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, region := range regions.Regions {\n\t\tregionNames = append(regionNames, awsgo.StringValue(region.RegionName))\n\t}\n\n\treturn regionNames, nil\n}",
"func defaultAwsConfig() aws.Config {\n\tregion := getMetadataRegion(\"us-east-1\")\n\treturn aws.Config{Region: ®ion}\n}",
"func (o *AmazonAccountAccessKeys) HasDefaultRegion() bool {\n\tif o != nil && o.DefaultRegion != nil {\n\t\treturn true\n\t}\n\n\treturn false\n}",
"func (s *dummyService) GetRegionNames() (*[]string, error) {\n\treturn nil, nil\n}",
"func (o *AmazonAccountAccessKeys) GetDefaultRegionOk() (*RegionTypes, bool) {\n\tif o == nil || o.DefaultRegion == nil {\n\t\treturn nil, false\n\t}\n\treturn o.DefaultRegion, true\n}",
"func (a *CloudProviderCredentialsApiService) ListAWSRegions(ctx _context.Context) ApiListAWSRegionsRequest {\n\treturn ApiListAWSRegionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}",
"func (a *AzureInfoer) GetRegions() (map[string]string, error) {\n\n\tallLocations := make(map[string]string)\n\tsupLocations := make(map[string]string)\n\n\t// retrieve all locations for the subscription id (some of them may not be supported by the required provider\n\tif locations, err := a.subscriptionsClient.ListLocations(context.TODO(), a.subscriptionId); err == nil {\n\t\t// fill up the map: DisplayName - > Name\n\t\tfor _, loc := range *locations.Value {\n\t\t\tallLocations[*loc.DisplayName] = *loc.Name\n\t\t}\n\t} else {\n\t\tlog.Errorf(\"error while retrieving azure locations. err: %s\", err.Error())\n\t\treturn nil, err\n\t}\n\n\t// identify supported locations for the namespace and resource type\n\tconst (\n\t\tproviderNamespace = \"Microsoft.Compute\"\n\t\tresourceType = \"locations/vmSizes\"\n\t)\n\n\tif providers, err := a.providersClient.Get(context.TODO(), providerNamespace, \"\"); err == nil {\n\t\tfor _, pr := range *providers.ResourceTypes {\n\t\t\tif *pr.ResourceType == resourceType {\n\t\t\t\tfor _, displName := range *pr.Locations {\n\t\t\t\t\tif loc, ok := allLocations[displName]; ok {\n\t\t\t\t\t\tlog.Debugf(\"found supported location. [name, display name] = [%s, %s]\", loc, displName)\n\t\t\t\t\t\tsupLocations[loc] = displName\n\t\t\t\t\t} else {\n\t\t\t\t\t\tlog.Debugf(\"unsupported location. [name, display name] = [%s, %s]\", loc, displName)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t} else {\n\t\tlog.Errorf(\"error while retrieving supported locations for provider: %s. err: %s\", providerNamespace, err.Error())\n\t\treturn nil, err\n\t}\n\n\treturn supLocations, nil\n}",
"func ExampleRDS_DescribeSourceRegions_shared00() {\n\tsvc := rds.New(session.New())\n\tinput := &rds.DescribeSourceRegionsInput{\n\t\tRegionName: aws.String(\"us-east-1\"),\n\t}\n\n\tresult, err := svc.DescribeSourceRegions(input)\n\tif err != nil {\n\t\tif aerr, ok := err.(awserr.Error); ok {\n\t\t\tswitch aerr.Code() {\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 DescribeRegionsSample() {\n\t// Create archive bucket\n\tclient, err := oss.New(endpoint, accessID, accessKey)\n\tif err != nil {\n\t\tHandleError(err)\n\t}\n\n\t// Get describe regions\n\tregionEndpoint := \"oss-cn-hangzhou\"\n\tlist, err := client.DescribeRegions(regionEndpoint)\n\tif err != nil {\n\t\tHandleError(err)\n\t}\n\tfor _, region := range list.Regions {\n\t\tfmt.Printf(\"Region:%s\\n\", region.Region)\n\t\tfmt.Printf(\"Region Internet Endpoint:%s\\n\", region.InternetEndpoint)\n\t\tfmt.Printf(\"Region Internal Endpoint:%s\\n\", region.InternalEndpoint)\n\t\tfmt.Printf(\"Region Accelerate Endpoint:%s\\n\", region.AccelerateEndpoint)\n\t}\n\tfmt.Println(\"Get Describe Regions Success\")\n\n\t// List describe regions\n\n\tlist, err = client.DescribeRegions(\"\")\n\tif err != nil {\n\t\tHandleError(err)\n\t}\n\tfor _, region := range list.Regions {\n\t\tfmt.Printf(\"Region:%s\\n\", region.Region)\n\t\tfmt.Printf(\"Region Internet Endpoint:%s\\n\", region.InternetEndpoint)\n\t\tfmt.Printf(\"Region Internal Endpoint:%s\\n\", region.InternalEndpoint)\n\t\tfmt.Printf(\"Region Accelerate Endpoint:%s\\n\", region.AccelerateEndpoint)\n\t}\n\tfmt.Println(\"List Describe Regions Success\")\n\n\tfmt.Println(\"DescribeRegionsSample completed\")\n}",
"func (o *CreateVaultOptions) ApplyDefaultRegionIfEmpty(enforcedDefault string) error {\n\tif o.DynamoDBRegion == \"\" || o.KMSRegion == \"\" || o.S3Region == \"\" {\n\t\tvar defaultRegion string\n\t\tvar err error\n\t\tif enforcedDefault == \"\" {\n\t\t\t_, defaultRegion, err = amazon.GetCurrentlyConnectedRegionAndClusterName()\n\t\t\tif err != nil {\n\t\t\t\treturn errors.Wrap(err, \"finding default AWS region\")\n\t\t\t}\n\t\t} else {\n\t\t\tdefaultRegion = enforcedDefault\n\t\t}\n\n\t\tlog.Logger().Infof(\"Region not specified, defaulting to %s\", util.ColorInfo(defaultRegion))\n\t\tif o.DynamoDBRegion == \"\" {\n\t\t\to.DynamoDBRegion = defaultRegion\n\t\t}\n\t\tif o.KMSRegion == \"\" {\n\t\t\to.KMSRegion = defaultRegion\n\t\t}\n\t\tif o.S3Region == \"\" {\n\t\t\to.S3Region = defaultRegion\n\t\t}\n\n\t}\n\treturn nil\n}",
"func (a *RegionsApiService) GetAllRegions(ctx _context.Context) ApiGetAllRegionsRequest {\n\treturn ApiGetAllRegionsRequest{\n\t\tApiService: a,\n\t\tctx: ctx,\n\t}\n}",
"func GetAvailableRegions(client *godo.Client, ctx context.Context) ([]godo.Region, error) {\n\tregions, err := rawGetRegions(client, ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar listRegions []godo.Region\n\tfor _, region := range regions {\n\t\tif region.Available {\n\t\t\tlistRegions = append(listRegions, region)\n\t\t}\n\t}\n\treturn listRegions, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
trackConfigFileChanges monitors the host file using fsnotfiy
|
func trackConfigFileChanges(ctx context.Context, configFilePath string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
logs.LogWithFields(ctx).Error(err.Error())
}
err = watcher.Add(configFilePath)
if err != nil {
logs.LogWithFields(ctx).Error(err.Error())
}
go func() {
for {
select {
case fileEvent, ok := <-watcher.Events:
if !ok {
continue
}
if fileEvent.Op&fsnotify.Write == fsnotify.Write || fileEvent.Op&fsnotify.Remove == fsnotify.Remove {
logs.LogWithFields(ctx).Info("modified file:" + fileEvent.Name)
// update the host file
addHost(ctx, configFilePath)
}
//Reading file to continue the watch
watcher.Add(configFilePath)
case err, _ := <-watcher.Errors:
if err != nil {
logs.LogWithFields(ctx).Error(err.Error())
defer watcher.Close()
}
}
}
}()
}
|
[
"func WatchConfigFileChanges(watcher *fsnotify.Watcher, fname string, cb func()) {\n\tfor {\n\t\tselect {\n\t\tcase event := <-watcher.Events:\n\t\t\t// You may wonder why we can't just listen for \"Write\" events. The reason is that vim (and other editors)\n\t\t\t// will create swap files, and when you write they delete the original and rename the swap file. This is great\n\t\t\t// for resolving system crashes, but also completely incompatible with inotify and other fswatch implementations.\n\t\t\t// Thus, we check that the file of interest might be created as well.\n\t\t\tupdated := event.Op&fsnotify.Create == fsnotify.Create || event.Op&fsnotify.Write == fsnotify.Write\n\t\t\tzapconf := filepath.Clean(event.Name) == fname\n\t\t\tif updated && zapconf {\n\t\t\t\tcb()\n\t\t\t}\n\t\tcase e := <-watcher.Errors:\n\t\t\tlog.Println(\"error:\", e)\n\t\t}\n\t}\n}",
"func OnConfigChange(syncTime time.Duration) {\n\tConfig.WatchConfig()\n\tConfig.OnConfigChange(func(e fsnotify.Event) {\n\t\tfmt.Printf(\"'%s' config file is changed\\n\", e.Name)\n\t})\n}",
"func watcher(configModel model.Config) {\n\t// Set the client variable\n\tconfig.Client = configModel.Client.Name\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer watcher.Close()\n\n\tdone := make(chan struct{})\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tif event.Op&fsnotify.Write == fsnotify.Write {\n\t\t\t\t\tlogs.INFO.Println(\"Modified file -> \", event.Name)\n\t\t\t\t\t// When the file name has not been defined, it is time to\n\t\t\t\t\t// use the SetFile() method to add a new file to read.\n\t\t\t\t\tif filename == \"\" {\n\t\t\t\t\t\tstore.SetFile(event.Name)\n\t\t\t\t\t\tfilename = event.Name\n\t\t\t\t\t}\n\t\t\t\t\tif filename != \"\" && filename != event.Name {\n\t\t\t\t\t\tlogs.INFO.Println(\"Reset seek\")\n\t\t\t\t\t\tseek = 0\n\t\t\t\t\t}\n\t\t\t\t\treadLines(event.Name)\n\t\t\t\t}\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlogs.CRITICAL.Println(\"Error on watcher: \", err)\n\t\t\t}\n\t\t}\n\t}()\n\terr = watcher.Add(configModel.Pathlog.Name)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t<-done\n}",
"func watchConfig() {\n viper.WatchConfig()\n viper.OnConfigChange(func(e fsnotify.Event) {\n logrus.Info(\"Config file changed: %s\", e.Name)\n })\n}",
"func (h *manager) configWatcher(stop <-chan struct{}) {\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tklog.Fatalf(\"failed init fsnotify watcher: %v\", err)\n\t}\n\tdefer w.Close()\n\terr = w.Add(filepath.Dir(checkConfigFile))\n\tif err != nil {\n\t\tklog.Fatalf(\"failed add dir watcher(%s): %v\", filepath.Dir(checkConfigFile), err)\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-w.Events:\n\t\t\th.reload()\n\t\tcase err := <-w.Errors:\n\t\t\tklog.Errorf(\"fsnotify error: %v\", err)\n\t\tcase <-stop:\n\t\t\treturn\n\t\t}\n\t}\n}",
"func OnConfigChanged(_ fsnotify.Event) {\n\tloadConfig()\n\tlogrus.Info(\"configuration is reloaded\")\n}",
"func handleFileChange(event fsnotify.Event) {\n\tfmt.Println(event)\n}",
"func (n *Notifier) configCheck() {\n\tlog.Infof(\"Checking for config changes...\")\n\n\ts := n.Source()\n\tlast := n.last\n\tnote, err := n.pullConfig(s)\n\tif err != nil && s == SourcePeer {\n\t\tlog.Errorf(\"Failed to pull configuration from peer: %v\", err)\n\t\tn.peerFailures++\n\t\tif n.peerFailures < n.engineCfg.MaxPeerConfigSyncErrors {\n\t\t\treturn\n\t\t}\n\t\tlog.Infof(\"Sync from peer failed %v times, falling back to config server\",\n\t\t\tn.engineCfg.MaxPeerConfigSyncErrors)\n\t\ts = SourceServer\n\t\tnote, err = n.pullConfig(s)\n\t}\n\tn.peerFailures = 0\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to pull configuration: %v\", err)\n\t\treturn\n\t}\n\n\tif s != SourceDisk && s != SourcePeer {\n\t\toldMeta := last.protobuf.Metadata\n\t\tnewMeta := note.protobuf.Metadata\n\t\tif oldMeta != nil && newMeta != nil && oldMeta.GetLastUpdated() > newMeta.GetLastUpdated() {\n\t\t\tlog.Infof(\"Ignoring out-of-date config from %v\", note.SourceDetail)\n\t\t\treturn\n\t\t}\n\t}\n\n\tif note.Cluster.Equal(last.Cluster) {\n\t\tlog.Infof(\"No config changes found\")\n\t\treturn\n\t}\n\n\t// If there's only metadata differences, note it so we can skip some processing later.\n\toldCluster := *n.last.Cluster\n\toldCluster.Status = seesaw.ConfigStatus{}\n\tnewCluster := *note.Cluster\n\tnewCluster.Status = seesaw.ConfigStatus{}\n\tif newCluster.Equal(&oldCluster) {\n\t\tnote.MetadataOnly = true\n\t}\n\n\tnote.Cluster.Vservers = rateLimitVS(newCluster.Vservers, oldCluster.Vservers)\n\n\tlog.Infof(\"Sending config update notification\")\n\tselect {\n\tcase n.outgoing <- *note:\n\tdefault:\n\t\tlog.Warning(\"Config update channel is full. Skipped one config.\")\n\t\treturn\n\t}\n\tn.last = note\n\tlog.Infof(\"Sent config update notification\")\n\n\tif s != SourceDisk {\n\t\tif err := saveConfig(note.protobuf, n.engineCfg.ClusterFile, !note.MetadataOnly); err != nil {\n\t\t\tlog.Warningf(\"Failed to save config to %s: %v\", n.engineCfg.ClusterFile, err)\n\t\t}\n\t}\n}",
"func OnK8sFileConfigChangeHook(k8sConfigFileChangeEvent model.K8sConfigFileChangeEvent) error {\n\tfmt.Println(\"this is OnK8sFileConfigChangeHook plugin\")\n\treturn nil\n}",
"func updateConfigFile(context *cli.Context) {\n\tconfig, configFilename, err := lib.GetConfig(context)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\tif configFilename == \"\" {\n\t\tfmt.Println(\"Could not find a config file to update\")\n\t\treturn\n\t}\n\n\t// Same config in []byte format.\n\tconfigRaw, err := ioutil.ReadFile(configFilename)\n\tif err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\t// Same config in map format so that we can detect missing keys.\n\tvar configMap map[string]interface{}\n\tif err = json.Unmarshal(configRaw, &configMap); err != nil {\n\t\tlog.Fatalln(err)\n\t}\n\n\tdirty := updateConfig(config, configMap)\n\n\tif dirty {\n\t\tconfig.ToFile(context)\n\t\tfmt.Printf(\"Wrote %s\\n\", configFilename)\n\t} else {\n\t\tfmt.Println(\"Nothing to update\")\n\t}\n}",
"func (r *TrafficOpsReq) checkConfigFile(cfg *ConfigFile, filesAdding []string) error {\n\tif cfg.Name == \"\" {\n\t\tcfg.AuditFailed = true\n\t\treturn errors.New(\"Config file name is empty is empty, skipping further checks.\")\n\t}\n\n\tif cfg.Dir == \"\" {\n\t\tcfg.AuditFailed = true\n\t\treturn errors.New(\"No location information for \" + cfg.Name)\n\t}\n\t// return if audit has already been done.\n\tif cfg.AuditComplete {\n\t\treturn nil\n\t}\n\n\tif !util.MkDirWithOwner(cfg.Dir, r.Cfg.ReportOnly, &cfg.Uid, &cfg.Gid) {\n\t\tcfg.AuditFailed = true\n\t\treturn errors.New(\"Unable to create the directory '\" + cfg.Dir + \" for \" + \"'\" + cfg.Name + \"'\")\n\t}\n\n\tlog.Debugf(\"======== Start processing config file: %s ========\\n\", cfg.Name)\n\n\tif cfg.Name == \"50-ats.rules\" {\n\t\terr := r.processUdevRules(cfg)\n\t\tif err != nil {\n\t\t\tcfg.AuditFailed = true\n\t\t\treturn errors.New(\"unable to process udev rules in '\" + cfg.Name + \"': \" + err.Error())\n\t\t}\n\t}\n\n\tif cfg.Name == \"remap.config\" {\n\t\terr := r.processRemapOverrides(cfg)\n\t\tif err != nil {\n\t\t\tcfg.AuditFailed = true\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// perform plugin verification\n\tif cfg.Name == \"remap.config\" || cfg.Name == \"plugin.config\" {\n\t\tif err := checkRefs(r.Cfg, cfg.Body, filesAdding); err != nil {\n\t\t\tr.configFileWarnings[cfg.Name] = append(r.configFileWarnings[cfg.Name], \"failed to verify '\"+cfg.Name+\"': \"+err.Error())\n\t\t\tcfg.AuditFailed = true\n\t\t\treturn errors.New(\"failed to verify '\" + cfg.Name + \"': \" + err.Error())\n\t\t}\n\t\tlog.Infoln(\"Successfully verified plugins used by '\" + cfg.Name + \"'\")\n\t}\n\n\tif strings.HasSuffix(cfg.Name, \".cer\") {\n\t\terr, fatal := checkCert(cfg.Body)\n\t\tif err != nil {\n\t\t\tr.configFileWarnings[cfg.Name] = append(r.configFileWarnings[cfg.Name], err.Error())\n\t\t}\n\t\tr.configFileWarnings[cfg.Name] = append(r.configFileWarnings[cfg.Name], cfg.Warnings...)\n\t\tif fatal {\n\t\t\treturn errors.New(err.Error() + \" for: \" + cfg.Name)\n\t\t}\n\t}\n\n\tchangeNeeded, err := diff(r.Cfg, cfg.Body, cfg.Path, r.Cfg.ReportOnly, cfg.Perm, cfg.Uid, cfg.Gid)\n\n\tif err != nil {\n\t\tcfg.AuditFailed = true\n\t\treturn errors.New(\"getting diff: \" + err.Error())\n\t}\n\tcfg.ChangeNeeded = changeNeeded\n\tcfg.AuditComplete = true\n\n\tlog.Infof(\"======== End processing config file: %s for service: %s ========\\n\", cfg.Name, cfg.Service)\n\treturn nil\n}",
"func ConfigMapChanges(file string) (<-chan []byte, <-chan error, <-chan struct{}, error) {\n\terrCh := make(chan error)\n\tfCh := make(chan []byte)\n\tdone := make(chan struct{})\n\n\tw, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\twatchDir, err := DirOfSymlink(file)\n\tif err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tif err = w.Add(watchDir); err != nil {\n\t\treturn nil, nil, nil, err\n\t}\n\n\tgo func() {\n\t\tvar err error\n\t\tdefer w.Close()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase err = <-w.Errors:\n\t\t\t\terrCh <- err\n\n\t\t\tcase event := <-w.Events:\n\t\t\t\t// backing file are removed after updates\n\t\t\t\tif event.Op == fsnotify.Remove {\n\t\t\t\t\t// remove the watcher since the file is removed\n\t\t\t\t\tw.Remove(watchDir)\n\n\t\t\t\t\twatchDir, err = DirOfSymlink(file)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrCh <- err\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\t// add a new watcher pointing to the new symlink dir\n\t\t\t\t\tif err = w.Add(watchDir); err != nil {\n\t\t\t\t\t\terrCh <- err\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\n\t\t\t\t\tb, err := ioutil.ReadFile(file)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\terrCh <- err\n\t\t\t\t\t}\n\t\t\t\t\tfCh <- b\n\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t\tdone <- struct{}{}\n\n\t}()\n\treturn fCh, errCh, done, nil\n}",
"func (fc *FilterConfig) initFsnotifyEventHandler() {\n\tconst pauseDelay = 5 * time.Second // used to let all changes be done before reloading the file\n\tgo func() {\n\t\ttimer := time.NewTimer(0)\n\t\tdefer timer.Stop()\n\t\tfirstTime := true\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tif firstTime {\n\t\t\t\t\tfirstTime = false\n\t\t\t\t} else {\n\t\t\t\t\tfc.reloadFile()\n\t\t\t\t}\n\t\t\tcase <-fc.watcher.Events:\n\t\t\t\ttimer.Reset(pauseDelay)\n\t\t\tcase err := <-fc.watcher.Errors:\n\t\t\t\tgoglog.Logger.Errorf(\"ip2location: %s\", err.Error())\n\t\t\tcase <-fc.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}",
"func initFileWatcher(configFilePath string) {\n\tvar err error\n\twatcher, err = fsnotify.NewWatcher()\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"Unable To Setup Logging Config File Watcher: %v\", err))\n\t}\n\tstartWatchListener(configFilePath)\n}",
"func monitorLocalChanges(rootdir string, cafile string, server string, listFileInProcess *ListFileInProcess) {\n\tfmt.Println(\"*** Recursively monitoring folder\", rootdir)\n\twatcher, err := watch.NewWatcher(rootdir, hasher.PROCESSING_DIR)\n\t//watcher, err := watch.NewRecursiveWatcher(rootdir, hasher.PROCESSING_DIR)\n\tif err != nil {\n\t\tlog.Println(\"Watcher create error : \", err)\n\t}\n\tdefer watcher.Close()\n\t_done := make(chan bool)\n\n\tgo func() {\n\t\twatcher.start()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-watcher.Events:\n\t\t\t\tswitch {\n\t\t\t\tcase event.Op&fsnotify.Create == fsnotify.Create:\n\t\t\t\t\tfi, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// eg. stat .subl513.tmp : no such file or directory\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t} else if fi.IsDir() {\n\t\t\t\t\t\tfmt.Println(\"Detected new directory\", event.Name)\n\t\t\t\t\t\tif !watch.ShouldIgnoreFile(filepath.Base(event.Name), hasher.PROCESSING_DIR) {\n\t\t\t\t\t\t\tfmt.Println(\"Monitoring new folder...\")\n\t\t\t\t\t\t\twatcher.AddFolder(event.Name)\n\t\t\t\t\t\t\tconnsender := connectToServer(cafile, server)\n\t\t\t\t\t\t\tgo sendClientFolderChanges(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t\t\t//watcher.Folders <- event.Name\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(\"Detected new file, for now do nothing\", event.Name)\n\t\t\t\t\t\t// watcher.Files <- event.Name // created a file\n\t\t\t\t\t\t// TODO\n\t\t\t\t\t}\n\n\t\t\t\tcase event.Op&fsnotify.Write == fsnotify.Write:\n\t\t\t\t\t// modified a file, assuming that you don't modify folders\n\t\t\t\t\tfmt.Println(\"Detected file modification\", event.Name)\n\t\t\t\t\t// Don't handle folder change, since they receive notification\n\t\t\t\t\t// when a file they contain is changed\n\t\t\t\t\tfi, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tfmt.Println(err)\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif fi.Mode().IsRegular() {\n\t\t\t\t\t\t// watcher.Files <- event.Name\n\t\t\t\t\t\tlog.Println(\"Modified file: \", event.Name)\n\t\t\t\t\t\t// connsender := connectToServer(cafile, server)\n\t\t\t\t\t\t// go sendClientChanges(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Remove == fsnotify.Remove:\n\t\t\t\t\tlog.Println(\"Removed file: \", event.Name)\n\t\t\t\t\t// connsender := connectToServer(cafile, server)\n\t\t\t\t\t// go sendClientDelete(connsender, event.Name, listFileInProcess)\n\t\t\t\tcase event.Op&fsnotify.Rename == fsnotify.Rename:\n\t\t\t\t\tlog.Println(\"Renamed file: \", event.Name)\n\t\t\t\t\t// The following is to handle an issue in fsnotify\n\t\t\t\t\t// On rename, fsnotify sends three events on linux: RENAME(old), CREATE(new), RENAME(new)\n\t\t\t\t\t// fsnotify sends two events on windows: RENAME(old), CREATE(new)\n\t\t\t\t\t// The way we handle this is:\n\t\t\t\t\t// 1. If there is a second rename, skip it\n\t\t\t\t\t// 2. When the first rename happens, remove old file/folder\n\t\t\t\t\t// 3. We'll re-add it when the new create comes in\n\t\t\t\t\t// Step 2 and 3 might be optimized later by remembering which was old/new and performing simple move\n\t\t\t\t\t_, err := os.Stat(event.Name)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t// Rename talks about a file/folder now gone, send a remove request to server\n\t\t\t\t\t\tlog.Println(\"Rename leading to delete\", event.Name)\n\t\t\t\t\t\tconnsender := connectToServer(cafile, server)\n\t\t\t\t\t\tgo sendClientDelete(connsender, event.Name, listFileInProcess)\n\t\t\t\t\t} else {\n\t\t\t\t\t\t// Rename talks about a file/folder already existing, skip it (do nothing)\n\t\t\t\t\t}\n\t\t\t\tcase event.Op&fsnotify.Chmod == fsnotify.Chmod:\n\t\t\t\t\tlog.Println(\"File changed permission: \", event.Name)\n\t\t\t\t}\n\n\t\t\tcase err := <-watcher.Errors:\n\t\t\t\tlog.Println(\"Watcher watching error : \", err)\n\t\t\t\t_done <- true\n\t\t\t\tdone <- true\n\t\t\t}\n\t\t}\n\n\t}()\n\n\t<-_done\n}",
"func (c *conditionManager) policyConfigFileWatcher() {\n\tlog.Infof(\"Start policy file watcher\\n\")\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\tlog.Errorf(\"create a new file wather error %v\\n\", err)\n\t\treturn\n\t}\n\tdefer watcher.Close()\n\n\tif err := watcher.Add(c.policyConfigFile); err != nil {\n\t\tlog.Errorf(\"add policy config file watcher error %v\\n\", err)\n\t\treturn\n\t}\n\n\tfor {\n\t\tselect {\n\t\t// watch for events\n\t\tcase event := <- watcher.Events:\n\t\t\tif event.Op == fsnotify.Write || event.Op == fsnotify.Create {\n\t\t\t\tc.loadPolicyConfig()\n\t\t\t}\n\t\t}\n\t}\n}",
"func (c *clientImpl) fireFileChangeEvent(info *ConfigInfo) {\n\tc.infoLock.Lock()\n\tc.info = *info\n\tc.infoLock.Unlock()\n\n\t// need to clone listener as the callback could call AddListener/RemoveListener\n\tc.listenerLock.Lock()\n\tlisteners := c.listeners[:]\n\tc.listenerLock.Unlock()\n\n\tfor _, regch := range listeners {\n\t\tfor _, f := range info.ModFiles {\n\t\t\tlogrus.Infof(\"Matching listener <%v> vs file <%v>\", regch, f)\n\t\t\tif regch.regex.Match([]byte(f.Path)) {\n\t\t\t\tlogrus.Infof(\"Matched listener <%v> vs file <%v>\", regch, f)\n\t\t\t\t*regch.ch <- f\n\t\t\t}\n\t\t}\n\t}\n}",
"func (s *Server) WatchForConfigChanges() {\n\t// Set up the file watcher\n\tw := watcher.New()\n\n\t// SetMaxEvents to 1 to allow at most 1 event's to be received\n\t// on the Event channel per watching cycle.\n\t//\n\t// If SetMaxEvents is not set, the default is to send all events.\n\tw.SetMaxEvents(1)\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase event := <-w.Event:\n\t\t\t\ts.ReloadConfiguration(event.Path)\n\t\t\tcase err := <-w.Error:\n\t\t\t\ts.Logger.Err(err)\n\t\t\tcase <-w.Closed:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\t// Watch this file for changes.\n\tif err := w.Add(s.configFile); err != nil {\n\t\ts.Logger.Error().Err(err)\n\t\treturn\n\t}\n\n\tif err := w.Start(10 * time.Second); err != nil {\n\t\ts.Logger.Error().Err(err)\n\t\treturn\n\t}\n}",
"func (fc *FilterConfig) initFsnotifyEventHandler() {\n\tconst pauseDelay = 5 * time.Second // used to let all changes be completed before reloading the file\n\tgo func() {\n\t\ttimer := time.NewTimer(0)\n\t\tdefer timer.Stop()\n\t\tfirstTime := true\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-timer.C:\n\t\t\t\tif firstTime {\n\t\t\t\t\tfirstTime = false\n\t\t\t\t} else {\n\t\t\t\t\tfc.reloadFile()\n\t\t\t\t}\n\t\t\tcase <-fc.watcher.Events:\n\t\t\t\ttimer.Reset(pauseDelay)\n\t\t\tcase err := <-fc.watcher.Errors:\n\t\t\t\tgoglog.Logger.Errorf(\"%s: %s\", ModuleName, err.Error())\n\t\t\tcase <-fc.ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
createContext creates a new context based on transactionId, actionId, actionName, threadId, threadName, ProcessName
|
func createContext(transactionID, actionID, actionName, threadID, threadName, ProcessName string) context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, common.TransactionID, transactionID)
ctx = context.WithValue(ctx, common.ActionID, actionID)
ctx = context.WithValue(ctx, common.ActionName, actionName)
ctx = context.WithValue(ctx, common.ThreadID, threadID)
ctx = context.WithValue(ctx, common.ThreadName, threadName)
ctx = context.WithValue(ctx, common.ProcessName, ProcessName)
return ctx
}
|
[
"func (c *Constructor) createScenarioContext(\n\tsender string,\n\tsenderValue *big.Int,\n\trecipient string,\n\trecipientValue *big.Int,\n\tchangeAddress string,\n\tchangeValue *big.Int,\n\tcoinIdentifier *types.CoinIdentifier,\n) (*scenario.Context, []*types.Operation, error) {\n\t// We create a deep copy of the scenaerio (and the change scenario)\n\t// to ensure we don't accidentally overwrite the loaded configuration\n\t// while hydrating values.\n\tscenarioOps := []*types.Operation{}\n\tif err := copier.Copy(&scenarioOps, c.scenario); err != nil {\n\t\treturn nil, nil, fmt.Errorf(\"%w: unable to copy scenario\", err)\n\t}\n\n\tif len(changeAddress) > 0 {\n\t\tchangeCopy := types.Operation{}\n\t\tif err := copier.Copy(&changeCopy, c.changeScenario); err != nil {\n\t\t\treturn nil, nil, fmt.Errorf(\"%w: unable to copy change intent\", err)\n\t\t}\n\n\t\tscenarioOps = append(scenarioOps, &changeCopy)\n\t}\n\n\treturn &scenario.Context{\n\t\tSender: sender,\n\t\tSenderValue: senderValue,\n\t\tRecipient: recipient,\n\t\tRecipientValue: recipientValue,\n\t\tCurrency: c.currency,\n\t\tCoinIdentifier: coinIdentifier,\n\t\tChangeAddress: changeAddress,\n\t\tChangeValue: changeValue,\n\t}, scenarioOps, nil\n}",
"func createContext(next http.HandlerFunc) http.HandlerFunc {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\theader := r.Header\n\t\tctx := r.Context()\n\t\trequestID := header.Get(RequestID)\n\t\tif requestID == \"\" {\n\t\t\trequestID = uuid.NewV4().String()\n\t\t}\n\t\tcorrelationID := header.Get(CorrelationID)\n\t\tif correlationID == \"\" {\n\t\t\tcorrelationID = uuid.NewV4().String()\n\t\t}\n\n\t\ttoken, client := header.Get(PlivoAPIToken), header.Get(\"clientID\")\n\t\tapiCtx := APIContext{\n\t\t\tClientID: client,\n\t\t\tToken: token,\n\t\t\tRequestID: requestID,\n\t\t\tCorrelationID: correlationID,\n\t\t}\n\t\tctx = WithAPICtx(ctx, apiCtx)\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}",
"func CreateTestContext(c qhttp.Controller, r *http.Request) (context *qhttp.Context) {\n\tw := httptest.NewRecorder()\n\trouter := qhttp.CreateRouter(c)\n\tcontext = qhttp.CreateContext(w, r, router)\n\treturn context\n}",
"func CreateTestContext(w http.ResponseWriter) (c *Context, r *Engine) {\n\tr = New()\n\tc = r.allocateContext()\n\tc.reset()\n\tc.writermem.reset(w)\n\treturn\n}",
"func makeContext(manager *Manager, params helpers.H) *Context {\n\tcontext := &Context{\n\t\tmanager: manager,\n\t\tparams: helpers.MakeDictionary(params),\n\t}\n\n\treturn context\n}",
"func createContext(ctx context.Context, t uint64) (context.Context, context.CancelFunc) {\n\ttimeout := time.Duration(t) * time.Millisecond\n\treturn context.WithTimeout(ctx, timeout*time.Millisecond)\n}",
"func NewContext(ctx context.Context, txn Transaction) context.Context {\n\treturn context.WithValue(ctx, contextKey, txn)\n}",
"func (a *OrchestrationContextApiService) CreateContext(ctx context.Context, body ContextInputRepresentation) (ContextRepresentation, *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 \tsuccessPayload ContextRepresentation\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/contexts\"\n\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\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{\n\t\t\"application/json\",\n\t\t}\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 = &body\n\tr, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes)\n\tif err != nil {\n\t\treturn successPayload, nil, err\n\t}\n\n\tlocalVarHttpResponse, err := a.client.callAPI(r)\n\tif err != nil || localVarHttpResponse == nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\tdefer localVarHttpResponse.Body.Close()\n\tif localVarHttpResponse.StatusCode >= 300 {\n\t\tbodyBytes, _ := ioutil.ReadAll(localVarHttpResponse.Body)\n\t\treturn successPayload, localVarHttpResponse, reportError(\"Status: %v, Body: %s\", localVarHttpResponse.Status, bodyBytes)\n\t}\n\n\tif err = json.NewDecoder(localVarHttpResponse.Body).Decode(&successPayload); err != nil {\n\t\treturn successPayload, localVarHttpResponse, err\n\t}\n\n\n\treturn successPayload, localVarHttpResponse, err\n}",
"func createContext(t *testing.T, role browser.Role, lic bool) context.Context {\n\tt.Helper()\n\n\tu := &browser.User{\n\t\tRole: role,\n\t\tLicense: lic,\n\t}\n\treturn context.WithValue(context.Background(), browser.UserContextKey, u)\n}",
"func makeContext(params helpers.H) *Context {\n\tcontext := &Context{\n\t\tparams: params,\n\t}\n\n\treturn context\n}",
"func NewContext(ctx context.Context, txn Transaction) context.Context {\n\treturn context.WithValue(ctx, transactionKey, txn)\n}",
"func (f *framework) createContext() context.Context {\n\treturn context.WithValue(context.Background(), epochKey, f.epoch)\n}",
"func (c *Context) CreateContext() *Context {\n\treturn newContext(c, c.window, c.resMan)\n}",
"func (app *BaseApp) NewContext(isCheckTx bool, header abci.Header) ctx.Context {\n\tif isCheckTx {\n\t\treturn ctx.NewContext(app.checkState.ms, header, true, app.Logger, app.registerMappers)\n\t}\n\treturn ctx.NewContext(app.deliverState.ms, header, false, app.Logger, app.registerMappers)\n}",
"func newContext(config *Config) (*Context, error) {\n\tctx := &Context{Env: make(map[string]string)}\n\n\tfor _, envVarName := range config.Envvars {\n\t\tvalue := os.Getenv(envVarName)\n\t\tif value != \"\" {\n\t\t\t//log.Printf(\"Env var %s found with value '%s'\", envVarName, value)\n\t\t\tctx.Env[envVarName] = value\n\t\t} else {\n\t\t\treturn nil, errors.New(fmt.Sprintf(\"Env var %s not defined!\", envVarName))\n\t\t}\n\t}\n\n\treturn ctx, nil\n}",
"func NewContext(ctx context.Context, t Trace) context.Context {\n\treturn context.WithValue(ctx, _ctxKey, t)\n}",
"func newTestContext() (tc *testContext, err error) {\n\ttc = new(testContext)\n\n\tconst genesisHash = \"0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206\"\n\tif tc.netParams, err = tc.createNetParams(genesisHash); err != nil {\n\t\treturn\n\t}\n\n\tconst block1Hex = \"0000002006226e46111a0b59caaf126043eb5bbf28c34f3a5e332a1fc7b2b73cf188910fadbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fdc30f9858ffff7f20000000000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff03510101ffffffff0100f2052a010000001976a9143ca33c2e4446f4a305f23c80df8ad1afdcf652f988ac00000000\"\n\tif tc.block1, err = blockFromHex(block1Hex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized block: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingInputPrivKeyHex = \"6bd078650fcee8444e4e09825227b801a1ca928debb750eb36e6d56124bb20e8\"\n\ttc.fundingInputPrivKey, err = privkeyFromHex(fundingInputPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPrivKeyHex = \"30ff4956bbdd3222d44cc5e8a1261dab1e07957bdac5ae88fe3261ef321f3749\"\n\ttc.localFundingPrivKey, err = privkeyFromHex(localFundingPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPrivKeyHex = \"bb13b121cdc357cd2e608b0aea294afca36e2b34cf958e2e6451a2f274694491\"\n\ttc.localPaymentPrivKey, err = privkeyFromHex(localPaymentPrivKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized privkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localFundingPubKeyHex = \"023da092f6980e58d2c037173180e9a465476026ee50f96695963e8efe436f54eb\"\n\ttc.localFundingPubKey, err = pubkeyFromHex(localFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remoteFundingPubKeyHex = \"030e9f7b623d2ccc7c9bd44d66d5ce21ce504c0acf6385a132cec6d3c39fa711c1\"\n\ttc.remoteFundingPubKey, err = pubkeyFromHex(remoteFundingPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localRevocationPubKeyHex = \"0212a140cd0c6539d07cd08dfe09984dec3251ea808b892efeac3ede9402bf2b19\"\n\ttc.localRevocationPubKey, err = pubkeyFromHex(localRevocationPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentPubKeyHex = \"030d417a46946384f88d5f3337267c5e579765875dc4daca813e21734b140639e7\"\n\ttc.localPaymentPubKey, err = pubkeyFromHex(localPaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentPubKeyHex = \"0394854aa6eab5b2a8122cc726e9dded053a2184d88256816826d6231c068d4a5b\"\n\ttc.remotePaymentPubKey, err = pubkeyFromHex(remotePaymentPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localDelayPubKeyHex = \"03fd5960528dc152014952efdb702a88f71e3c1653b2314431701ec77e57fde83c\"\n\ttc.localDelayPubKey, err = pubkeyFromHex(localDelayPubKeyHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst commitmentPointHex = \"025f7117a78150fe2ef97db7cfc83bd57b2e2c0d0dd25eaf467a4a1c2a45ce1486\"\n\ttc.commitmentPoint, err = pubkeyFromHex(commitmentPointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst localPaymentBasePointHex = \"034f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa\"\n\ttc.localPaymentBasePoint, err = pubkeyFromHex(localPaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst remotePaymentBasePointHex = \"032c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991\"\n\ttc.remotePaymentBasePoint, err = pubkeyFromHex(remotePaymentBasePointHex)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized pubkey: %v\", err)\n\t\treturn\n\t}\n\n\tconst fundingChangeAddressStr = \"bcrt1qgyeqfmptyh780dsk32qawsvdffc2g5q5sxamg0\"\n\ttc.fundingChangeAddress, err = btcutil.DecodeAddress(\n\t\tfundingChangeAddressStr, tc.netParams)\n\tif err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse address: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingInputUtxo, tc.fundingInputTxOut, err = tc.extractFundingInput()\n\tif err != nil {\n\t\treturn\n\t}\n\n\tconst fundingTxHex = \"0200000001adbb20ea41a8423ea937e76e8151636bf6093b70eaff942930d20576600521fd000000006b48304502210090587b6201e166ad6af0227d3036a9454223d49a1f11839c1a362184340ef0240220577f7cd5cca78719405cbf1de7414ac027f0239ef6e214c90fcaab0454d84b3b012103535b32d5eb0a6ed0982a0479bbadc9868d9836f6ba94dd5a63be16d875069184ffffffff028096980000000000220020c015c4a6be010e21657068fc2e6a9d02b27ebe4d490a25846f7237f104d1a3cd20256d29010000001600143ca33c2e4446f4a305f23c80df8ad1afdcf652f900000000\"\n\tif tc.fundingTx, err = txFromHex(fundingTxHex); err != nil {\n\t\terr = fmt.Errorf(\"Failed to parse serialized tx: %v\", err)\n\t\treturn\n\t}\n\n\ttc.fundingOutpoint = wire.OutPoint{\n\t\tHash: *tc.fundingTx.Hash(),\n\t\tIndex: 0,\n\t}\n\n\ttc.shortChanID = lnwire.ShortChannelID{\n\t\tBlockHeight: 1,\n\t\tTxIndex: 0,\n\t\tTxPosition: 0,\n\t}\n\n\thtlcData := []struct {\n\t\tincoming bool\n\t\tamount lnwire.MilliSatoshi\n\t\texpiry uint32\n\t\tpreimage string\n\t}{\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 1000000,\n\t\t\texpiry: 500,\n\t\t\tpreimage: \"0000000000000000000000000000000000000000000000000000000000000000\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 501,\n\t\t\tpreimage: \"0101010101010101010101010101010101010101010101010101010101010101\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 2000000,\n\t\t\texpiry: 502,\n\t\t\tpreimage: \"0202020202020202020202020202020202020202020202020202020202020202\",\n\t\t},\n\t\t{\n\t\t\tincoming: false,\n\t\t\tamount: 3000000,\n\t\t\texpiry: 503,\n\t\t\tpreimage: \"0303030303030303030303030303030303030303030303030303030303030303\",\n\t\t},\n\t\t{\n\t\t\tincoming: true,\n\t\t\tamount: 4000000,\n\t\t\texpiry: 504,\n\t\t\tpreimage: \"0404040404040404040404040404040404040404040404040404040404040404\",\n\t\t},\n\t}\n\n\ttc.htlcs = make([]channeldb.HTLC, len(htlcData))\n\tfor i, htlc := range htlcData {\n\t\tpreimage, decodeErr := hex.DecodeString(htlc.preimage)\n\t\tif decodeErr != nil {\n\t\t\terr = fmt.Errorf(\"Failed to decode HTLC preimage: %v\", decodeErr)\n\t\t\treturn\n\t\t}\n\n\t\ttc.htlcs[i].RHash = sha256.Sum256(preimage)\n\t\ttc.htlcs[i].Amt = htlc.amount\n\t\ttc.htlcs[i].RefundTimeout = htlc.expiry\n\t\ttc.htlcs[i].Incoming = htlc.incoming\n\t}\n\n\ttc.localCsvDelay = 144\n\ttc.fundingAmount = 10000000\n\ttc.dustLimit = 546\n\ttc.feePerKW = 15000\n\n\treturn\n}",
"func (p *AlertingProxy) createProxyContext(ctx *contextmodel.ReqContext, request *http.Request, response *response.NormalResponse) *contextmodel.ReqContext {\n\tcpy := *ctx\n\tcpyMCtx := *cpy.Context\n\tcpyMCtx.Resp = web.NewResponseWriter(ctx.Req.Method, &safeMacaronWrapper{response})\n\tcpy.Context = &cpyMCtx\n\tcpy.Req = request\n\n\t// If RBAC is enabled, the actions are checked upstream and if the user gets here then it is allowed to do an action against a datasource.\n\t// Some data sources require legacy Editor role in order to perform mutating operations. In this case, we elevate permissions for the context that we\n\t// will provide downstream.\n\t// TODO (yuri) remove this after RBAC for plugins is implemented\n\tif !ctx.SignedInUser.HasRole(org.RoleEditor) {\n\t\tnewUser := *ctx.SignedInUser\n\t\tnewUser.OrgRole = org.RoleEditor\n\t\tcpy.SignedInUser = &newUser\n\t}\n\treturn &cpy\n}",
"func CreateAppEngineContext(request *http.Request) appengine.Context {\n\n\tif AppEngineContext == nil {\n\t\t// make a new one\n\t\tAppEngineContext = appengine.NewContext(request)\n\t}\n\n\treturn AppEngineContext\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Easyer way to check error, exit program if error
|
func check(err error) {
if (err != nil) {
fmt.Println(err)
os.Exit(1)
}
}
|
[
"func checkErr(err error) {\n\tif err != nil {\n\t\tfmt.Println(err.Error())\n\t\tos.Exit(1)\n\t}\n}",
"func checkErr(err error) {\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t\tos.Exit(1)\n\t}\n}",
"func exitWithError(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}",
"func errorExit(err error) {\n\tif err != nil {\n\t\tfmt.Println(err)\n\t\tos.Exit(1)\n\t}\n}",
"func failOnErr(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\treport(\"\", err)\n\tos.Exit(2)\n}",
"func exitOnErr111(err error) {\n\tif err != nil {\n\t\tlog.Println(err)\n\t\tos.Exit(111)\n\t}\n}",
"func errorExit(exit_code int, err error) {\n\tfmt.Printf(\"Error: %v\\n\", err)\n\tos.Exit(exit_code)\n}",
"func checkFatal(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t\tos.Exit(1)\n\t}\n}",
"func checkResponse(code int) {\n\tif code != 200 {\n\t\tfmt.Println(\"Error: An error occurred while performing your request. Please try again later.\")\n\t\tos.Exit(1)\n\t}\n}",
"func fail(err error) {\n\t// no error check: if this goes wrong, we're in trouble anyways\n\tfmt.Fprint(os.Stderr, err.Error()) // nolint: gas\n\tos.Exit(1)\n}",
"func ExitOnErr(err error) {\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}",
"func fail(err error) {\n\tfmt.Println(\"match:\", err)\n\tos.Exit(1)\n}",
"func errExit(err error, l logrus.FieldLogger) {\n\tif l != nil {\n\t\tl.Fatal(err)\n\t} else {\n\t\tlog.Fatal(err)\n\t}\n\n\tos.Exit(1)\n}",
"func errExitCode() int {\n\tif *lenient {\n\t\treturn 0\n\t}\n\treturn 1\n}",
"func ExitErr(reason error) {\n\tfmt.Printf(\"ERROR: %v\\n\", reason)\n\tos.Exit(1)\n}",
"func ExitError(msg string, code uint64) {\n PrintString(msg);\n PrintChar(10); //Print new line ('\\n' = 10)\n Exit(code);\n}",
"func exitWithError(err error, rollBackFuncs []rollBackFunc) {\n\tif err != nil {\n\t\tlog.WithError(err).Error()\n\t}\n\tif rollBackFuncs != nil {\n\t\tlog.Info(\"Rolling back changes...\")\n\t\tfor _, r := range rollBackFuncs {\n\t\t\tif err := r(); err != nil {\n\t\t\t\tlog.WithError(err).Error()\n\t\t\t}\n\t\t}\n\t}\n\tos.Exit(1)\n}",
"func dieIfError(err error) {\n\tif err != nil {\n\t\tglog.Fatalln(\"Fatal: \", err)\n\t}\n}",
"func Main(err error) {\n\tif err == nil {\n\t\treturn\n\t}\n\tfmt.Fprintln(os.Stderr, err.Error())\n\tos.Exit(Code)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
userInput reads from Stdin untill newline, if input was empty append space to msg
|
func userInput() string {
msg, err := reader.ReadBytes('\n')
check(err)
if len(msg) == 0 {
msg = append(msg, 32)
}
return string(msg)
}
|
[
"func ReadInputFromUser(message string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tif message != \"\" {\n\t\tfmt.Println(message)\n\t}\n\n\ttext, _ := reader.ReadString('\\n')\n\tvar trimmedText = strings.TrimSpace(text)\n\n\t// Listen while the user enter something instead of pressing enter or space\n\tfor trimmedText == \"\" {\n\t\ttrimmedText = ReadInputFromUser(\"\")\n\t}\n\n\treturn trimmedText\n}",
"func input() {\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\ttext, err := reader.ReadString('\\n')\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t\terr = client.SendRequest(scr.Append(\n\t\t\t\"chat.messages\",\n\t\t\t&Message{Text: string(text[:len(text)-1])},\n\t\t))\n\t\tif err != nil {\n\t\t\tbreak\n\t\t}\n\t}\n\twg.Done()\n}",
"func ReadInput(message string) string {\n\tif message != \"\" {\n\t\tfmt.Printf(\"%s: \", message)\n\t}\n\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\n\treturn scanner.Text()\n}",
"func GetUserInput(question string) string {\n\tlog.Infof(\"%s: \", question)\n\treader := bufio.NewReader(os.Stdin)\n\tif input, _ := reader.ReadString('\\n'); input != \"\\n\" && input != \"\" {\n\t\treturn string(bytes.TrimSuffix([]byte(input), []byte(\"\\n\")))\n\t}\n\treturn \"\"\n}",
"func readInput(prompt string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Print(prompt + \": \")\n\tinput, err := reader.ReadString('\\n')\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn strings.TrimSpace(input)\n}",
"func PromptMessage(message, value string) string {\n\tfor value == \"\" {\n\t\treader := bufio.NewReader(os.Stdin)\n\t\tfmt.Print(message + \": \")\n\t\tvalueRaw, err := reader.ReadString('\\n')\n\t\terrors.CheckError(err)\n\t\tvalue = strings.TrimSpace(valueRaw)\n\t}\n\treturn value\n}",
"func collectDataFromUser(input string) string {\n\treader := bufio.NewReader(os.Stdin)\n\n\tfmt.Print(input + \": \")\n\tdata, _ := reader.ReadString('\\n')\n\treturn strings.Trim(data, \"\\n\")\n}",
"func (p *Prompt) GetInput(msg string) (string, error) {\n\tfmt.Fprintln(p.out, msg)\n\tfmt.Fprint(p.out, \"-> \")\n\tp.out.Flush()\n\ttext, err := p.in.ReadString('\\n')\n\treturn strings.TrimSpace(text), err\n}",
"func watchForConsoleInput(conn net.Conn) {\n reader := bufio.NewReader(os.Stdin)\n\n for true {\n message, err := reader.ReadString('\\n')\n util.CheckForError(err, \"Lost console connection\")\n\n message = strings.TrimSpace(message)\n if (message != \"\") {\n command := parseInput(message)\n\n if (command.Command == \"\") {\n // there is no command so treat this as a simple message to be sent out\n sendCommand(\"message\", message, conn);\n } else {\n switch command.Command {\n\n // enter a room\n case \"enter\":\n sendCommand(\"enter\", command.Body, conn)\n\n // ignore someone\n case \"ignore\":\n sendCommand(\"ignore\", command.Body, conn)\n\n // leave a room\n case \"leave\":\n // leave the current room (we aren't allowing multiple rooms)\n sendCommand(\"leave\", \"\", conn)\n\n // disconnect from the chat server\n case \"disconnect\":\n sendCommand(\"disconnect\", \"\", conn)\n\n default:\n fmt.Printf(\"Unknown command \\\"%s\\\"\\n\", command.Command)\n }\n }\n }\n }\n}",
"func readInput() string {\r\n cmdString, err := reader.ReadString('\\n')\r\n check(err)\r\n\r\n return cmdString\r\n}",
"func getInput(request string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(\"\\n\" + request)\n\tusrInput, _ := reader.ReadString('\\n')\n\treturn strings.TrimSpace(usrInput)\n}",
"func (inputReader InputReader) GetUserInput() string {\n\tdata, _ := inputReader.reader.ReadString('\\n')\n\treturn strings.TrimSuffix(data, \"\\n\")\n}",
"func getInput(input chan string) {\n for {\n reader := bufio.NewReader(os.Stdin)\n d,_ := reader.ReadString('\\n')\n input <- d\n }\n}",
"func Input(s bool, a ...interface{}) string {\n\tif s {\n\t\tfmt.Printf(\"\\a\")\n\t}\n\tfmt.Printf(\"%v\", a...)\n\tscanner := bufio.NewScanner(os.Stdin)\n\tscanner.Scan()\n\treturn scanner.Text()\n}",
"func UserInputHandler() {\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tif input, err := reader.ReadString('\\n'); err != nil {\n\t\t\tlog.Print(err)\n\t\t} else {\n\t\t\tif ws != nil {\n\t\t\t\tif _, err := ws.Write([]byte(input)); err != nil {\n\t\t\t\t\tlog.Print(err)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tlog.Print(\"Connection closed. Try later!\")\n\t\t\t}\n\t\t}\n\t}\n}",
"func ReadUserMessage(msg chan<- []byte) {\n\n\t// Prepare a Reader for input message from the console\n\treader := bufio.NewReader(os.Stdin)\n\tfor {\n\t\tmessage, _ := reader.ReadBytes('\\n')\n\t\tmsg <- message\n\t}\n}",
"func (c *Client) processStdIn() {\n\tscanner := bufio.NewScanner(os.Stdin)\n\tfor {\n\t\tselect {\n\t\tcase <-c.done:\n\t\t\treturn\n\t\tcase <-c.nextRequest:\n\t\t\tif _, err := color.New(color.FgGreen).Print(config.InputIndicator); err != nil {\n\t\t\t\tc.err <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := c.con.WriteMessage(ws.TextMessage, c.readStdIn(scanner)); err != nil {\n\t\t\t\tc.err <- err\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tif err := scanner.Err(); err != nil {\n\t\t\t\tc.err <- err\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}",
"func askForInput(prompt string) string {\n\treader := bufio.NewReader(os.Stdin)\n\tfmt.Println(prompt)\n\tresponse, _ := reader.ReadString('\\n')\n\tfmt.Println(\"\\nThank You\")\n\treturn strings.TrimSpace(response)\n}",
"func readInput(conn net.Conn, qst string) (string, error) {\n\tconn.Write([]byte(qst))\n\ts, err := bufio.NewReader(conn).ReadString('\\n')\n\tif err != nil {\n\t\tlog.Printf(\"readinput: could not read input from stdin: %v from client %v\", err, conn.RemoteAddr().String())\n\t\treturn \"\", err\n\t}\n\ts = strings.Trim(s, \"\\r\\n\")\n\treturn s, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
makeMsg takes opt code for what we want to send and a msg return value will always be 10 bytes
|
func makeMsg(opt int, msg string) []byte {
msg = strings.TrimSpace(msg) //remove space from input
var res = make([]byte, 10) //return array variable for what to send back to srv
res[0] = byte(opt) //opt code will always be on index zero
switch opt {
case 2 : //Withdrawl
if len(msg) > 9 { //cant whithdrawl amounts more than length 9,
break
}
//convert input msg to bytes, each byte gets its own index in res
for index := range msg {
res[index+1] = byte(msg[index])
}
//if msg was less then 9 we fill upp the rest so we always send 10 bytes
res = fillup(res, len(msg)+1, 10)
case 3 : //deposit does same as case 2
if len(msg) > 9 {
break
}
for index := range msg {
res[index+1] = byte(msg[index])
}
res = fillup(res, len(msg) +1, 10)
case 100 : //cardnumber
if len(msg) != 16 { //cardnumber must be 16 digits
break
}
//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255
res[1] = byte(stringToInt(msg[0:2]))
res[2] = byte(stringToInt(msg[2:4]))
res[3] = byte(stringToInt(msg[4:6]))
res[4] = byte(stringToInt(msg[6:8]))
res[5] = byte(stringToInt(msg[8:10]))
res[6] = byte(stringToInt(msg[10:12]))
res[7] = byte(stringToInt(msg[12:14]))
res[8] = byte(stringToInt(msg[14:16]))
res = fillup(res, 9,10)
case 101 : //password
if len(msg) != 4 { //password must be length 4
break
}
//each digit in the password converts to bytes into res
res[1] = byte(stringToInt(msg[0:1]))
res[2] = byte(stringToInt(msg[1:2]))
res[3] = byte(stringToInt(msg[2:3]))
res[4] = byte(stringToInt(msg[3:4]))
res = fillup(res, 5, 10)
case 103 : //engångs koderna must be length 2
if len(msg) != 2 {
break
}
res[1] = byte(msg[0])
res[2] = byte(msg[1])
res= fillup(res, 3, 10)
}
return res
}
|
[
"func makeMsg(name string) *sqs.Message {\n\tb := make([]byte, 32)\n\tif _, err := rand.Read(b); err != nil {\n\t\tpanic(err)\n\t}\n\tmessageID := base64.URLEncoding.EncodeToString(b) + \"-\" + name\n\th := md5.Sum([]byte(name))\n\treceiptHandle := uuid.New().String() + \"-\" + name\n\treturn &sqs.Message{\n\t\tMessageId: aws.String(messageID),\n\t\tMD5OfBody: aws.String(base64.URLEncoding.EncodeToString(h[:])),\n\t\tBody: aws.String(name),\n\t\tReceiptHandle: aws.String(receiptHandle),\n\t}\n}",
"func allocMsg(t string, length int) (messager, error) {\n\tswitch t {\n\tcase \"msgheader\":\n\t\tvar msg msgHdr\n\t\treturn &msg, nil\n\tcase \"version\":\n\t\tvar msg version\n\t\treturn &msg, nil\n\tcase \"verack\":\n\t\tvar msg verACK\n\t\treturn &msg, nil\n\tcase \"getheaders\":\n\t\tvar msg headersReq\n\t\treturn &msg, nil\n\tcase \"headers\":\n\t\tvar msg blkHeader\n\t\treturn &msg, nil\n\tcase \"getaddr\":\n\t\tvar msg addrReq\n\t\treturn &msg, nil\n\tcase \"addr\":\n\t\tvar msg addr\n\t\treturn &msg, nil\n\tcase \"inv\":\n\t\tvar msg inv\n\t\t// the 1 is the inv type lenght\n\t\tmsg.p.blk = make([]byte, length - MSGHDRLEN - 1)\n\t\treturn &msg, nil\n\tcase \"getdata\":\n\t\tvar msg dataReq\n\t\treturn &msg, nil\n\tcase \"block\":\n\t\tvar msg block\n\t\treturn &msg, nil\n\tcase \"tx\":\n\t\tvar msg trn\n\t\treturn &msg, nil\n\tdefault:\n\t\treturn nil, errors.New(\"Unknown message type\")\n\t}\n}",
"func newMsg(opCode int16, receiver string, body string) *mirc.Message {\n\tmsg := mirc.NewMsg(opCode, receiver, body)\n\tmsg.Header.Sender = \"server\"\n\tmsg.Header.Timeout = timeout\n\treturn msg\n}",
"func MakeMsg(msg string) Message {\n\treturn Message{\n\t\tfalse,\n\t\ttime.Now().Unix(),\n\t\tmsg,\n\t}\n}",
"func (a *Asock) genMsg(conn, req uint, code, ml int, txt string, err error) {\n\t// if this message's level is below the instance's level, don't\n\t// generate the message\n\tif ml < a.ml {\n\t\treturn\n\t}\n\tselect {\n\tcase a.Msgr <- &Msg{conn, req, code, txt, err}:\n\tdefault:\n\t}\n}",
"func BuildMsg(from sdk.AccAddress, to sdk.AccAddress, coins sdk.Coins) sdk.Msg {\n\tinput := bank.NewInput(from, coins)\n\toutput := bank.NewOutput(to, coins)\n\tmsg := bank.NewMsgSend([]bank.Input{input}, []bank.Output{output})\n\treturn msg\n}",
"func PrepareMsg(msg *Msgbuf) (*bytes.Buffer, error) {\n\tif len(msg.Mtext) > msgmax {\n\t\treturn nil, fmt.Errorf(\"mtext is too large, %d > %d\", len(msg.Mtext), msgmax)\n\t}\n\n\tbuf := make([]byte, uintSize+msgmax)\n\tbuffer := bytes.NewBuffer(buf)\n\tbuffer.Reset()\n\tvar err error\n\tswitch uintSize {\n\tcase 4:\n\t\terr = binary.Write(buffer, binary.LittleEndian, uint32(msg.Mtype))\n\tcase 8:\n\t\terr = binary.Write(buffer, binary.LittleEndian, uint64(msg.Mtype))\n\t}\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"Can't write binary: %v\", err)\n\t}\n\tbuffer.Write(msg.Mtext)\n\n\treturn buffer, nil\n\n}",
"func sendmsg(s int, msg *unix.Msghdr, flags int) (n int, err error)",
"func makePacket(addr string, args []string) Packet {\n\tmsg := NewMessage(addr)\n\tfor _, arg := range args {\n\t\tmsg.Append(arg)\n\t}\n\treturn msg\n}",
"func (mb *MessageBuilder) msg(msg string) *MessageBuilder {\n\tspace := \"\"\n\tif mb.message > \"\" {\n\t\tspace = \" \"\n\t}\n\tmb.message = fmt.Sprintf(`%s%s%s`, mb.message, space, msg)\n\treturn mb\n}",
"func (conn *Connection) SendMessage(msg message.Messager, timeout time.Duration) (err error) {\n\t// Send residual data\n\tpriBufLen := conn.WriteBuf.Len()\n\tif priBufLen > 0 {\n\t\t_, err = io.CopyN(conn.RWC, conn.WriteBuf, int64(conn.WriteBuf.Len()))\n\t}\n\tif err != nil {\n\t\tutils.Logger.Error(\"Send residual data error with %s\", err.Error())\n\t\treturn\n\t}\n\n\t// Pack data\n\thead := new(frame.Head)\n\thead.Init()\n\thead.Seq = conn.tickSeq()\n\tswitch msg.(type) {\n\tcase *node.ACK:\n\t\thead.CMD = proto.MNCMDACK\n\tcase *node.SessionRsp:\n\t\thead.CMD = proto.MNCMDSessionRsp\n\tcase *knot.ConnRsp:\n\t\thead.CMD = proto.MKCMDConnRsp\n\tcase *knot.AgentArriveReq:\n\t\thead.CMD = proto.MKCMDAgentArriveReq\n\tcase *node.Confirm:\n\t\thead.CMD = proto.MNCMDConfirm\n\tcase *knot.NodeMsg:\n\t\thead.CMD = proto.MKCMDNodeMsg\n\tcase *node.KnotMsg:\n\t\thead.CMD = proto.MNCMDKnotMsg\n\tcase *node.ErrorMsg:\n\t\thead.CMD = proto.MNCMDErrorMsg\n\tcase *knot.AgentQuit:\n\t\thead.CMD = proto.MKCMDAgentQuit\n\tcase *node.Discard:\n\t\thead.CMD = proto.MNCMDDiscard\n\tdefault:\n\t\thead.CMD = proto.MLCMDUnknown\n\n\t}\n\tframe := frame.Frame{\n\t\tHead: head,\n\t\tBody: msg,\n\t}\n\tutils.Logger.Debug(\"before pack buf is %d\", conn.WriteBuf.Len())\n\terr = frame.Pack(conn.WriteBuf)\n\tutils.Logger.Debug(\"after pack buf is %d\", conn.WriteBuf.Len())\n\tif err != nil {\n\t\tutils.Logger.Error(\"Pack frame with error %s\", err.Error())\n\t\treturn\n\t}\n\n\t// Send current package\n\ts, err := io.CopyN(conn.RWC, conn.WriteBuf, int64(conn.WriteBuf.Len()))\n\tif err != nil {\n\t\tutils.Logger.Error(\"Send current packge data error with %s\", err.Error())\n\t\treturn\n\t}\n\tutils.Logger.Debug(\"CopyN with %d\", s)\n\treturn\n}",
"func fillMsg(fromAddress address.Address, api *apistruct.FullNodeStruct, msg *types.Message) (*types.SignedMessage, error) {\n\t// Get nonce\n\tnonce, err := api.MpoolGetNonce(context.Background(), msg.From)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.Nonce = nonce\n\n\t// Calculate gas\n\tlimit, err := api.GasEstimateGasLimit(context.Background(), msg, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasLimit = int64(float64(limit) * 1.25)\n\n\tpremium, err := api.GasEstimateGasPremium(context.Background(), 10, msg.From, msg.GasLimit, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasPremium = premium\n\n\tfeeCap, err := api.GasEstimateFeeCap(context.Background(), msg, 20, types.EmptyTSK)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmsg.GasFeeCap = feeCap\n\n\t// Sign message\n\treturn api.WalletSignMessage(context.Background(), fromAddress, msg)\n}",
"func SendMsg(\n\tr *rand.Rand, app *baseapp.BaseApp, ak authkeeper.AccountKeeper, bk bankkeeper.Keeper,\n\tmsg sdk.Msg, ctx sdk.Context, chainID string, gasValue uint64, privkeys []cryptotypes.PrivKey,\n) error {\n\taddr := msg.GetSigners()[0]\n\taccount := ak.GetAccount(ctx, addr)\n\tcoins := bk.SpendableCoins(ctx, account.GetAddress())\n\n\tfees, err := simtypes.RandomFees(r, ctx, coins)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttxGen := simappparams.MakeTestEncodingConfig().TxConfig\n\ttx, err := helpers.GenTx(\n\t\ttxGen,\n\t\t[]sdk.Msg{msg},\n\t\tfees,\n\t\tgasValue,\n\t\tchainID,\n\t\t[]uint64{account.GetAccountNumber()},\n\t\t[]uint64{account.GetSequence()},\n\t\tprivkeys...,\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t_, _, err = app.Deliver(txGen.TxEncoder(), tx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}",
"func CliMsg(format string, a ...interface{}) {\n\tmsg_color := color.New(color.Bold, color.FgCyan)\n\tlog.Println(msg_color.Sprintf(format, a...))\n\tif IsAPIEnabled {\n\t\t// send to socket\n\t\tvar resp APIResponse\n\t\tmsg := GetDateTime() + \" MSG: \" + fmt.Sprintf(format, a...)\n\t\tresp.MsgData = []byte(msg)\n\t\tresp.Alert = false\n\t\tresp.MsgType = LOG\n\t\tdata, err := json.Marshal(resp)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"CliMsg: %v\", err)\n\t\t\treturn\n\t\t}\n\t\t_, err = APIConn.Write([]byte(data))\n\t\tif err != nil {\n\t\t\tlog.Printf(\"CliMsg: %v\", err)\n\t\t}\n\t}\n}",
"func WriteMessage(w io.Writer, msg Message, pver uint32, btcnet BitcoinNet) error {\n\tvar command [commandSize]byte\n\n\t// Enforce max command size.\n\tcmd := msg.Command()\n\tif len(cmd) > commandSize {\n\t\tstr := fmt.Sprintf(\"command [%s] is too long [max %v]\",\n\t\t\tcmd, commandSize)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\tcopy(command[:], []byte(cmd))\n\n\t// Encode the message payload.\n\tvar bw bytes.Buffer\n\terr := msg.BtcEncode(&bw, pver)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpayload := bw.Bytes()\n\tlenp := len(payload)\n\n\t// Enforce maximum overall message payload.\n\tif lenp > maxMessagePayload {\n\t\tstr := fmt.Sprintf(\"message payload is too large - encoded \"+\n\t\t\t\"%d bytes, but maximum message payload is %d bytes\",\n\t\t\tlenp, maxMessagePayload)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\n\t// Enforce maximum message payload based on the message type.\n\tmpl := msg.MaxPayloadLength(pver)\n\tif uint32(lenp) > mpl {\n\t\tstr := fmt.Sprintf(\"message payload is too large - encoded \"+\n\t\t\t\"%d bytes, but maximum message payload size for \"+\n\t\t\t\"messages of type [%s] is %d.\", lenp, cmd, mpl)\n\t\treturn messageError(\"WriteMessage\", str)\n\t}\n\n\t// Create header for the message.\n\thdr := messageHeader{}\n\thdr.magic = btcnet\n\thdr.command = cmd\n\thdr.length = uint32(lenp)\n\tcopy(hdr.checksum[:], DoubleSha256(payload)[0:4])\n\n\t// Write header.\n\terr = writeElements(w, hdr.magic, command, hdr.length, hdr.checksum)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Write payload.\n\t_, err = w.Write(payload)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func MsgPrepare(common Common, tx *Transfer) base.Message {\n\tif tx.MessageType == 2 && common.PrivateKey != \"\" {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: \"\",\n\t\t}\n\t} else if tx.MessageType == 2 && common.IsHW {\n\t\treturn base.Message{\n\t\t\tType: 2,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t\tPublicKey: tx.RecipientPublicKey,\n\t\t}\n\n\t} else if tx.MessageType == 0 && utils.IsHexadecimal(tx.Message) {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: \"fe\" + tx.Message,\n\t\t}\n\t} else {\n\t\treturn base.Message{\n\t\t\tType: 1,\n\t\t\tPayload: utils.Utf8ToHex(tx.Message),\n\t\t}\n\t}\n}",
"func CodeToDefaultMsg(code sdk.CodeType) string {\n\tswitch code {\n\tcase CodeInvalidValue:\n\t\treturn \"invalid value\"\n\tcase CodeInvalidChainID:\n\t\treturn \"invalid chain ID\"\n\tcase CodeInvalidSender:\n\t\treturn \"could not derive sender from transaction\"\n\tcase CodeVMExecution:\n\t\treturn \"error while executing evm transaction\"\n\tcase CodeInvalidNonce:\n\t\treturn \"invalid nonce\"\n\tdefault:\n\t\treturn sdk.CodeToDefaultMsg(code)\n\t}\n}",
"func (packet *SnmpPacket) marshalMsg(pdus []SnmpPDU,\n\tpdutype PDUType, msgid uint32, requestid uint32) ([]byte, error) {\n\tvar auth_param_start uint32\n\tbuf := new(bytes.Buffer)\n\n\t// version\n\tbuf.Write([]byte{2, 1, byte(packet.Version)})\n\n\tif packet.Version != Version3 {\n\t\t// community\n\t\tbuf.Write([]byte{4, uint8(len(packet.Community))})\n\t\tbuf.WriteString(packet.Community)\n\t\t// pdu\n\t\tpdu, err := packet.marshalPDU(pdus, requestid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf.Write(pdu)\n\t} else {\n\t\theader, err := packet.marshalSnmpV3Header(msgid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf.Write([]byte{byte(Sequence), byte(len(header))})\n\t\tbuf.Write(header)\n\n\t\tvar security_parameters []byte\n\t\tif packet.SecurityModel == UserSecurityModel {\n\t\t\tsecurity_parameters, auth_param_start, err = packet.marshalSnmpV3UsmSecurityParameters()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\n\t\tbuf.Write([]byte{byte(OctetString)})\n\t\tsec_param_len, err := marshalLength(len(security_parameters))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf.Write(sec_param_len)\n\t\tauth_param_start += uint32(buf.Len())\n\t\tbuf.Write(security_parameters)\n\n\t\tscoped_pdu, err := packet.marshalSnmpV3ScopedPDU(pdus, requestid)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbuf.Write(scoped_pdu)\n\t}\n\n\t// build up resulting msg - sequence, length then the tail (buf)\n\tmsg := new(bytes.Buffer)\n\tmsg.WriteByte(byte(Sequence))\n\n\tbufLengthBytes, err2 := marshalLength(buf.Len())\n\tif err2 != nil {\n\t\treturn nil, err2\n\t}\n\tmsg.Write(bufLengthBytes)\n\tauth_param_start += uint32(msg.Len())\n\tbuf.WriteTo(msg) // reverse logic - want to do msg.Write(buf)\n\n\tauthenticated_message, err := packet.authenticate(msg.Bytes(), auth_param_start)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn authenticated_message, nil\n}",
"func (obj *MessagePacket) makeMessagePacket() {\n\tif obj.dataType == 0 {\n\t\tobj.dataType = 2\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
validate login setup from the user, needs cardnumber on 16 digits and sifferkod on 4 digits everything thats Write from loginSetup uses makeMsg to convert the msg to 10 byte array Each msg will start with an opt code and followed by different msg in byte 110
|
func loginSetUp(connection net.Conn) {
fmt.Println(lines[0]) //first line in the given lang file
//infinit loop to read in correct cardnumber
for {
fmt.Print(lines[1])
card := strings.Replace(string(userInput()), " ", "", -1) //remooves space in cardnumber
connection.Write(makeMsg(100, card)) //send msg to srv, first is opt code 100 for cardnumber to be validated
ans := make([]byte, 10) //return value from srv
connection.Read(ans) //read if it was validated from srv, 253 = true
if ans[0] == 253 {
break
} else {
fmt.Println(lines[6]) //received opt code 252 = fail
}
}
//infinit loop to read password
for {
fmt.Print(lines[2])
password := userInput() //read input password from user
connection.Write(makeMsg(101, password)) //makeMsg, opt code 101 for password,
ans := make([]byte, 10)
connection.Read(ans) //validate password from srv
if ans[0] == 253 {
break
} else {
fmt.Println(lines[6])
}
}
}
|
[
"func makeMsg(opt int, msg string) []byte {\n\t\n\tmsg = strings.TrimSpace(msg) //remove space from input\n\tvar res = make([]byte, 10) //return array variable for what to send back to srv\n\tres[0] = byte(opt) //opt code will always be on index zero\n\t\n\tswitch opt {\n\tcase 2 : //Withdrawl\n\t\tif len(msg) > 9 { //cant whithdrawl amounts more than length 9, \n\t\t\tbreak\n\t\t}\n\t\t//convert input msg to bytes, each byte gets its own index in res\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\t//if msg was less then 9 we fill upp the rest so we always send 10 bytes\n\t\tres = fillup(res, len(msg)+1, 10)\n\tcase 3 : //deposit does same as case 2\n\t\tif len(msg) > 9 {\n\t\t\tbreak\n\t\t}\n\t\tfor index := range msg {\n\t\t\tres[index+1] = byte(msg[index])\n\t\t}\n\n\t\tres = fillup(res, len(msg) +1, 10)\n\t\t\n\tcase 100 : //cardnumber\n\t\tif len(msg) != 16 { //cardnumber must be 16 digits\n\t\t\tbreak\n\t\t}\n\t\t//each two digit gets it's own index in res to avoid when we are converintg numbers bigger then 255\n\t\tres[1] = byte(stringToInt(msg[0:2]))\n\t\tres[2] = byte(stringToInt(msg[2:4]))\n\t\tres[3] = byte(stringToInt(msg[4:6]))\n\t\tres[4] = byte(stringToInt(msg[6:8]))\n\t\tres[5] = byte(stringToInt(msg[8:10]))\n\t\tres[6] = byte(stringToInt(msg[10:12]))\n\t\tres[7] = byte(stringToInt(msg[12:14]))\n\t\tres[8] = byte(stringToInt(msg[14:16]))\n\t\tres = fillup(res, 9,10)\n\tcase 101 : //password\n\t\tif len(msg) != 4 { //password must be length 4\n\t\t\tbreak\t\n\t\t}\n\t\t//each digit in the password converts to bytes into res\n\t\tres[1] = byte(stringToInt(msg[0:1]))\n\t\tres[2] = byte(stringToInt(msg[1:2]))\n\t\tres[3] = byte(stringToInt(msg[2:3]))\n\t\tres[4] = byte(stringToInt(msg[3:4]))\n\t\tres = fillup(res, 5, 10)\n\tcase 103 : //engångs koderna must be length 2 \n\t\tif len(msg) != 2 {\n\t\t\tbreak\n\t\t}\n\t\tres[1] = byte(msg[0])\n\t\tres[2] = byte(msg[1])\n\t\tres= fillup(res, 3, 10)\n\t}\n\treturn res\n}",
"func TestCV13(t *testing.T) {\n\tstatedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))\n\tmsg := createValidator()\n\t// details length: 280 characters\n\tmsg.Details = \"HelloiwfhwifbwfbcerghveugbviuscbhwiefbcusidbcifwefhgciwefherhbfiwuehfciwiuebfcuyiewfhwieufwiweifhcwefhwefhwidsffevjnononwondqmeofniowfndjoweHlloiwfhwifbwfbcerghveugbviuscbhwiefbcusidbcifwefhgciwefherhbfiwuehfciwiuedbfcuyiewfhwieufwiweifhcwefhwefhwidsffevjnononwondqmeofniowfndjowe\"\n\tstatedb.AddBalance(msg.ValidatorAddress, tenK)\n\tif _, err := VerifyAndCreateValidatorFromMsg(\n\t\tstatedb, postStakingEpoch, big.NewInt(0), msg,\n\t); err != nil {\n\t\tt.Error(\"expected\", nil, \"got\", err)\n\t}\n}",
"func validateGenerateSIPAuthVectorInputs(key []byte, opc []byte, sqn uint64) error {\n\tif len(key) != ExpectedKeyBytes {\n\t\treturn fmt.Errorf(\"incorrect key size. Expected %v bytes, but got %v bytes\", ExpectedKeyBytes, len(key))\n\t}\n\tif len(opc) != ExpectedOpcBytes {\n\t\treturn fmt.Errorf(\"incorrect opc size. Expected %v bytes, but got %v bytes\", ExpectedOpcBytes, len(opc))\n\t}\n\tif sqn > maxSqn {\n\t\treturn fmt.Errorf(\"sequence number too large, expected a number which can fit in 48 bits. Got: %v\", sqn)\n\t}\n\treturn nil\n}",
"func (mp *MysqlProtocolImpl) makeHandshakeV10Payload() []byte {\n\tvar data = make([]byte, 256)\n\tvar pos = 0\n\t//int<1> protocol version\n\tpos = mp.io.WriteUint8(data, pos, clientProtocolVersion)\n\n\t//string[NUL] server version\n\tpos = mp.writeStringNUL(data, pos, serverVersion)\n\n\t//int<4> connection id\n\tpos = mp.io.WriteUint32(data, pos, mp.connectionID)\n\n\t//string[8] auth-plugin-data-part-1\n\tpos = mp.writeCountOfBytes(data, pos, mp.salt[0:8])\n\n\t//int<1> filler 0\n\tpos = mp.io.WriteUint8(data, pos, 0)\n\n\t//int<2> capabilities flags (lower 2 bytes)\n\tpos = mp.io.WriteUint16(data, pos, uint16(DefaultCapability&0xFFFF))\n\n\t//int<1> character set\n\tpos = mp.io.WriteUint8(data, pos, utf8mb4BinCollationID)\n\n\t//int<2> status flags\n\tpos = mp.io.WriteUint16(data, pos, DefaultClientConnStatus)\n\n\t//int<2> capabilities flags (upper 2 bytes)\n\tpos = mp.io.WriteUint16(data, pos, uint16((DefaultCapability>>16)&0xFFFF))\n\n\tif (DefaultCapability & CLIENT_PLUGIN_AUTH) != 0 {\n\t\t//int<1> length of auth-plugin-data\n\t\t//set 21 always\n\t\tpos = mp.io.WriteUint8(data, pos, 21)\n\t} else {\n\t\t//int<1> [00]\n\t\t//set 0 always\n\t\tpos = mp.io.WriteUint8(data, pos, 0)\n\t}\n\n\t//string[10] reserved (all [00])\n\tpos = mp.writeZeros(data, pos, 10)\n\n\tif (DefaultCapability & CLIENT_SECURE_CONNECTION) != 0 {\n\t\t//string[$len] auth-plugin-data-part-2 ($len=MAX(13, length of auth-plugin-data - 8))\n\t\tpos = mp.writeCountOfBytes(data, pos, mp.salt[8:])\n\t\tpos = mp.io.WriteUint8(data, pos, 0)\n\t}\n\n\tif (DefaultCapability & CLIENT_PLUGIN_AUTH) != 0 {\n\t\t//string[NUL] auth-plugin name\n\t\tpos = mp.writeStringNUL(data, pos, AuthNativePassword)\n\t}\n\n\treturn data[:pos]\n}",
"func validateNewUFA(who string, payload string) string {\r\n\r\n\t//As of now I am checking if who is of proper role\r\n\tvar validationMessage bytes.Buffer\r\n\tvar ufaDetails map[string]string\r\n\r\n\tlogger.Info(\"validateNewUFA\")\r\n\tif who == \"SELLER\" || who == \"BUYER\" {\r\n\t\tjson.Unmarshal([]byte(payload), &ufaDetails)\r\n\t\t//Now check individual fields\r\n\t\tnetChargeStr := ufaDetails[\"netCharge\"]\r\n\t\tfmt.Println(\"netcharge is :\" + netChargeStr)\r\n\t\ttolerenceStr := ufaDetails[\"chargTolrence\"]\r\n\t\tnetCharge := validateNumber(netChargeStr)\r\n\t\tif netCharge <= 0.0 {\r\n\t\t\tvalidationMessage.WriteString(\"\\nInvalid net charge\")\r\n\t\t}\r\n\t\ttolerence := validateNumber(tolerenceStr)\r\n\t\tif tolerence < 0.0 || tolerence > 10.0 {\r\n\t\t\tvalidationMessage.WriteString(\"\\nTolerence is out of range. Should be between 0 and 10\")\r\n\t\t}\r\n\r\n\t} else {\r\n\t\tvalidationMessage.WriteString(\"\\nUser is not authorized to create a UFA\")\r\n\t}\r\n\tlogger.Info(\"Validation messagge \" + validationMessage.String())\r\n\treturn validationMessage.String()\r\n}",
"func (vc *vncConn) login() bool {\n\t/* read ProtocolVersion packet */\n\terr := vc.read()\n\tif err != nil {\n\t\tif err.Error() == \"EOF\" {\n\t\t\tvc.WriteError(\"connection refused\")\n\t\t} else {\n\t\t\tvc.WriteError(\"failed to read protocol version: %s\", err)\n\t\t}\n\t\treturn false\n\t}\n\n\t/* some servers will send a \"too many security failures\" or\n\t \"to many authentication failures\" message if we failed too many times */\n\tstr := string(vc.message[:vc.length])\n\tif strings.Contains(str, \"failure\") {\n\t\tvc.WriteError(\"connection refused: %s\", str)\n\t\treturn false\n\t}\n\n\t/* handshake format: RFB 003.007\\n\n\t server may send handshake packet appended with additional information (RealVNC 3.3) */\n\tif vc.length < 12 || !strings.HasPrefix(str, \"RFB \") || str[7] != '.' || str[11] != '\\n' {\n\t\tvc.WriteError(\"invalid packet: %s\", str)\n\t\treturn false\n\t}\n\n\t/* parse major and minor versions */\n\tmajor := (int(vc.message[4])-48)*100 + (int(vc.message[5])-48)*10 + (int(vc.message[6]) - 48)\n\tminor := (int(vc.message[8])-48)*100 + (int(vc.message[9])-48)*10 + (int(vc.message[10]) - 48)\n\n\t/* The only published protocol versions at this time are 3.3, 3.7, and 3.8. */\n\tif major < 3 || major > 5 || minor < 0 {\n\t\tvc.WriteError(\"invalid VNC version: %d.%d\", major, minor)\n\t\treturn false\n\t}\n\n\t/* send ProtocolVersion packet */\n\tif major == 3 && minor == 7 {\n\t\t/* version 3.7 */\n\t\terr = vc.write([]byte(\"RFB 003.007\\n\"))\n\t\tif err != nil {\n\t\t\tvc.WriteError(\"failed to send protocol version: %s\", err)\n\t\t\treturn false\n\t\t}\n\t\treturn vc.login38()\n\n\t} else if major == 3 && minor != 8 && minor != 889 {\n\t\t/* general version 3.x */\n\t\terr = vc.write([]byte(\"RFB 003.003\\n\"))\n\t\tif err != nil {\n\t\t\tvc.WriteError(\"failed to send protocol version: %s\", err)\n\t\t\treturn false\n\t\t}\n\t\treturn vc.login33()\n\n\t} else {\n\t\t/* version 3.8, 3.889, 4.x, 5.x */\n\t\terr = vc.write([]byte(\"RFB 003.008\\n\"))\n\t\t// err = vc.write(vc.message[:12]) /* send back the same version */\n\t\tif err != nil {\n\t\t\tvc.WriteError(\"failed to send protocol version: %s\", err)\n\t\t\treturn false\n\t\t}\n\t\treturn vc.login38()\n\t}\n}",
"func TestMalformedPacket(t *testing.T) {\n\t// copied as bytes from Wireshark, then modified the RelayMessage option length\n\tbytes := []byte{\n\t\t0x0c, 0x00, 0x24, 0x01, 0xdb, 0x00, 0x30, 0x10, 0xb0, 0x8a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t0x00, 0x0a, 0xfe, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x0b, 0xab, 0xff, 0xfe, 0x8a,\n\t\t0x6d, 0xf2, 0x00, 0x09, 0x00, 0x50 /*was 0x32*/, 0x01, 0x8d, 0x3e, 0x24, 0x00, 0x01, 0x00, 0x0e, 0x00, 0x01,\n\t\t0x00, 0x01, 0x0c, 0x71, 0x3d, 0x0e, 0x00, 0x0b, 0xab, 0x8a, 0x6d, 0xf2, 0x00, 0x08, 0x00, 0x02,\n\t\t0x00, 0x00, 0x00, 0x03, 0x00, 0x0c, 0xee, 0xbf, 0xfb, 0x6e, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,\n\t\t0xff, 0xff, 0x00, 0x06, 0x00, 0x02, 0x00, 0x17, 0x00, 0x25, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x09,\n\t\t0x00, 0x03, 0x08, 0x00, 0xf0, 0x7f, 0x06, 0xd6, 0x4c, 0x3c, 0x00, 0x12, 0x00, 0x04, 0x09, 0x01,\n\t\t0x08, 0x5a,\n\t}\n\tpacket := Packet6(bytes)\n\t_, err := packet.dhcp6message()\n\tif err == nil {\n\t\tt.Fatalf(\"Should be unable to extract dhcp6message, but did not fail\")\n\t}\n}",
"func validateGenerateSIPAuthVectorWithRandInputs(rand []byte, key []byte, opc []byte, sqn uint64) error {\n\tif len(rand) != RandChallengeBytes {\n\t\treturn fmt.Errorf(\"incorrect rand size. Expected %v bytes, but got %v bytes\", RandChallengeBytes, len(rand))\n\t}\n\tif len(key) != ExpectedKeyBytes {\n\t\treturn fmt.Errorf(\"incorrect key size. Expected %v bytes, but got %v bytes\", ExpectedKeyBytes, len(key))\n\t}\n\tif len(opc) != ExpectedOpcBytes {\n\t\treturn fmt.Errorf(\"incorrect opc size. Expected %v bytes, but got %v bytes\", ExpectedOpcBytes, len(opc))\n\t}\n\tif sqn > maxSqn {\n\t\treturn fmt.Errorf(\"sequence number too large, expected a number which can fit in 48 bits. Got: %v\", sqn)\n\t}\n\treturn nil\n}",
"func validateTokenForUpdating(tokenObj token.StructToken) (string, bool) {\n\n\tvar errorfound string\n\t//validate initiator address if exist in account data\n\taccountobj := account.GetAccountByAccountPubicKey(tokenObj.InitiatorAddress)\n\tif accountobj.AccountPublicKey == \"\" {\n\t\terrorfound = \"please enter valid initiator address (Public key)\"\n\t\treturn errorfound, false\n\t}\n\tif accountobj.AccountPassword != tokenObj.Password {\n\t\terrorfound = \"The given password is incorrect.\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens Total Supply less than or equal zero\n\tif tokenObj.TokensTotalSupply < 1 {\n\t\terrorfound = \"please enter Tokens Total Supply more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate Tokens value less than or equal zero\n\tif tokenObj.TokenValue <= 0.0 {\n\t\terrorfound = \"please enter Tokens value more than zero\"\n\t\treturn errorfound, false\n\t}\n\t//validate token precision from 0 to 5\n\tif tokenObj.Precision < 0 || tokenObj.Precision > 5 {\n\t\terrorfound = \"please enter Precision range from 0 to 5 \"\n\t\treturn errorfound, false\n\t}\n\n\t//validate Tokens TokenType is mandatory public or private\n\tif tokenObj.TokenType == \"public\" || tokenObj.TokenType == \"private\" {\n\t\t// check type token is public, optianal enter contact ID\n\t\tif tokenObj.TokenType == \"public\" {\n\t\t\t// validate ContractID if empty or ==60\n\t\t\tif len(tokenObj.ContractID) < 4 || len(tokenObj.ContractID) > 60 {\n\t\t\t\terrorfound = \"enter ContractID must be more than 4 character and less than or equal 60 characters\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t\t// check type token is Private , optianal enter pentential PK ,enter the potential users public keys which can use this token\n\t\taccountList := accountdb.GetAllAccounts()\n\t\tif tokenObj.TokenType == \"private\" {\n\t\t\t//enter pentential PK which can use this token\n\t\t\tif len(tokenObj.UserPublicKey) != 0 {\n\t\t\t\tfor _, pk := range tokenObj.UserPublicKey {\n\t\t\t\t\tif pk == tokenObj.InitiatorAddress {\n\t\t\t\t\t\terrorfound = \"user create token can't be in user public key \"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t\tif !containspk(accountList, pk) {\n\t\t\t\t\t\terrorfound = \"this public key is not associated with any account\"\n\t\t\t\t\t\treturn errorfound, false\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\terrorfound = \"enter the potential users public keys which can use this token\"\n\t\t\t\treturn errorfound, false\n\t\t\t}\n\t\t}\n\t} else {\n\t\terrorfound = \"please enter TokenType is public or private\"\n\t\treturn errorfound, false\n\t}\n\n\treturn \"\", true\n}",
"func validateNewUFA(who string, payload string) string {\n\n\t//As of now I am checking if who is of proper role\n\tvar validationMessage bytes.Buffer\n\tvar ufaDetails interface{}\n\n\tlogger.Info(\"validateNewUFA\")\n\tif who == \"SELLER\" || who == \"BUYER\" {\n\t\tlogger.Info(\"validateNewUFA WHO\")\n\n\t\tjson.Unmarshal([]byte(payload), &ufaDetails)\n\t\t//Now check individual fields\n\t\tufaRecordMap := ufaDetails.(map[string]interface{})\n\t\tnetChargeStr := getSafeString(ufaRecordMap[\"netCharge\"])\n\t\ttolerenceStr := getSafeString(ufaRecordMap[\"chargTolrence\"])\n\t\tnetCharge := validateNumber(netChargeStr)\n\t\tif netCharge <= 0.0 {\n\t\t\tvalidationMessage.WriteString(\"\\nInvalid net charge\")\n\t\t}\n\t\ttolerence := validateNumber(tolerenceStr)\n\t\tif tolerence < 0.0 || tolerence > 10.0 {\n\t\t\tvalidationMessage.WriteString(\"\\nTolerence is out of range. Should be between 0 and 10\")\n\t\t}\n\n\t} else {\n\t\tvalidationMessage.WriteString(\"\\nUser is not authorized to create a UFA\")\n\t}\n\tlogger.Info(\"Validation messagge \" + validationMessage.String())\n\treturn validationMessage.String()\n}",
"func (mp *MysqlProtocolImpl) analyseHandshakeResponse41(data []byte) (bool, response41, error) {\n\tvar pos = 0\n\tvar ok bool\n\tvar info response41\n\n\t//int<4> capabilities flags of the client, CLIENT_PROTOCOL_41 always set\n\tinfo.capabilities, pos, ok = mp.io.ReadUint32(data, pos)\n\tif !ok {\n\t\treturn false, info, fmt.Errorf(\"get capabilities failed\")\n\t}\n\n\tif (info.capabilities & CLIENT_PROTOCOL_41) == 0 {\n\t\treturn false, info, fmt.Errorf(\"capabilities does not have protocol 41\")\n\t}\n\n\t//int<4> max-packet size\n\t//max size of a command packet that the client wants to send to the server\n\tinfo.maxPacketSize, pos, ok = mp.io.ReadUint32(data, pos)\n\tif !ok {\n\t\treturn false, info, fmt.Errorf(\"get max packet size failed\")\n\t}\n\n\t//int<1> character set\n\t//connection's default character set\n\tinfo.collationID, pos, ok = mp.io.ReadUint8(data, pos)\n\tif !ok {\n\t\treturn false, info, fmt.Errorf(\"get character set failed\")\n\t}\n\n\t//string[23] reserved (all [0])\n\t//just skip it\n\tpos += 23\n\n\t//string[NUL] username\n\tinfo.username, pos, ok = mp.readStringNUL(data, pos)\n\tif !ok {\n\t\treturn false, info, fmt.Errorf(\"get username failed\")\n\t}\n\n\t/*\n\t\tif capabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA {\n\t\t\tlenenc-int length of auth-response\n\t\t\tstring[n] auth-response\n\t\t} else if capabilities & CLIENT_SECURE_CONNECTION {\n\t\t\tint<1> length of auth-response\n\t\t\tstring[n] auth-response\n\t\t} else {\n\t\t\tstring[NUL] auth-response\n\t\t}\n\t*/\n\tif (info.capabilities & CLIENT_PLUGIN_AUTH_LENENC_CLIENT_DATA) != 0 {\n\t\tvar l uint64\n\t\tl, pos, ok = mp.readIntLenEnc(data, pos)\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get length of auth-response failed\")\n\t\t}\n\t\tinfo.authResponse, pos, ok = mp.readCountOfBytes(data, pos, int(l))\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get auth-response failed\")\n\t\t}\n\t} else if (info.capabilities & CLIENT_SECURE_CONNECTION) != 0 {\n\t\tvar l uint8\n\t\tl, pos, ok = mp.io.ReadUint8(data, pos)\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get length of auth-response failed\")\n\t\t}\n\t\tinfo.authResponse, pos, ok = mp.readCountOfBytes(data, pos, int(l))\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get auth-response failed\")\n\t\t}\n\t} else {\n\t\tvar auth string\n\t\tauth, pos, ok = mp.readStringNUL(data, pos)\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get auth-response failed\")\n\t\t}\n\t\tinfo.authResponse = []byte(auth)\n\t}\n\n\tif (info.capabilities & CLIENT_CONNECT_WITH_DB) != 0 {\n\t\tinfo.database, pos, ok = mp.readStringNUL(data, pos)\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get database failed\")\n\t\t}\n\t}\n\n\tif (info.capabilities & CLIENT_PLUGIN_AUTH) != 0 {\n\t\tinfo.clientPluginName, pos, ok = mp.readStringNUL(data, pos)\n\t\tif !ok {\n\t\t\treturn false, info, fmt.Errorf(\"get auth plugin name failed\")\n\t\t}\n\n\t\t//to switch authenticate method\n\t\tif info.clientPluginName != AuthNativePassword {\n\t\t\tvar err error\n\t\t\tif info.authResponse, err = mp.negotiateAuthenticationMethod(); err != nil {\n\t\t\t\treturn false, info, fmt.Errorf(\"negotiate authentication method failed. error:%v\", err)\n\t\t\t}\n\t\t\tinfo.clientPluginName = AuthNativePassword\n\t\t}\n\t}\n\n\t//drop client connection attributes\n\treturn true, info, nil\n}",
"func TestCV12(t *testing.T) {\n\tstatedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))\n\tmsg := createValidator()\n\t// security contact length: 140 characters\n\tmsg.SecurityContact = \"Helloiwfhwifbwfbcerghveugbviuscbhwiefbcusidbcifwefhgciwefherhbfiwuehfciwiuebfcuyiewfhwieufwiweifhcwefhwefhwidsffevjnononwondqmeofniowfndjowe\"\n\tstatedb.AddBalance(msg.ValidatorAddress, tenK)\n\tif _, err := VerifyAndCreateValidatorFromMsg(\n\t\tstatedb, postStakingEpoch, big.NewInt(0), msg,\n\t); err != nil {\n\t\tt.Error(\"expected\", nil, \"got\", err)\n\t}\n}",
"func (c *Conn) writeInitHandshake() error {\n\n data := make([]byte, 4, 128)\n\n // 1 byte 协议版本号\n\n data = append(data, 10)\n\n // n bytes 服务版本号[00]\n\n data = append(data, constant.ServerVersion...)\n data = append(data, 0)\n\n // 4 bytes 线程id\n data = append(data, byte(c.connectionId), byte(c.connectionId>>8), byte(c.connectionId>>16), byte(c.connectionId>>24) )\n\n // 8 bytes 随机数\n\n data = append(data, c.salt[0:8]...)\n\n // 1 bytes 填充值 0x00\n data = append(data, 0)\n\n\n // 2 bytes 服务器权能标志\n data = append(data, byte(DEFAULT_CAPABILITY), byte(DEFAULT_CAPABILITY>>8))\n\n // 1 bytes 字符编码\n data = append(data, uint8(DEFAULT_COLLATION_ID))\n\n // 2 bytes 服务器状态\n data = append(data, byte(c.status), byte(c.status>>8))\n\n // 2 bytes 服务器权能标志(高16位)\n data = append(data, byte(DEFAULT_CAPABILITY>>16), byte(DEFAULT_COLLATION_ID>>24))\n\n // 1 bytes 挑战长度\n data = append(data, 0x15)\n\n // 10 bytes 填充数据\n data = append(data, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)\n\n // n bytes 挑战随机数\n data = append(data, c.salt[8:]...)\n\n // 1 byte 结尾0x00\n data = append(data,0)\n\n return c.pkg.WritePacket(data)\n\n}",
"func validateGenerateEutranVectorInputs(key []byte, opc []byte, sqn uint64, plmn []byte) error {\n\tif err := validateGenerateSIPAuthVectorInputs(key, opc, sqn); err != nil {\n\t\treturn err\n\t}\n\tif len(plmn) != ExpectedPlmnBytes {\n\t\treturn fmt.Errorf(\"incorrect plmn size. Expected 3 bytes, but got %v bytes\", len(plmn))\n\t}\n\treturn nil\n}",
"func TestHandshake66(t *testing.T) { testHandshake(t, ETH66) }",
"func (p *Flex) readDataAndCheckPaddingBytes(cnt int) (ok bool) {\n\tb := make([]byte, cnt+3+8) // max 3 more plus head plus possible long count\n\tcopy(b, p.IBuf)\n\tif cnt > 4 {\n\t\tb = append(b[0:4], b[8:]...) // remove long count in copy\n\t}\n\ttt := strings.TrimRight(p.upperCaseTriceType, \"I\")\n\tswitch tt { // for trice* too {\n\tcase \"TRICE0\":\n\t\treturn true\n\tcase \"TRICE32_4\", \"TRICE64_2\":\n\t\tp.d3 = p.ReadU32(b[16:20])\n\t\tfallthrough\n\tcase \"TRICE32_3\":\n\t\tp.d2 = p.ReadU32(b[12:16])\n\t\tfallthrough\n\tcase \"TRICE8_8\", \"TRICE16_4\", \"TRICE32_2\", \"TRICE64_1\":\n\t\tp.d1 = p.ReadU32(b[8:12])\n\t\tfallthrough\n\tcase \"TRICE8_4\", \"TRICE16_2\", \"TRICE32_1\":\n\t\tp.d0 = p.ReadU32(b[4:8])\n\t\treturn true // no padding bytes\n\tcase \"TRICE_S\":\n\t\tx := 3 & cnt\n\t\tswitch x {\n\t\tcase 0:\n\t\t\treturn true // no padding bytes\n\t\tcase 3:\n\t\t\tok = 0 == b[4+cnt]\n\t\tcase 2:\n\t\t\tok = 0 == b[4+cnt] && 0 == b[1+4+cnt]\n\t\tcase 1:\n\t\t\tok = 0 == b[4+cnt] && 0 == b[1+4+cnt] && 0 == b[2+4+cnt]\n\t\t}\n\tdefault:\n\t\tp.d0 = p.ReadU32(b[4:8])\n\t\tswitch tt {\n\t\tcase \"TRICE8_1\":\n\t\t\tok = p.d0 < (1 << 8)\n\t\tcase \"TRICE8_2\", \"TRICE16_1\":\n\t\t\tok = p.d0 < (1 << 16)\n\t\tcase \"TRICE8_3\":\n\t\t\tok = p.d0 < (1 << 24)\n\t\tdefault:\n\t\t\tp.d1 = p.ReadU32(b[8:12])\n\t\t\tswitch tt {\n\t\t\tcase \"TRICE8_5\":\n\t\t\t\tok = p.d1 < (1 << 8)\n\t\t\tcase \"TRICE8_6\", \"TRICE16_3\":\n\t\t\t\tok = p.d1 < (1 << 16)\n\t\t\tcase \"TRICE8_7\":\n\t\t\t\tok = p.d1 < (1 << 24)\n\t\t\t}\n\t\t}\n\t}\n\tif true == ok {\n\t\treturn\n\t}\n\treturn false\n}",
"func TestCV11(t *testing.T) {\n\tstatedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))\n\tmsg := createValidator()\n\t// website length: 140 characters\n\tmsg.Website = \"Helloiwfhwifbwfbcerghveugbviuscbhwiefbcusidbcifwefhgciwefherhbfiwuehfciwiuebfcuyiewfhwieufwiweifhcwefhwefhwidsffevjnononwondqmeofniowfndjowe\"\n\tstatedb.AddBalance(msg.ValidatorAddress, tenK)\n\tif _, err := VerifyAndCreateValidatorFromMsg(\n\t\tstatedb, postStakingEpoch, big.NewInt(0), msg,\n\t); err != nil {\n\t\tt.Error(\"expected\", nil, \"got\", err)\n\t}\n}",
"func onHandshake(data []byte) (err error) {\n\tif !(bytes.Equal(handshakePrefix[:20], data[:20]) && data[25]&0x10 != 0) {\n\t\terr = errors.New(\"invalid handshake response\")\n\t}\n\treturn\n}",
"func (c *Connection) readInitPacket() error {\n\tvar packetHeader *PacketHeader\n\tvar err error\n\n\tpacketHeader, err = ReadPacketHeader(c.reader)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif packetHeader.Seq != 0 {\n\t\t// The sequence number of the initial packet must be a zero.\n\t\treturn errors.New(\"Unexpected Sequence Number\")\n\t}\n\n\tspew.Printf(\"=== packetHeader\\n\")\n\tspew.Dump(packetHeader)\n\n\t// ProtocolVersion [1 byte]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ProtocolVersion)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ProtocolVersion\\n\")\n\tspew.Dump(c.ProtocolVersion)\n\n\t// ServerVersion [null terminated string]\n\tc.ServerVersion, err = c.reader.ReadString('\\x00')\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ServerVersion\\n\")\n\tspew.Dump(c.ServerVersion)\n\n\t// ConnectionID [4 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ConnectionID)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ConnectionID\\n\")\n\tspew.Dump(c.ConnectionID)\n\n\t// ScramblePart1 [8 bytes]\n\tc.ScramblePart1 = make([]byte, 8)\n\n\terr = ReadPacket(c.reader, c.ScramblePart1[0:8])\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ScramblePart1\\n\")\n\tspew.Dump(c.ScramblePart1)\n\n\t// Reserved byte [1 byte]\n\tIgnoreBytes(c.reader, 1)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerCapabilitiesPart1 (lower 2 bytes) [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerCapabilitiesPart1)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerDefaultCollation [1 byte]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerDefaultCollation)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// StatusFlags [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.StatusFlags)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ServerCapabilitiesPart2 (upper 2 bytes) [2 bytes]\n\terr = binary.Read(c.reader, binary.LittleEndian, &c.ServerCapabilitiesPart2)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// LenOfScramblePart2 [1 byte]\n\t//err = binary.Read(c.reader, binary.LittleEndian, &c.LenOfScramblePart2)\n\n\t//if err != nil {\n\t//\treturn err\n\t//}\n\n\t//spew.Dump(c.LenOfScramblePart2)\n\n\t// PLUGIN_AUTH [1 byte]\n\t// Filler [6 bytes]\n\t// Filler [4 bytes]\n\tIgnoreBytes(c.reader, 1+6+4)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// ScramblePart2 [12 bytes]\n\t// The web documentation is ambiguous about the length.\n\t// Reference:\n\t// https://github.com/go-sql-driver/mysql/blob/master/packets.go\n\tc.ScramblePart2 = make([]byte, 12)\n\n\terr = ReadPacket(c.reader, c.ScramblePart2[0:12])\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== ScramblePart2\\n\")\n\tspew.Dump(c.ScramblePart2)\n\n\t// ScramblePart2 0x00\n\tIgnoreBytes(c.reader, 1)\n\n\t// AuthenticationPluginName [null terminated string]\n\tc.AuthenticationPluginName, err = c.reader.ReadString('\\x00')\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tspew.Printf(\"=== AuthenticationPluginName\\n\")\n\tspew.Dump(c.AuthenticationPluginName)\n\tspew.Dump([]byte(c.AuthenticationPluginName))\n\n\t//\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
decode converts byte array to string and returns it.
|
func decode(array []byte) string {
var tmp string
for _, elem := range array {
tmp += strconv.Itoa(int(elem))
}
return tmp
}
|
[
"func ToString(bs []byte) (s string)",
"func (enc *Encoding) DecodeString(s string) ([]byte, error) {}",
"func EncodingDecodeString(enc *base64.Encoding, s string) ([]byte, error)",
"func StringBytes(b []byte) string { return *(*string)(Pointer(&b)) }",
"func (n Encoding) Decode(s *string) string {\n\tif s == nil {\n\t\treturn string(n)\n\t}\n\treturn *s\n}",
"func (d *Decoder) Decode(input []byte) ([]byte, Encoding) {\n\tif len(input) == 0 {\n\t\treturn []byte{}, None\n\t}\n\n\tunmarshalled := &protodec.Empty{}\n\n\tif d.proto {\n\t\tif err := proto.Unmarshal(input, unmarshalled); err == nil {\n\t\t\t// TODO: remove control characters (unfortunately, they are all valid strings here)\n\t\t\treturn []byte(unmarshalled.String()), Proto\n\t\t}\n\t}\n\n\tif d.bitDec {\n\t\tbyteIn := strings.Trim(string(input), \"[]\") // [32 87 111 114 108 100] -> 32 87 111 114 108 100\n\n\t\tif b, err := Base2AsBytes(byteIn); err == nil {\n\t\t\treturn b, Bit\n\t\t}\n\t}\n\n\t// byte before hex, hex might contains letters, which are not valid in byte dec\n\tif d.byteDec {\n\t\tbyteIn := strings.Trim(string(input), \"[]\") // [32 87 111 114 108 100] -> 32 87 111 114 108 100\n\n\t\tif b, err := Base10AsBytes(byteIn); err == nil {\n\t\t\treturn b, Byte\n\t\t}\n\t}\n\n\t// hex after byte\n\tif d.hex {\n\t\thexIn := strings.TrimSpace(string(input)) // e.g. new line\n\t\thexIn = strings.TrimPrefix(hexIn, \"0x\") // hex prefix\n\t\thexIn = strings.Replace(hexIn, \" \", \"\", -1) // bd b2 3d bc 20 e2 8c 98 -> bdb23dbc20e28c98\n\n\t\tif b, err := hex.DecodeString(hexIn); err == nil {\n\t\t\treturn b, Hex\n\t\t}\n\t}\n\n\t// TODO: many false-positives. Decodes it when no base64 was given.\n\t// Keep it as one of the last decodings.\n\tif d.base64 {\n\t\tif b, err := base64.StdEncoding.DecodeString(strings.TrimSpace(string(input))); err == nil {\n\t\t\treturn b, Base64\n\t\t}\n\t}\n\n\treturn input, None\n}",
"func BytesToString(b []byte) string { return *(*string)(unsafe.Pointer(&b)) }",
"func convertBytesToString(b []byte) string {\n\treturn *(*string)(unsafe.Pointer(&b))\n}",
"func Decode(value []byte) ([]byte, error) {\n var length int = len(value)\n decoded := make([]byte, base64.URLEncoding.DecodedLen(length))\n\n n, err := base64.URLEncoding.Decode(decoded, value)\n if err != nil {\n return nil, err\n }\n return decoded[:n], nil\n}",
"func String(b []byte) string {\n\treturn string(b)\n}",
"func ByteArr2Str(p []byte) string {\n\tfor i := 0; i < len(p); i++ {\n\t\tif p[i] == 0 {\n\t\t\treturn string(p[0:i])\n\t\t}\n\t}\n\treturn string(p)\n}",
"func ByteToString(b *[]byte) string {\n\tresult := *b\n\treturn string(result[:])\n}",
"func decodeSimpleString(r BytesReader) (interface{}, error) {\n\tv, err := r.ReadBytes('\\r')\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// Presume next byte was \\n\n\t_, err = r.ReadByte()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn string(v[:len(v)-1]), nil\n}",
"func Decode(src []byte) (dst [10]byte)",
"func ByteToStr(inputBytes []byte) string {\r\n\treturn string(inputBytes[:])\r\n}",
"func decode(k *KeyValue) {\n\tif k.Encoding == \"binary\" {\n\t\tdecoded, err := base64.StdEncoding.DecodeString(k.Data)\n\t\tif err != nil {\n\t\t\tlog.Println(\"Error decoding base64 key/value\")\n\t\t}\n\t\tk.Data = string(decoded)\n\t}\n}",
"func base64Decode(b string) string {\n\tdata, err := base64.StdEncoding.DecodeString(b)\n\tif err != nil {\n\t\treturn string(b)\n\t}\n\treturn string(data)\n}",
"func DecodeString(toDecode string) ([]byte, error) {\n\treturn base64.RawURLEncoding.DecodeString(toDecode)\n}",
"func decodeByteSlice(s *Stream, val reflect.Value) error {\n\t// b = byte slice contained string content\n\tb, err := s.Bytes()\n\tif err != nil {\n\t\treturn wrapStreamError(err, val.Type())\n\t}\n\tval.SetBytes(b)\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
overrideFile is for when the srv is udpatning lang files
|
func overrideFile(filename, newcontent string) {
file, fileErr := os.Create(filename) //open given file
if fileErr != nil {
fmt.Println(fileErr)
}
file.WriteString(newcontent) //write the new content to the file
file.Close()
return
}
|
[
"func updateFile(connection net.Conn) {\n\tfmt.Println(\"Updating file...\")\n\tlang := make([]byte, 10)\n\tvar content string //content for the new file\n\t\n\tconnection.Read(lang) //read what lang file to change\n\n\t\n\t\n\ttmp := make([]byte, 255) //tmp for holdning the content from the srv\n\tfor {\n\t\tread,_ := connection.Read(tmp) //reads what the srv wants to update the file with\n\t\tif tmp[read-1] == 4 { //the update from the srv will end will 4 ascii = end of transmission\n\t\t\tbreak\n\t\t}\n\t\tcontent += string(tmp) //store the content of the file\n\t}\n\t\n\n\t//search for the input lang and if we can change it.\n\texist := false\n\tfor _,currentlang := range languages {\n\t\tif currentlang == strings.TrimSpace(string(lang)) {\n\t\t\texist = true\n\t\t}\n\t}\n\n\t//the lang did exists! so we append the lang to the global languages list.\n\tif exist == false {\n\t\tlanguages = append(languages, strings.TrimSpace(string(lang)))\n\t}\n\n\t//We will override already existing languages and create a new file if its a totally new language\n\tfilename := strings.TrimSpace(string(lang)) + \".txt\"\n\n\tnewcontent := string(content) //the content from the srv\n\t\n\toverrideFile(filename, newcontent) //overridefile will take all the content and replace all content with the new content\n\n\n\t// check if the clients current lang is the new lang\n\tif custlang == strings.TrimSpace(string(lang)) {\n\t\ttmplines := make([]string,0) //we must replace all old lines from the lang file\n\t\tfile, err := os.Open(filename) //open the file\n\t\tcheck(err)\n\t\t\n\t\tscanner := bufio.NewScanner(file)\n\t\tfor scanner.Scan() {\n\t\t\ttmplines = append(tmplines, scanner.Text())\n\t\t}\n\t\tfile.Close()\n\t\t*(&lines) = tmplines //replace all old lines with the new content \n\t\tcheck(scanner.Err())\n\t}\n\t\n}",
"func (p *Parser) LoadConfigFileOverride(path string) (*File, hcl.Diagnostics) {\n\treturn p.loadConfigFile(path, true)\n}",
"func applyOverrideOverrides(f *flag.FlagSet, k *koanf.Koanf) error {\n\t// Command line overrides config file or config string\n\tif err := k.Load(posflag.Provider(f, \".\", k), nil); err != nil {\n\t\treturn errors.Wrap(err, \"error loading command line config\")\n\t}\n\n\t// Config string overrides any config file\n\tconfigString := k.String(\"conf.string\")\n\tif len(configString) > 0 {\n\t\tif err := k.Load(rawbytes.Provider([]byte(configString)), json.Parser()); err != nil {\n\t\t\treturn errors.Wrap(err, \"error loading config string config\")\n\t\t}\n\n\t\t// Command line overrides config file or config string\n\t\tif err := k.Load(posflag.Provider(f, \".\", k), nil); err != nil {\n\t\t\treturn errors.Wrap(err, \"error loading command line config\")\n\t\t}\n\t}\n\n\t// Environment variables overrides config files or command line options\n\tif err := loadEnvironmentVariables(k); err != nil {\n\t\treturn errors.Wrap(err, \"error loading environment variables\")\n\t}\n\n\treturn nil\n}",
"func (conf blah) SetOverride(key string, def string) {\n\tviper.Set(key, def)\n}",
"func (c *configuration) cmdlineOverride(opts *cliOptions) {\n\t// Populate options that can be provided on both the commandline and config.\n\tif opts.Port > 0 {\n\t\tc.Port = int(opts.Port)\n\t}\n\tif opts.Rank != nil {\n\t\t// global rank parameter should only apply to first I/O service\n\t\tc.Servers[0].Rank = opts.Rank\n\t}\n\tif opts.Insecure {\n\t\tc.TransportConfig.AllowInsecure = true\n\t}\n\t// override each per-server config\n\tfor i := range c.Servers {\n\t\tsrv := &c.Servers[i]\n\n\t\tif opts.MountPath != \"\" {\n\t\t\t// override each per-server config in addition to global value\n\t\t\tc.ScmMountPath = opts.MountPath\n\t\t\tsrv.ScmMount = opts.MountPath\n\t\t} else if srv.ScmMount == \"\" {\n\t\t\t// if scm not specified for server, apply global\n\t\t\tsrv.ScmMount = c.ScmMountPath\n\t\t}\n\t\tif opts.Cores > 0 {\n\t\t\tlog.Debugf(\"-c option deprecated, please use -t instead\")\n\t\t\tsrv.Targets = int(opts.Cores)\n\t\t}\n\t\t// Targets should override Cores if specified in cmdline or\n\t\t// config file.\n\t\tif opts.Targets > 0 {\n\t\t\tsrv.Targets = int(opts.Targets)\n\t\t}\n\t\tif opts.NrXsHelpers != nil {\n\t\t\tsrv.NrXsHelpers = int(*opts.NrXsHelpers)\n\t\t}\n\t\tif opts.FirstCore > 0 {\n\t\t\tsrv.FirstCore = int(opts.FirstCore)\n\t\t}\n\t}\n\n\tif opts.Group != \"\" {\n\t\tc.SystemName = opts.Group\n\t}\n\tif opts.SocketDir != \"\" {\n\t\tc.SocketDir = opts.SocketDir\n\t}\n\tif opts.Modules != nil {\n\t\tc.Modules = *opts.Modules\n\t}\n\tif opts.Attach != nil {\n\t\tc.Attach = *opts.Attach\n\t}\n\tif opts.Map != nil {\n\t\tc.SystemMap = *opts.Map\n\t}\n}",
"func override() {\n\tb, err := ioutil.ReadFile(\"./devconfig.json\")\n\tif err != nil {\n\t\treturn\n\t}\n\n\tvar configVars map[string]string\n\tif err := json.Unmarshal(b, &configVars); err != nil {\n\t\tpanic(err)\n\t}\n\n\tfor k, v := range configVars {\n\t\tos.Setenv(k, v)\n\t}\n}",
"func overrideFile(fileName string, err error, contents []byte, perm os.FileMode, vfn verify.VerifyFn) error {\n\ttimeNano := time.Now().UnixNano()\n\t// write the new contents to a temporary file\n\tnewFileName := fmt.Sprintf(\"%s.tmp%d\", fileName, timeNano)\n\tlog.Printf(\"Writing contents to temporary file %s...\\n\", newFileName)\n\terr = ioutil.WriteFile(newFileName, contents, perm)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to write new file %s, err: %v\\n\", newFileName, err)\n\t\treturn err\n\t}\n\n\t// Sanity check the new file against the existing one\n\tif vfn != nil {\n\t\terr = vfn(fileName, newFileName)\n\t\tif err != nil {\n\t\t\tlog.Printf(\"invalid content: %q, error: %v\", newFileName, err)\n\t\t\treturn err\n\t\t}\n\t}\n\n\t// move the contents of the old file to a backup file\n\tbakFileName := fmt.Sprintf(\"%s.bak%d\", fileName, timeNano)\n\tlog.Printf(\"Renaming original file %s to backup file %s...\\n\", fileName, bakFileName)\n\terr = os.Rename(fileName, bakFileName)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to rename file %s to %s, err: %v\\n\", fileName, bakFileName, err)\n\t\treturn err\n\t}\n\t// move the new contents to the original location\n\tlog.Printf(\"Renaming temporary file %s to requested file %s...\\n\", newFileName, fileName)\n\terr = os.Rename(newFileName, fileName)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to rename file %s to %s, err: %v\\n\", newFileName, fileName, err)\n\t\t// before returning try to restore the original file\n\t\tos.Rename(bakFileName, fileName)\n\t\treturn err\n\t}\n\t// remove the temporary backup file\n\tlog.Printf(\"Removing backup file %s...\\n\", bakFileName)\n\tos.Remove(bakFileName)\n\treturn nil\n}",
"func OverrideLocale(loc *Locale) error {\n\tif err := loc.Check(); err != nil {\n\t\treturn err\n\t}\n\tif _, exists := locales[loc.ISOCode]; !exists {\n\t\treturn fmt.Errorf(\"locale with ISO code %s does not exist\", loc.ISOCode)\n\t}\n\tlocales[loc.ISOCode] = loc\n\tupdateAllLanguageList()\n\treturn nil\n}",
"func FromFileWithOverride(path string) config.Provider {\n\tf1 := config.FromFile(path)\n\tf2 := config.FromFile(path + \".override\")\n\n\treturn func() ([]string, error) {\n\t\td, err := f1()\n\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\td2, err := f2()\n\n\t\t// don't care about .override not existing\n\t\tif err == nil {\n\t\t\td = append(d, d2...)\n\t\t}\n\n\t\treturn d, nil\n\t}\n}",
"func (l *Loader) translateFile(path, file string) error {\n\tl.msgIndex = 0\n\tl.srvIndex = 0\n\tl.enumIndex = 0\n\tl.toGen[path][file] = true\n\tif _, ok := l.allProto[file]; ok {\n\t\treturn nil\n\t}\n\tbpkg := l.bldPkgs[path]\n\tastFiles := l.astPkgs[path]\n\tl.gfile = astFiles[file]\n\tl.pfile = &desc.FileDescriptorProto{\n\t\tSyntax: proto.String(\"proto3\"),\n\t\tName: proto.String(file),\n\t\tPackage: proto.String(bpkg.ImportPath),\n\t\tOptions: &desc.FileOptions{\n\t\t\tGoPackage: proto.String(bpkg.Name),\n\t\t},\n\t}\n\tl.addDoc(l.gfile.Doc, nil, packagePath)\n\tfor _, decl := range l.gfile.Decls {\n\t\tif err := l.translateDecl(decl); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\tl.allProto[file] = l.pfile\n\treturn nil\n}",
"func (p *ProviderHost) UpdateFromFile(path string) (err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbase := new(BaseModel)\n\tif err = yaml.NewDecoder(f).Decode(base); err != nil {\n\t\treturn\n\t}\n\tf.Seek(0, 0)\n\n\tswitch base.Type {\n\n\tcase ProviderLanguage:\n\t\tlang := new(LanguageModel)\n\t\tif err = yaml.NewDecoder(f).Decode(lang); err != nil {\n\t\t\treturn\n\t\t}\n\t\tp.languages[lang.Id] = lang\n\t}\n\n\treturn\n}",
"func (r *TrafficOpsReq) replaceCfgFile(cfg *ConfigFile) (*FileRestartData, error) {\n\tif r.Cfg.ReportOnly ||\n\t\t(r.Cfg.Files != t3cutil.ApplyFilesFlagAll && r.Cfg.Files != t3cutil.ApplyFilesFlagReval) {\n\t\tlog.Infof(\"You elected not to replace %s with the version from Traffic Ops.\\n\", cfg.Name)\n\t\tcfg.ChangeApplied = false\n\t\treturn &FileRestartData{Name: cfg.Name}, nil\n\t}\n\n\ttmpFileName := cfg.Path + configFileTempSuffix\n\tlog.Infof(\"Writing temp file '%s' with file mode: '%#o' \\n\", tmpFileName, cfg.Perm)\n\n\t// write a new file, then move to the real location\n\t// because moving is atomic but writing is not.\n\t// If we just wrote to the real location and the app or OS or anything crashed,\n\t// we'd end up with malformed files.\n\n\tif _, err := util.WriteFileWithOwner(tmpFileName, cfg.Body, &cfg.Uid, &cfg.Gid, cfg.Perm); err != nil {\n\t\treturn &FileRestartData{Name: cfg.Name}, errors.New(\"Failed to write temp config file '\" + tmpFileName + \"': \" + err.Error())\n\t}\n\n\tlog.Infof(\"Copying temp file '%s' to real '%s'\\n\", tmpFileName, cfg.Path)\n\tif err := os.Rename(tmpFileName, cfg.Path); err != nil {\n\t\treturn &FileRestartData{Name: cfg.Name}, errors.New(\"Failed to move temp '\" + tmpFileName + \"' to real '\" + cfg.Path + \"': \" + err.Error())\n\t}\n\tcfg.ChangeApplied = true\n\tr.changedFiles = append(r.changedFiles, cfg.Path)\n\n\tremapConfigReload := cfg.RemapPluginConfig ||\n\t\tcfg.Name == \"remap.config\" ||\n\t\tstrings.HasPrefix(cfg.Name, \"bg_fetch\") ||\n\t\tstrings.HasPrefix(cfg.Name, \"hdr_rw_\") ||\n\t\tstrings.HasPrefix(cfg.Name, \"regex_remap_\") ||\n\t\tstrings.HasPrefix(cfg.Name, \"set_dscp_\") ||\n\t\tstrings.HasPrefix(cfg.Name, \"url_sig_\") ||\n\t\tstrings.HasPrefix(cfg.Name, \"uri_signing\") ||\n\t\tstrings.HasSuffix(cfg.Name, \".lua\")\n\n\ttrafficCtlReload := strings.HasSuffix(cfg.Dir, \"trafficserver\") ||\n\t\tremapConfigReload ||\n\t\tcfg.Name == \"ssl_multicert.config\" ||\n\t\tcfg.Name == \"records.config\" ||\n\t\t(strings.HasSuffix(cfg.Dir, \"ssl\") && strings.HasSuffix(cfg.Name, \".cer\")) ||\n\t\t(strings.HasSuffix(cfg.Dir, \"ssl\") && strings.HasSuffix(cfg.Name, \".key\"))\n\n\ttrafficServerRestart := cfg.Name == \"plugin.config\"\n\tntpdRestart := cfg.Name == \"ntpd.conf\"\n\tsysCtlReload := cfg.Name == \"sysctl.conf\"\n\n\tlog.Debugf(\"Reload state after %s: remap.config: %t reload: %t restart: %t ntpd: %t sysctl: %t\", cfg.Name, remapConfigReload, trafficCtlReload, trafficServerRestart, ntpdRestart, sysCtlReload)\n\n\tlog.Debugf(\"Setting change applied for '%s'\\n\", cfg.Name)\n\treturn &FileRestartData{\n\t\tName: cfg.Name,\n\t\tRestartData: RestartData{\n\t\t\tTrafficCtlReload: trafficCtlReload,\n\t\t\tSysCtlReload: sysCtlReload,\n\t\t\tNtpdRestart: ntpdRestart,\n\t\t\tTrafficServerRestart: trafficServerRestart,\n\t\t\tRemapConfigReload: remapConfigReload,\n\t\t},\n\t}, nil\n}",
"func (g *altsTC) OverrideServerName(serverNameOverride string) error {\n\tg.info.ServerName = serverNameOverride\n\treturn nil\n}",
"func pythonConfigOverrideAction(app *DdevApp) error {\n\tif app.WebserverType == nodeps.WebserverDefault {\n\t\tapp.WebserverType = nodeps.WebserverNginxGunicorn\n\t}\n\tif app.Database == DatabaseDefault {\n\t\tapp.Database.Type = nodeps.Postgres\n\t\tapp.Database.Version = nodeps.Postgres14\n\t}\n\treturn nil\n}",
"func updateUserdataFile(driverOpts *rpcdriver.RPCFlags, machineName, hostname, userdataFlag, osFlag, customInstallScript string) error {\n\tvar userdataContent []byte\n\tvar err error\n\tuserdataFile := driverOpts.String(userdataFlag)\n\tmachineOS := driverOpts.String(osFlag)\n\n\tif userdataFile == \"\" {\n\t\t// Always convert to cloud config if user data is not provided\n\t\tuserdataContent = []byte(\"#cloud-config\")\n\t} else {\n\t\tuserdataContent, err = os.ReadFile(userdataFile)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tcustomScriptContent, err := os.ReadFile(customInstallScript)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Remove the shebang\n\tcustomScriptContent = regexp.MustCompile(`^#!.*\\n`).ReplaceAll(customScriptContent, nil)\n\n\tmodifiedUserdataFile, err := ioutil.TempFile(\"\", \"modified-user-data\")\n\tif err != nil {\n\t\treturn fmt.Errorf(\"[updateUserdataFile] unable to create tempfile [%v]\\nError returned\\n[%v]\", modifiedUserdataFile, err)\n\t}\n\tdefer modifiedUserdataFile.Close()\n\n\tif err := replaceUserdataFile(machineName, machineOS, hostname, userdataContent, customScriptContent, modifiedUserdataFile); err != nil {\n\t\treturn err\n\t}\n\n\tdriverOpts.Values[userdataFlag] = modifiedUserdataFile.Name()\n\n\treturn nil\n}",
"func (e *Engine) handleOverride(o seesaw.Override) {\n\te.overrides[o.Target()] = o\n\te.distributeOverride(o)\n\tif o.State() == seesaw.OverrideDefault {\n\t\tdelete(e.overrides, o.Target())\n\t}\n}",
"func SetLanguageFilePath(path string) string {\n\tlastPath := langFilePath\n\tlangFilePath = path\n\treturn lastPath\n}",
"func (iob *IndexOptionsBuilder) LanguageOverride(languageOverride string) *IndexOptionsBuilder {\n\tiob.document = append(iob.document, bson.E{\"language_override\", languageOverride})\n\treturn iob\n}",
"func (r *TrafficOpsReq) processRemapOverrides(cfg *ConfigFile) error {\n\tfrom := \"\"\n\tnewlines := []string{}\n\tlineCount := 0\n\toverrideCount := 0\n\toverridenCount := 0\n\toverrides := map[string]int{}\n\tdata := cfg.Body\n\n\tif len(data) > 0 {\n\t\tlines := strings.Split(string(data), \"\\n\")\n\t\tfor ii := range lines {\n\t\t\tstr := lines[ii]\n\t\t\tfields := strings.Fields(str)\n\t\t\tif str == \"\" || len(fields) < 2 {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tlineCount++\n\t\t\tfrom = fields[1]\n\n\t\t\t_, ok := overrides[from]\n\t\t\tif ok == true { // check if this line should be overriden\n\t\t\t\tnewstr := \"##OVERRIDDEN## \" + str\n\t\t\t\tnewlines = append(newlines, newstr)\n\t\t\t\toverridenCount++\n\t\t\t} else if fields[0] == \"##OVERRIDE##\" { // check for an override\n\t\t\t\tfrom = fields[2]\n\t\t\t\tnewlines = append(newlines, \"##OVERRIDE##\")\n\t\t\t\t// remove the ##OVERRIDE## comment along with the trailing space\n\t\t\t\tnewstr := strings.TrimPrefix(str, \"##OVERRIDE## \")\n\t\t\t\t// save the remap 'from field' to overrides.\n\t\t\t\toverrides[from] = 1\n\t\t\t\tnewlines = append(newlines, newstr)\n\t\t\t\toverrideCount++\n\t\t\t} else { // no override is necessary\n\t\t\t\tnewlines = append(newlines, str)\n\t\t\t}\n\t\t}\n\t} else {\n\t\treturn errors.New(\"The \" + cfg.Name + \" file is empty, nothing to process.\")\n\t}\n\tif overrideCount > 0 {\n\t\tlog.Infof(\"Overrode %d old remap rule(s) with %d new remap rule(s).\\n\",\n\t\t\toverridenCount, overrideCount)\n\t\tnewdata := strings.Join(newlines, \"\\n\")\n\t\t// strings.Join doesn't add a newline character to\n\t\t// the last element in the array and we need one\n\t\t// when the data is written out to a file.\n\t\tif !strings.HasSuffix(newdata, \"\\n\") {\n\t\t\tnewdata = newdata + \"\\n\"\n\t\t}\n\t\tbody := []byte(newdata)\n\t\tcfg.Body = body\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
update the clients language file
|
func updateFile(connection net.Conn) {
fmt.Println("Updating file...")
lang := make([]byte, 10)
var content string //content for the new file
connection.Read(lang) //read what lang file to change
tmp := make([]byte, 255) //tmp for holdning the content from the srv
for {
read,_ := connection.Read(tmp) //reads what the srv wants to update the file with
if tmp[read-1] == 4 { //the update from the srv will end will 4 ascii = end of transmission
break
}
content += string(tmp) //store the content of the file
}
//search for the input lang and if we can change it.
exist := false
for _,currentlang := range languages {
if currentlang == strings.TrimSpace(string(lang)) {
exist = true
}
}
//the lang did exists! so we append the lang to the global languages list.
if exist == false {
languages = append(languages, strings.TrimSpace(string(lang)))
}
//We will override already existing languages and create a new file if its a totally new language
filename := strings.TrimSpace(string(lang)) + ".txt"
newcontent := string(content) //the content from the srv
overrideFile(filename, newcontent) //overridefile will take all the content and replace all content with the new content
// check if the clients current lang is the new lang
if custlang == strings.TrimSpace(string(lang)) {
tmplines := make([]string,0) //we must replace all old lines from the lang file
file, err := os.Open(filename) //open the file
check(err)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
tmplines = append(tmplines, scanner.Text())
}
file.Close()
*(&lines) = tmplines //replace all old lines with the new content
check(scanner.Err())
}
}
|
[
"func (a *AccdGeneralLanguage) Update(client sophos.ClientInterface, options ...sophos.Option) (err error) {\n\treturn put(client, \"/api/nodes/accd.general.language\", a.Value, options...)\n}",
"func (w *WebadminLanguage) Update(client sophos.ClientInterface, options ...sophos.Option) (err error) {\n\treturn put(client, \"/api/nodes/webadmin.language\", w.Value, options...)\n}",
"func (p *PortalLanguage) Update(client sophos.ClientInterface, options ...sophos.Option) (err error) {\n\treturn put(client, \"/api/nodes/portal.language\", p.Value, options...)\n}",
"func updateLocalizableStrings(project Project, str string) Project {\n\tfor _, lang := range project.Languages { //do it to all project's Localizable.strings file\n\t\tvar path = lang.Path + \"/Localizable.strings\"\n\t\tvar fileContents = readFile(path)\n\t\tif !strings.Contains(fileContents, str) { //if str does not exist in Localizable.strings...\n\t\t\tvar stringToWrite = str + \" = \\\"\\\";\" //equivalent to: \"word\" = \"\";\n\t\t\twriteToFile(path, \"\\n\"+stringToWrite) //write at the end\n\t\t}\n\t}\n\treturn project\n}",
"func openLangJSON(updated interface{}) CustError {\n\tfile, err := ioutil.ReadFile(\"languages.json\")\n\n\t// Failed reading the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to load local file: languages.json\"}\n\t}\n\n\terr = json.Unmarshal(file, &updated)\n\n\t// Failed unmarshaling the file\n\tif err != nil {\n\t\treturn CustError{http.StatusInternalServerError, \"Failed to unmarshal local file: languages.json\"}\n\t}\n\n\t// Nothing bad happened\n\treturn CustError{0, errorStr[0]}\n}",
"func updatePOFiles(moduleDir string, langs []string) {\n\ti18nDir := filepath.Join(moduleDir, \"i18n\")\n\tserver.LoadModuleTranslations(i18nDir, langs)\n\tconf := loader.Config{}\n\tconf.Import(moduleDir)\n\tprogram, err := conf.Load()\n\tif err != nil {\n\t\tlog.Panic(\"Unable to build program\", \"error\", err)\n\t}\n\tpacks := program.InitialPackages()\n\tif len(packs) != 1 {\n\t\tlog.Panic(\"Something has gone wrong, we have more than one package\", \"packs\", packs)\n\t}\n\tmodInfos := []*generate.ModuleInfo{{PackageInfo: *packs[0], ModType: generate.Base}}\n\tmodelsASTData := generate.GetModelsASTDataForModules(modInfos, false)\n\n\tfor _, lang := range langs {\n\t\tmessages := make(map[messageRef]po.Message)\n\t\tfor model, modelASTData := range modelsASTData {\n\t\t\tfor field, fieldASTData := range modelASTData.Fields {\n\t\t\t\tmessages = addDescriptionToMessages(lang, model, field, fieldASTData, messages)\n\t\t\t\tmessages = addHelpToMessages(lang, model, field, fieldASTData, messages)\n\t\t\t\tmessages = addSelectionToMessages(lang, model, field, fieldASTData, messages)\n\t\t\t}\n\t\t}\n\t\tmessages = addResourceItemsToMessages(lang, filepath.Join(moduleDir, \"resources\"), messages)\n\t\tmessages = addCodeToMessages(lang, moduleDir, messages)\n\n\t\tmsgs := make([]po.Message, len(messages))\n\t\ti := 0\n\t\tfor _, m := range messages {\n\t\t\tm.ExtractedComment = strings.TrimSuffix(m.ExtractedComment, \"\\n\")\n\t\t\tmsgs[i] = m\n\t\t\ti += 1\n\t\t}\n\t\tfile := po.File{\n\t\t\tMessages: msgs,\n\t\t\tMimeHeader: po.Header{\n\t\t\t\tLanguage: lang,\n\t\t\t\tContentType: \"text/plain; charset=utf-8\",\n\t\t\t\tContentTransferEncoding: \"8bit\",\n\t\t\t\tMimeVersion: \"1.0\",\n\t\t\t},\n\t\t}\n\t\terr = file.Save(fmt.Sprintf(\"%s/%s.po\", i18nDir, lang))\n\t\tif err != nil {\n\t\t\tlog.Panic(\"Error while saving PO file\", \"error\", err)\n\t\t}\n\t}\n}",
"func (c *Client) SetLanguage(language string) {\n\n}",
"func (this *GenericController) setLangVer() bool {\n\tisNeedRedir := false\n\thasCookie := false\n\n\n\t// 1. Check URL arguments.\n\tpreferredLang := this.GetString(\"preferredLang\", \"\")\n\n\t// 2. Get language information from cookies.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = this.Ctx.GetCookie(\"preferredLang\")\n\t\thasCookie = true\n\t} else {\n\t\tisNeedRedir = true\n\t}\n\n\t// Check again in case someone modify on purpose.\n\tif !i18n.IsExist(preferredLang) {\n\t\tpreferredLang = \"\"\n\t\tisNeedRedir = false\n\t\thasCookie = false\n\t}\n\n\t// 3. Get language information from 'Accept-Language'.\n\tif len(preferredLang) == 0 {\n\t\tal := this.Ctx.Request.Header.Get(\"Accept-Language\")\n\t\tif len(al) > 4 {\n\t\t\tal = al[:5] // Only compare first 5 letters.\n\t\t\tif i18n.IsExist(al) {\n\t\t\t\tpreferredLang = al\n\t\t\t}\n\t\t}\n\t}\n\n\t// 4. Default language is English.\n\tif len(preferredLang) == 0 {\n\t\tpreferredLang = \"ta-LK\"\n\t\tisNeedRedir = false\n\t}\n\n\tcurLang := lang.LangType{\n\t\tLang: preferredLang,\n\t}\n\n\t// Save language information in cookies.\n\tif !hasCookie {\n\t\tthis.Ctx.SetCookie(\"preferredLang\", curLang.Lang, 1<<31-1, \"/\")\n\t}\n\n\trestLangs := make([]*lang.LangType, 0, len(lang.LangTypes)-1)\n\tfor _, v := range lang.LangTypes {\n\t\tif preferredLang != v.Lang {\n\t\t\trestLangs = append(restLangs, v)\n\t\t} else {\n\t\t\tcurLang.Name = v.Name\n\t\t}\n\t}\n\t// Set language properties.\n\tthis.Lang = preferredLang\n\tthis.Data[\"Lang\"] = curLang.Lang\n\tthis.Data[\"CurLang\"] = curLang.Name\n\tthis.Data[\"RestLangs\"] = restLangs\n\treturn isNeedRedir\n}",
"func setLang(lang string) {\n\tif lang == \"pl\" {\n\t\tl = langTexts[\"pl\"]\n\t} else if lang == \"en\" {\n\t\tl = langTexts[\"en\"]\n\t}\n}",
"func (c *config) setClientLanguage(clientLanguage, jsModulePath string) error {\n\tif clientLanguage != \"\" {\n\t\tif clientLanguage != \"go\" && clientLanguage != \"js\" {\n\t\t\treturn fmt.Errorf(\"client-language must be one of \\\"go\\\" or \\\"js\\\"\")\n\t\t}\n\t\tswitch clientLanguage {\n\t\tcase \"go\":\n\t\t\tc.generateGoClient = true\n\t\t\tc.generateJSClient = false\n\t\tcase \"js\":\n\t\t\tc.generateGoClient = false\n\t\t\tc.generateJSClient = true\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"client-language must be one of \\\"go\\\" or \\\"js\\\"\")\n\t\t}\n\t} else {\n\t\tc.generateGoClient = true\n\t\tc.generateJSClient = true\n\t}\n\n\tif c.generateJSClient && jsModulePath == \"\" {\n\t\treturn fmt.Errorf(\"js-path is required\")\n\t}\n\n\treturn nil\n}",
"func (a *Api) refreshLocal(res http.ResponseWriter, req *http.Request, vars map[string]string) {\n\tlog.Println(\"refresh locales files from remote system!\")\n\tsuccess := a.localeManager.DownloadLocales(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif !success {\n\t\tlog.Printf(\"error while retriving locales from localizer service!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\tlocalizer, err := localize.NewI18nLocalizer(path.Join(a.Config.I18nTemplatesPath, \"locales/\"))\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading locales files!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\temailTemplates, err := templates.New(a.Config.I18nTemplatesPath, localizer)\n\tif err != nil {\n\t\tlog.Printf(\"error while reloading templates!\")\n\t\ts := status.NewApiStatus(http.StatusInternalServerError, \"error\")\n\t\ta.sendModelAsResWithStatus(res, s, http.StatusInternalServerError)\n\t\treturn\n\t}\n\ta.templates = emailTemplates\n}",
"func (h *MemHome) Lang(path string) Lang { return h.langs.lang(path) }",
"func (u *GithubGistUpsertOne) UpdateLanguage() *GithubGistUpsertOne {\n\treturn u.Update(func(s *GithubGistUpsert) {\n\t\ts.UpdateLanguage()\n\t})\n}",
"func (p *ProviderHost) UpdateFromFile(path string) (err error) {\n\tf, err := os.Open(path)\n\tif err != nil {\n\t\treturn\n\t}\n\n\tbase := new(BaseModel)\n\tif err = yaml.NewDecoder(f).Decode(base); err != nil {\n\t\treturn\n\t}\n\tf.Seek(0, 0)\n\n\tswitch base.Type {\n\n\tcase ProviderLanguage:\n\t\tlang := new(LanguageModel)\n\t\tif err = yaml.NewDecoder(f).Decode(lang); err != nil {\n\t\t\treturn\n\t\t}\n\t\tp.languages[lang.Id] = lang\n\t}\n\n\treturn\n}",
"func (l *Language) Update(terms []TermTranslation) (CountResult, error) {\n\tvar res UploadResult\n\t// Typecheck translations\n\tfor _, t := range terms {\n\t\tc := t.Translation.Content\n\t\tif _, ok := c.(string); ok {\n\t\t\tcontinue\n\t\t}\n\t\tif _, ok := c.(Plural); ok {\n\t\t\tcontinue\n\t\t}\n\t\treturn res.Translations, ErrTranslationInvalid\n\t}\n\t// Encode and send translations\n\tts, err := json.Marshal(terms)\n\tif err != nil {\n\t\treturn res.Translations, err\n\t}\n\terr = l.post(\"/languages/update\", map[string]string{\"data\": string(ts)}, nil, &res)\n\treturn res.Translations, err\n}",
"func Load() {\n\tf, _ := os.Open(filepath.ToSlash(filepath.Join(model.Conf.StaticRoot, \"i18n\")))\n\tnames, _ := f.Readdirnames(-1)\n\tf.Close()\n\n\tfor _, name := range names {\n\t\tif !util.IsLetter(rune(name[0])) || !strings.HasSuffix(name, \".json\") {\n\t\t\tcontinue\n\t\t}\n\n\t\tloc := name[:strings.LastIndex(name, \".\")]\n\t\tload(loc)\n\t}\n\n\tlogger.Tracef(\"loaded [%d] language configuration files\", len(locales))\n}",
"func (h *HttpDownloadManagerDefaultCharset) Update(client sophos.ClientInterface, options ...sophos.Option) (err error) {\n\treturn put(client, \"/api/nodes/http.download_manager_default_charset\", h.Value, options...)\n}",
"func SetLanguageFilePath(path string) string {\n\tlastPath := langFilePath\n\tlangFilePath = path\n\treturn lastPath\n}",
"func (i *i18n) localize(r *Request) {\n\ti.once.Do(func() {\n\t\tlr, err := filepath.Abs(i.a.LocaleRoot)\n\t\tif err != nil {\n\t\t\ti.a.ERROR(\n\t\t\t\t\"air: failed to get absolute representation \"+\n\t\t\t\t\t\"of locale root\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tlfns, err := filepath.Glob(filepath.Join(lr, \"*.toml\"))\n\t\tif err != nil {\n\t\t\ti.a.ERROR(\n\t\t\t\t\"air: failed to get locale files\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t},\n\t\t\t)\n\n\t\t\treturn\n\t\t}\n\n\t\tls := make(map[string]map[string]string, len(lfns))\n\t\tts := make([]language.Tag, 0, len(lfns))\n\t\tfor _, lfn := range lfns {\n\t\t\tb, err := ioutil.ReadFile(lfn)\n\t\t\tif err != nil {\n\t\t\t\ti.a.ERROR(\n\t\t\t\t\t\"air: failed to read locale file\",\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tl := map[string]string{}\n\t\t\tif err := toml.Unmarshal(b, &l); err != nil {\n\t\t\t\ti.a.ERROR(\n\t\t\t\t\t\"air: failed to unmarshal locale file\",\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tt, err := language.Parse(strings.Replace(\n\t\t\t\tfilepath.Base(lfn),\n\t\t\t\t\".toml\",\n\t\t\t\t\"\",\n\t\t\t\t1,\n\t\t\t))\n\t\t\tif err != nil {\n\t\t\t\ti.a.ERROR(\n\t\t\t\t\t\"air: failed to parse locale\",\n\t\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t\t},\n\t\t\t\t)\n\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tls[t.String()] = l\n\t\t\tts = append(ts, t)\n\t\t}\n\n\t\ti.locales = ls\n\t\ti.matcher = language.NewMatcher(ts)\n\n\t\tif err := i.watcher.Add(lr); err != nil {\n\t\t\ti.a.ERROR(\n\t\t\t\t\"air: failed to watch locale files\",\n\t\t\t\tmap[string]interface{}{\n\t\t\t\t\t\"error\": err.Error(),\n\t\t\t\t},\n\t\t\t)\n\t\t}\n\t})\n\n\tt, _ := language.MatchStrings(i.matcher, r.Header[\"Accept-Language\"]...)\n\tl := i.locales[t.String()]\n\n\tr.localizedString = func(key string) string {\n\t\tif v, ok := l[key]; ok {\n\t\t\treturn v\n\t\t} else if v, ok := i.locales[i.a.LocaleBase][key]; ok {\n\t\t\treturn v\n\t\t}\n\n\t\treturn key\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewArtifactListerOK creates ArtifactListerOK with default headers values
|
func NewArtifactListerOK() *ArtifactListerOK {
return &ArtifactListerOK{}
}
|
[
"func (a *APIDefaults) ArtifactLister(params artifacts.ArtifactListerParams) middleware.Responder {\n\tpaginator := weles.ArtifactPagination{}\n\tif a.PageLimit != 0 {\n\t\tif (params.After != nil) && (params.Before != nil) {\n\t\t\treturn artifacts.NewArtifactListerBadRequest().WithPayload(&weles.ErrResponse{\n\t\t\t\tMessage: weles.ErrBeforeAfterNotAllowed.Error()})\n\t\t}\n\t\tpaginator = setArtifactPaginator(params, a.PageLimit)\n\t}\n\tfilter := setArtifactFilter(params.ArtifactFilterAndSort.Filter)\n\tsorter := setArtifactSorter(params.ArtifactFilterAndSort.Sorter)\n\n\tartifactInfoReceived, listInfo, err := a.Managers.AM.ListArtifact(filter, sorter, paginator)\n\n\tswitch err {\n\tdefault:\n\t\treturn artifacts.NewArtifactListerInternalServerError().WithPayload(\n\t\t\t&weles.ErrResponse{Message: err.Error()})\n\tcase weles.ErrArtifactNotFound:\n\t\treturn artifacts.NewArtifactListerNotFound().WithPayload(\n\t\t\t&weles.ErrResponse{Message: weles.ErrArtifactNotFound.Error()})\n\tcase nil:\n\t}\n\n\tartifactInfoReturned := artifactInfoReceivedToReturn(artifactInfoReceived)\n\n\tif (listInfo.RemainingRecords == 0) || (a.PageLimit == 0) { //last page...\n\t\treturn responderArtifact200(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n\t} //not last page...\n\treturn responderArtifact206(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n}",
"func responderArtifact200(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerOK) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\tresponder = artifacts.NewArtifactListerOK()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tif paginator.ID != 0 { //not the first page\n\t\t// keep in mind that ArtifactPath in paginator is taken from query parameter,\n\t\t// not ArtifactManager\n\t\tif paginator.Forward {\n\t\t\ttmp := artifactInfoReturned[0].ID\n\t\t\tartifactListerURL.Before = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp\n\t\t\t}\n\t\t\tresponder.SetPrevious(artifactListerURL.String())\n\t\t} else {\n\t\t\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\t\t\tartifactListerURL.After = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp2 := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp2\n\t\t\t}\n\t\t\tresponder.SetNext(artifactListerURL.String())\n\t\t}\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func (c helmClient) NewLister(flg flags.ListFlags) (Lister, error) {\n\tenvconfig := config.NewEnvConfig(&flg.GlobalFlags)\n\tactionconfig, err := config.NewActionConfig(envconfig, &flg.GlobalFlags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := action.NewList(actionconfig.Configuration)\n\tlist.AllNamespaces = flg.AllNamespaces\n\tlist.Deployed = flg.Deployed\n\tlist.Failed = flg.Failed\n\tlist.Pending = flg.Pending\n\tlist.Uninstalling = flg.Uninstalling\n\tlist.Uninstalled = flg.Uninstalled\n\n\treturn &lister{\n\t\taction: list,\n\t\tenvSettings: envconfig.EnvSettings,\n\t}, nil\n}",
"func (o *ArtifactListerOK) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerOK {\n\to.Payload = payload\n\treturn o\n}",
"func NewListArtifactsOK() *ListArtifactsOK {\n\treturn &ListArtifactsOK{}\n}",
"func generateListVersionsResponse(bucket, prefix, marker, delimiter, encodingType string, maxKeys int, resp ListObjectsInfo) ListVersionsResponse {\n\tvar versions []ObjectVersion\n\tvar prefixes []CommonPrefix\n\tvar owner = Owner{}\n\tvar data = ListVersionsResponse{}\n\n\towner.ID = globalMinioDefaultOwnerID\n\tfor _, object := range resp.Objects {\n\t\tvar content = ObjectVersion{}\n\t\tif object.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontent.Key = s3EncodeName(object.Name, encodingType)\n\t\tcontent.LastModified = object.ModTime.UTC().Format(timeFormatAMZLong)\n\t\tif object.ETag != \"\" {\n\t\t\tcontent.ETag = \"\\\"\" + object.ETag + \"\\\"\"\n\t\t}\n\t\tcontent.Size = object.Size\n\t\tcontent.StorageClass = object.StorageClass\n\t\tcontent.Owner = owner\n\t\tcontent.VersionID = \"null\"\n\t\tcontent.IsLatest = true\n\t\tversions = append(versions, content)\n\t}\n\tdata.Name = bucket\n\tdata.Versions = versions\n\n\tdata.EncodingType = encodingType\n\tdata.Prefix = s3EncodeName(prefix, encodingType)\n\tdata.KeyMarker = s3EncodeName(marker, encodingType)\n\tdata.Delimiter = s3EncodeName(delimiter, encodingType)\n\tdata.MaxKeys = maxKeys\n\n\tdata.NextKeyMarker = s3EncodeName(resp.NextMarker, encodingType)\n\tdata.IsTruncated = resp.IsTruncated\n\n\tfor _, prefix := range resp.Prefixes {\n\t\tvar prefixItem = CommonPrefix{}\n\t\tprefixItem.Prefix = s3EncodeName(prefix, encodingType)\n\t\tprefixes = append(prefixes, prefixItem)\n\t}\n\tdata.CommonPrefixes = prefixes\n\treturn data\n}",
"func NewArtifactListerBadRequest() *ArtifactListerBadRequest {\n\n\treturn &ArtifactListerBadRequest{}\n}",
"func responderArtifact206(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerPartialContent) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\n\tresponder = artifacts.NewArtifactListerPartialContent()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tresponder.SetRemainingRecords(listInfo.RemainingRecords)\n\n\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\tartifactListerURL.After = &tmp\n\n\tif defaultPageLimit != paginator.Limit {\n\t\ttmp := paginator.Limit\n\t\tartifactListerURL.Limit = &tmp\n\t}\n\tresponder.SetNext(artifactListerURL.String())\n\n\tif paginator.ID != 0 { //... and not the first\n\t\t//paginator.ID is from query parameter not artifactmanager\n\t\tvar artifactListerURL artifacts.ArtifactListerURL\n\t\ttmp = artifactInfoReturned[0].ID\n\t\tartifactListerURL.Before = &tmp\n\t\tif defaultPageLimit != paginator.Limit {\n\t\t\ttmp := paginator.Limit\n\t\t\tartifactListerURL.Limit = &tmp\n\t\t}\n\t\tresponder.SetPrevious(artifactListerURL.String())\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func TestApiLevelArtifactsCreate(t *testing.T) {\n\tctx := context.Background()\n\tregistryClient, err := connection.NewClient(ctx)\n\tif err != nil {\n\t\tt.Logf(\"Failed to create client: %+v\", err)\n\t\tt.FailNow()\n\t}\n\tdefer registryClient.Close()\n\n\t// Setup\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n\tcreateProject(ctx, registryClient, t, \"controller-test\")\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"test-api-1\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-1/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\n\t// Test API 2\n\tcreateApi(ctx, registryClient, t, \"projects/controller-test\", \"test-api-2\")\n\t// Version 1.0.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.0.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.0.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.0.1\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.0.1\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.0.1\", \"openapi.yaml\", gzipOpenAPIv3)\n\t// Version 1.1.0\n\tcreateVersion(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2\", \"1.1.0\")\n\tcreateSpec(ctx, registryClient, t, \"projects/controller-test/apis/test-api-2/versions/1.1.0\", \"openapi.yaml\", gzipOpenAPIv3)\n\n\t// Test the manifest\n\tmanifest := manifests[1]\n\tactions, err := ProcessManifest(ctx, registryClient, \"controller-test\", manifest)\n\tif err != nil {\n\t\tlog.Printf(err.Error())\n\t}\n\texpectedActions := []string{\n\t\t\"compute vocabulary projects/controller-test/apis/test-api-1\",\n\t\t\"compute vocabulary projects/controller-test/apis/test-api-2\"}\n\tif diff := cmp.Diff(expectedActions, actions, sortStrings); diff != \"\" {\n\t\tt.Errorf(\"ProcessManifest(%+v) returned unexpected diff (-want +got):\\n%s\", manifest, diff)\n\t}\n\n\tdeleteProject(ctx, registryClient, t, \"controller-test\")\n}",
"func NewArtifactListerNotFound() *ArtifactListerNotFound {\n\n\treturn &ArtifactListerNotFound{}\n}",
"func getLeastDownloaded(w http.ResponseWriter, r *http.Request) {\n\ttopDownloaded, err := client.GetArtifactoryClient().GetLeastDownloaded()\n\tif err != nil {\n\t\tlog.Print(\"failed to get top downloaded artifacts\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tio.WriteString(w, \"failed to get top downloaded artifacts:\"+err.Error())\n\t\treturn\n\t}\n\tw.Header().Set(\"Content-Type\", \"application/json\")\n\terr = json.NewEncoder(w).Encode(topDownloaded)\n\tif err != nil {\n\t\tlog.Print(\"failed to encode top downloaded artifacts\", err.Error())\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t\tio.WriteString(w, \"failed to encode top downloaded artifact:\"+err.Error())\n\t\treturn\n\t}\n}",
"func NewAllDashboardsOK() *AllDashboardsOK {\n return &AllDashboardsOK{\n }\n}",
"func New(s string, timeout int, pagesDomain string) *Artifact {\n\treturn &Artifact{\n\t\tserver: s,\n\t\tclient: &http.Client{Timeout: time.Second * time.Duration(timeout)},\n\t\tpattern: hostPatternGen(pagesDomain),\n\t}\n\n}",
"func (a *DefaultApiService) ListRetrievedFiles(ctx _context.Context, imageDigest string) ([]RetrievedFile, *_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 []RetrievedFile\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/images/{imageDigest}/artifacts/retrieved_files\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageDigest\"+\"}\", _neturl.QueryEscape(parameterToString(imageDigest, \"\")) , -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\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\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 Create(\n\tctx context.Context,\n\tcfg config.Config,\n\tdc downloads.DatasetClient,\n\tfc downloads.FilterClient,\n\tic downloads.ImageClient,\n\ts3 content.S3Client,\n\tvc content.VaultClient,\n\tzc *health.Client,\n\thc *healthcheck.HealthCheck) Download {\n\n\trouter := mux.NewRouter()\n\n\tdownloader := downloads.Downloader{\n\t\tFilterCli: fc,\n\t\tDatasetCli: dc,\n\t\tImageCli: ic,\n\t}\n\n\ts3c := content.NewStreamWriter(s3, vc, cfg.VaultPath, cfg.EncryptionDisabled)\n\n\td := handlers.Download{\n\t\tDownloader: downloader,\n\t\tS3Content: s3c,\n\t\tIsPublishing: cfg.IsPublishing,\n\t}\n\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.csv\").HandlerFunc(d.DoDatasetVersion(\"csv\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.csv-metadata.json\").HandlerFunc(d.DoDatasetVersion(\"csvw\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/datasets/{datasetID}/editions/{edition}/versions/{version}.xlsx\").HandlerFunc(d.DoDatasetVersion(\"xls\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/filter-outputs/{filterOutputID}.csv\").HandlerFunc(d.DoFilterOutput(\"csv\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/downloads/filter-outputs/{filterOutputID}.xlsx\").HandlerFunc(d.DoFilterOutput(\"xls\", cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.Path(\"/images/{imageID}/{variant}/{filename}\").HandlerFunc(d.DoImage(cfg.ServiceAuthToken, cfg.DownloadServiceToken))\n\trouter.HandleFunc(\"/health\", hc.Handler)\n\n\t// Create new middleware chain with whitelisted handler for /health endpoint\n\tmiddlewareChain := alice.New(middleware.Whitelist(middleware.HealthcheckFilter(hc.Handler)))\n\n\t// For non-whitelisted endpoints, do identityHandler or corsHandler\n\tif cfg.IsPublishing {\n\t\tlog.Event(ctx, \"private endpoints are enabled. using identity middleware\", log.INFO)\n\t\tidentityHandler := dphandlers.IdentityWithHTTPClient(clientsidentity.NewWithHealthClient(zc))\n\t\tmiddlewareChain = middlewareChain.Append(identityHandler)\n\t} else {\n\t\tcorsHandler := gorillahandlers.CORS(gorillahandlers.AllowedMethods([]string{\"GET\"}))\n\t\tmiddlewareChain = middlewareChain.Append(corsHandler)\n\t}\n\n\tr := middlewareChain.\n\t\tAppend(dphandlers.CheckHeader(dphandlers.UserAccess)).\n\t\tAppend(dphandlers.CheckHeader(dphandlers.CollectionID)).\n\t\tThen(router)\n\thttpServer := dphttp.NewServer(cfg.BindAddr, r)\n\n\treturn Download{\n\t\tfilterClient: fc,\n\t\timageClient: ic,\n\t\tdatasetClient: dc,\n\t\tvaultClient: vc,\n\t\trouter: router,\n\t\tserver: httpServer,\n\t\tshutdown: cfg.GracefulShutdownTimeout,\n\t\thealthCheck: hc,\n\t}\n}",
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func catalog_Get(t *testing.T, opts ...configOpt) {\n\tenv := newTestEnv(t, opts...)\n\tdefer env.Shutdown()\n\n\tsortedRepos := []string{\n\t\t\"2j2ar\",\n\t\t\"asj9e/ieakg\",\n\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\"hpgkt/bmawb\",\n\t\t\"jyi7b\",\n\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\"kb0j5/pic0i\",\n\t\t\"n343n\",\n\t\t\"sb71y\",\n\t}\n\n\t// shuffle repositories to make sure results are consistent regardless of creation order (it matters when running\n\t// against the metadata database)\n\tshuffledRepos := shuffledCopy(sortedRepos)\n\n\tfor _, repo := range shuffledRepos {\n\t\tcreateRepository(t, env, repo, \"latest\")\n\t}\n\n\ttt := []struct {\n\t\tname string\n\t\tqueryParams url.Values\n\t\texpectedBody catalogAPIResponse\n\t\texpectedLinkHeader string\n\t}{\n\t\t{\n\t\t\tname: \"no query parameters\",\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last query parameter\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"empty last and n query parameters\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"\"}, \"n\": []string{\"\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"non integer n query parameter\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"foo\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"1st page\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"2j2ar\",\n\t\t\t\t\"asj9e/ieakg\",\n\t\t\t\t\"dcsl6/xbd1z/9t56s\",\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=hpgkt%2Fbmawb&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"nth page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"hpgkt/bmawb\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t}},\n\t\t\texpectedLinkHeader: `</v2/_catalog?last=kb0j5%2Fpic0i&n=4>; rel=\"next\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"last page\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}, \"n\": []string{\"4\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"zero page size\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"0\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"page size bigger than full list\",\n\t\t\tqueryParams: url.Values{\"n\": []string{\"100\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: sortedRepos},\n\t\t},\n\t\t{\n\t\t\tname: \"after marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"kb0j5/pic0i\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t\t{\n\t\t\tname: \"after non existent marker\",\n\t\t\tqueryParams: url.Values{\"last\": []string{\"does-not-exist\"}},\n\t\t\texpectedBody: catalogAPIResponse{Repositories: []string{\n\t\t\t\t\"hpgkt/bmawb\",\n\t\t\t\t\"jyi7b\",\n\t\t\t\t\"jyi7b/sgv2q/d5a2f\",\n\t\t\t\t\"jyi7b/sgv2q/fxt1v\",\n\t\t\t\t\"kb0j5/pic0i\",\n\t\t\t\t\"n343n\",\n\t\t\t\t\"sb71y\",\n\t\t\t}},\n\t\t},\n\t}\n\n\tfor _, test := range tt {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tresp, err := http.Get(catalogURL)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\tvar body catalogAPIResponse\n\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\terr = dec.Decode(&body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t})\n\t}\n\n\t// If the database is enabled, disable it and rerun the tests again with the\n\t// database to check that the filesystem mirroring worked correctly.\n\tif env.config.Database.Enabled && !env.config.Migration.DisableMirrorFS {\n\t\tenv.config.Database.Enabled = false\n\t\tdefer func() { env.config.Database.Enabled = true }()\n\n\t\tfor _, test := range tt {\n\t\t\tt.Run(fmt.Sprintf(\"%s filesystem mirroring\", test.name), func(t *testing.T) {\n\t\t\t\tcatalogURL, err := env.builder.BuildCatalogURL(test.queryParams)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp, err := http.Get(catalogURL)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tdefer resp.Body.Close()\n\n\t\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\t\tvar body catalogAPIResponse\n\t\t\t\tdec := json.NewDecoder(resp.Body)\n\t\t\t\terr = dec.Decode(&body)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trequire.Equal(t, test.expectedBody, body)\n\t\t\t\trequire.Equal(t, test.expectedLinkHeader, resp.Header.Get(\"Link\"))\n\t\t\t})\n\t\t}\n\t}\n}",
"func NewDescribeOK() *DescribeOK {\n\n\treturn &DescribeOK{}\n}",
"func newTestLister(t *testing.T) *testLister {\n\treturn &testLister{\n\t\tt: t,\n\t\talbums: newAlbums(),\n\t\tuploaded: dirtree.New(),\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithNext adds the next to the artifact lister o k response
|
func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {
o.Next = next
return o
}
|
[
"func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}",
"func (o *ArtifactListerOK) SetNext(next string) {\n\to.Next = next\n}",
"func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}",
"func (o *ArtifactListerPartialContent) SetNext(next string) {\n\to.Next = next\n}",
"func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}",
"func (s Service) Next(msg *Message, data interface{}, useMeta map[string]string) error {\n\terr := msg.RawMessage.Ack(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Chain == nil {\n\t\treturn ErrorChainIsEmpty\n\t}\n\n\tchain := SetCurrentItemSuccess(msg.Chain)\n\n\tnextIndex := getCurrentChainIndex(chain)\n\tif nextIndex == -1 {\n\t\treturn ErrorNextIsNotDefined\n\t}\n\n\tnextElement := chain[nextIndex]\n\n\tmeta := Meta{}\n\tmeta.Merge(msg.Meta, useMeta)\n\n\tvar items []interface{}\n\n\tif nextElement.IsMultiple {\n\t\tval := reflect.ValueOf(data)\n\n\t\tif val.Kind() != reflect.Slice {\n\t\t\treturn ErrorDataIsNotArray\n\t\t}\n\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\titems = append(items, val.Index(i).Interface())\n\t\t}\n\t} else {\n\t\titems = append(items, data)\n\t}\n\n\tfor _, item := range items {\n\t\tb, err := json.Marshal(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := InitialMessage{\n\t\t\tCatch: msg.InitialMessage.Catch,\n\t\t\tConfig: msg.Config,\n\t\t\tMeta: meta,\n\t\t\tChain: chain,\n\t\t\tData: b,\n\t\t}\n\n\t\tif err := s.Publish(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}",
"func (client DatasetClient) listNextResults(ctx context.Context, lastResults DatasetListResponse) (result DatasetListResponse, err error) {\n req, err := lastResults.datasetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }",
"func (i *UploadShrinker) Next() *FileUpload {\n\tvar n int\n\tvar err error\n\n\tif i.Done() {\n\t\treturn nil\n\t}\n\n\tif n, err = i.f.Read(i.buff); err != nil && err != io.EOF {\n\t\ti.err = err\n\t\treturn nil\n\t}\n\n\ti.fu.Chunk = i.chunk\n\ti.fu.Content = i.buff[:n]\n\ti.chunk++\n\n\treturn i.fu\n}",
"func (page *DatabaseOperationListResultPage) Next() error {\n\tnext, err := page.fn(page.dolr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dolr = next\n\treturn nil\n}",
"func (rrs *readResponseSet) next(ctx context.Context) *jobReadRegistryResponse {\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn nil\n\tcase resp := <-rrs.c:\n\t\trrs.readResps = append(rrs.readResps, resp)\n\t\trrs.left--\n\t\treturn resp\n\t}\n}",
"func (h *Sagify) SetNext(next job.Handler) {\n\th.next = next\n}",
"func WithNext(next *url.URL) Opt {\n\treturn func(opts *Options) {\n\t\topts.Next = next\n\t}\n}",
"func (l *EnvironmentList) Next(ctx context.Context, c *Client) error {\n\treturn fmt.Errorf(\"no next page\")\n}",
"func (it *kmerIter1[T, H]) next() error {\n\terr := it.cur.Decode(it.r)\n\tif err != nil {\n\t\tit.cur = nil\n\t}\n\treturn err\n}",
"func (l *Listing) Next() bool {\n\tif l.err != nil {\n\t\treturn false\n\t}\n\tif len(l.objects) > 0 {\n\t\tl.objects = l.objects[:len(l.objects)-1]\n\t}\n\tif len(l.objects) > 0 {\n\t\treturn true\n\t}\n\tif l.nextName == nil {\n\t\treturn false // end of iteration\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"bucketId\": l.b.ID,\n\t\t\"startFileName\": *l.nextName,\n\t\t\"maxFileCount\": l.nextPageCount,\n\t}\n\tendpoint := \"b2_list_file_names\"\n\tif l.versions {\n\t\tendpoint = \"b2_list_file_versions\"\n\t}\n\tif l.nextID != nil && *l.nextID != \"\" {\n\t\tdata[\"startFileId\"] = *l.nextID\n\t}\n\tr, err := l.b.c.doRequest(endpoint, data)\n\tif err != nil {\n\t\tl.err = err\n\t\treturn false\n\t}\n\tdefer drainAndClose(r.Body)\n\n\tvar x struct {\n\t\tFiles []fileInfoObj\n\t\tNextFileName *string\n\t\tNextFileID *string\n\t}\n\tif l.err = json.NewDecoder(r.Body).Decode(&x); l.err != nil {\n\t\treturn false\n\t}\n\n\tl.objects = make([]*FileInfo, len(x.Files))\n\tfor i, f := range x.Files {\n\t\tl.objects[len(l.objects)-1-i] = f.makeFileInfo()\n\t}\n\tl.nextName, l.nextID = x.NextFileName, x.NextFileID\n\treturn len(l.objects) > 0\n}",
"func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}",
"func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}",
"func (s seekResult) Next() {\n\tnext := s.Node().Next()\n\tfor i := range next.nexts {\n\t\ts[i] = next\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetNext sets the next to the artifact lister o k response
|
func (o *ArtifactListerOK) SetNext(next string) {
o.Next = next
}
|
[
"func (o *ArtifactListerPartialContent) SetNext(next string) {\n\to.Next = next\n}",
"func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {\n\to.Next = next\n\treturn o\n}",
"func (h *Sagify) SetNext(next job.Handler) {\n\th.next = next\n}",
"func (o *StdOutOutput) SetNext(next Output) {\n\to.next = next\n}",
"func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}",
"func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}",
"func (f *MutateFilter) SetNext(next Filter) {\n\tf.next = next\n}",
"func (s *Links) SetNext(val OptString) {\n\ts.Next = val\n}",
"func (bce *BaseCompositeEndpoint) SetNext(next CompositeEndpoint) CompositeEndpoint {\n\tif bce.self == nil {\n\t\tlogrus.Fatal(\"Any struct that edtends BaseCompositeEndpoint should have 'self' set. Consider using SetSelf().\")\n\t}\n\tbce.next = next\n\treturn bce.self\n}",
"func (c *layerCache) setNext(next Layer) error {\n\tc.next = next\n\treturn nil\n}",
"func (g *GZipper) SetNext(h http.Handler) {\n\tg.next = h\n}",
"func (l *Headers) SetNext(h http.Handler) {\n\tl.next = h\n}",
"func (tn *MergeNode) SetNext(t *TaskNode) {\n\t// make sure we have a cpy of this in the parent map\n\ttn.floe.registerNode(t)\n\ttn.next = t\n}",
"func (m *BaseStatement) SetNext(next Statement) {\n\tm.next = next\n}",
"func (p *Playlist) Next() {\n\tp.ch <- \"next\"\n}",
"func (p *page) SetNext(id txfile.PageID) {\n\thdr := castEventPageHeader(p.Data)\n\thdr.next.Set(uint64(id))\n}",
"func (o *PaginatedChangeset) SetNext(v string) {\n\to.Next = &v\n}",
"func (nu *NodeUpdate) SetNext(n *Node) *NodeUpdate {\n\treturn nu.SetNextID(n.ID)\n}",
"func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPrevious adds the previous to the artifact lister o k response
|
func (o *ArtifactListerOK) WithPrevious(previous string) *ArtifactListerOK {
o.Previous = previous
return o
}
|
[
"func (o *ArtifactListerOK) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (o *ArtifactListerPartialContent) WithPrevious(previous string) *ArtifactListerPartialContent {\n\to.Previous = previous\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (app *builder) WithPrevious(prev Government) Builder {\n\tapp.prev = prev\n\treturn app\n}",
"func (c *Client) PlaylistPrevious() error {\n\t_, err := c.Exec(\"playlist-prev\", \"weak\")\n\treturn err\n}",
"func (r Response) Prev() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"prev\",\n\t}\n}",
"func (el *Element) Previous() *Element {\n\tparent, err := el.PreviousE()\n\tkit.E(err)\n\treturn parent\n}",
"func (e *ListElement) Previous() *ListElement {\n\treturn (*ListElement)(atomic.LoadPointer(&e.previousElement))\n}",
"func WithPrev(prev *url.URL) Opt {\n\treturn func(opts *Options) {\n\t\topts.Prev = prev\n\t}\n}",
"func (r AboutRequester) PreviousDeployment() (*Deployment, error) {\n\towner := \"jacobpatterson1549\"\n\trepo := \"nate-mlb\"\n\turi := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/deployments\", owner, repo)\n\tvar s githubRepoDeployments\n\terr := r.requester.structPointerFromURI(uri, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.previousDeployment(r.environment), nil\n}",
"func (lr *ListResponse) HasPrevious() bool {\n\tif lr.currentIndex == 0 {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (iter *iterator) Previous() List.Iterator {\n\titer.i--\n\n\tif iter.current != nil && iter.i < 0 {\n\t\titer.current = iter.current.previous\n\n\t\tif iter.current != nil {\n\t\t\titer.i = len(iter.current.values) - 1\n\t\t}\n\t}\n\n\tif iter.current == nil {\n\t\treturn nil\n\t}\n\n\treturn iter\n}",
"func (as appendStrategy) previous() error {\n\treturn as.previousErr\n}",
"func (e *RepoEntity) PreviousRemote() error {\n\te.Remote = e.Remotes[(len(e.Remotes)+e.currentRemoteIndex()-1)%len(e.Remotes)]\n\te.Remote.SyncBranches(e.Branch.Name)\n\treturn e.Publish(RepositoryUpdated, nil)\n}",
"func (hist *history) previous() (prev string) {\n\n\thist.index -= 1\n\tif hist.index < 0 {\n\t\thist.index = 0\n\t}\n\n\tif hist.index < len(hist.commandHistory) {\n\t\tprev = hist.commandHistory[hist.index]\n\t}\n\treturn prev\n}",
"func (a *Art) SavePrevious(b *Buf) {\n\tif a.Page.AnsSave == \"on\" {\n\t\tb.ArrStr1 = append(append(b.ArrStr1, \" \"), a.Page.AnsWeb...)\n\t\tb.ArrStr2 = append(append(b.ArrStr2, \" \"), a.Page.AnsFile...)\n\t}\n\ta.Page.AnsWeb = b.ArrStr1\n\ta.Page.AnsFile = b.ArrStr2\n}",
"func NextPrev(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Received Request: /MediaControls\")\n\taction := strings.TrimPrefix(r.URL.Path, \"/MediaControls/\")\n\tfmt.Println(\"Action:\", action)\n\n\tvar URL *url.URL\n\tURL, err := url.Parse(\"https://api.spotify.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tURL.Path += \"/v1/me/player\"\n\n\tclient := &http.Client{}\n\n\tswitch action {\n\tcase \"Next\":\n\t\tURL.Path += \"/next\"\n\tcase \"Previous\":\n\t\tURL.Path += \"/previous\"\n\t}\n\n\treq, err := http.NewRequest(\"POST\", URL.String(), nil)\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+sAcsTok.AccessToken)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}",
"func (o *PaginatedChangeset) SetPrevious(v string) {\n\to.Previous = &v\n}",
"func (l *Linenoise) historyPrev(ls *linestate) string {\n\tif len(l.history) == 0 {\n\t\treturn \"\"\n\t}\n\t// update the current history entry with the line buffer\n\tl.historySet(ls.historyIndex, ls.String())\n\tls.historyIndex++\n\t// previous history item\n\tif ls.historyIndex >= len(l.history) {\n\t\tls.historyIndex = len(l.history) - 1\n\t}\n\treturn l.historyGet(ls.historyIndex)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPrevious sets the previous to the artifact lister o k response
|
func (o *ArtifactListerOK) SetPrevious(previous string) {
o.Previous = previous
}
|
[
"func (o *ArtifactListerPartialContent) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (o *ArtifactListerOK) WithPrevious(previous string) *ArtifactListerOK {\n\to.Previous = previous\n\treturn o\n}",
"func (o *PaginatedChangeset) SetPrevious(v string) {\n\to.Previous = &v\n}",
"func (o *ArtifactListerPartialContent) WithPrevious(previous string) *ArtifactListerPartialContent {\n\to.Previous = previous\n\treturn o\n}",
"func (m *Mutation) SetPrevious(oldValueRevision uint64, oldValue []byte, copyPrevious bool) error {\n\tprevSignedEntry, err := FromLeafValue(oldValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.prevRev = oldValueRevision\n\tm.prevSignedEntry = prevSignedEntry\n\n\thash := sha256.Sum256(prevSignedEntry.GetEntry())\n\tm.entry.Previous = hash[:]\n\n\tvar prevEntry pb.Entry\n\tif err := proto.Unmarshal(prevSignedEntry.GetEntry(), &prevEntry); err != nil {\n\t\treturn err\n\t}\n\tif copyPrevious {\n\t\tm.entry.AuthorizedKeyset = prevEntry.GetAuthorizedKeyset()\n\t\tm.entry.Commitment = prevEntry.GetCommitment()\n\t}\n\treturn nil\n}",
"func (r Response) Prev() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"prev\",\n\t}\n}",
"func (e *RepoEntity) PreviousCommit() {\n\te.Commit = e.Commits[(len(e.Commits)+e.currentCommitIndex()-1)%len(e.Commits)]\n}",
"func (c *Client) PlaylistPrevious() error {\n\t_, err := c.Exec(\"playlist-prev\", \"weak\")\n\treturn err\n}",
"func (p *Player) Previous() *dbus.Error {\n\treturn nil\n}",
"func (e *RepoEntity) PreviousRemote() error {\n\te.Remote = e.Remotes[(len(e.Remotes)+e.currentRemoteIndex()-1)%len(e.Remotes)]\n\te.Remote.SyncBranches(e.Branch.Name)\n\treturn e.Publish(RepositoryUpdated, nil)\n}",
"func (r AboutRequester) PreviousDeployment() (*Deployment, error) {\n\towner := \"jacobpatterson1549\"\n\trepo := \"nate-mlb\"\n\turi := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/deployments\", owner, repo)\n\tvar s githubRepoDeployments\n\terr := r.requester.structPointerFromURI(uri, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.previousDeployment(r.environment), nil\n}",
"func (n *Node) setPrev(newPrev shared.NodeInfo) {\n\tn.prevLock.Lock()\n\n\tn.prev = newPrev\n\n\tn.prevLock.Unlock()\n\t//Used for visulization\n\t//n.updateState()\n}",
"func (r *Raft) setPreviousLog(req *pb.AppendEntriesRequest, nextIndex uint64) error {\n\t// Guard for the first index, since there is no 0 log entry\n\t// Guard against the previous index being a snapshot as well\n\tlastSnapIdx, lastSnapTerm := r.getLastSnapshot()\n\tif nextIndex == 1 {\n\t\treq.PrevLogIndex = 0\n\t\treq.PrevLogTerm = 0\n\t} else if (nextIndex - 1) == lastSnapIdx {\n\t\treq.PrevLogIndex = lastSnapIdx\n\t\treq.PrevLogTerm = lastSnapTerm\n\t} else {\n\t\tvar l pb.Log\n\t\tif err := r.logs.GetLog(nextIndex-1, &l); err != nil {\n\t\t\tklog.Errorf(fmt.Sprintf(\"failed to get log index:%d err:%v\", nextIndex-1, err))\n\t\t\treturn err\n\t\t}\n\n\t\t// Set the previous index and term (0 if nextIndex is 1)\n\t\treq.PrevLogIndex = l.Index\n\t\treq.PrevLogTerm = l.Term\n\t}\n\treturn nil\n}",
"func (s *Links) SetPrev(val OptString) {\n\ts.Prev = val\n}",
"func (nu *NodeUpdate) SetPrev(n *Node) *NodeUpdate {\n\treturn nu.SetPrevID(n.ID)\n}",
"func (a *Art) SavePrevious(b *Buf) {\n\tif a.Page.AnsSave == \"on\" {\n\t\tb.ArrStr1 = append(append(b.ArrStr1, \" \"), a.Page.AnsWeb...)\n\t\tb.ArrStr2 = append(append(b.ArrStr2, \" \"), a.Page.AnsFile...)\n\t}\n\ta.Page.AnsWeb = b.ArrStr1\n\ta.Page.AnsFile = b.ArrStr2\n}",
"func (el *Element) Previous() *Element {\n\tparent, err := el.PreviousE()\n\tkit.E(err)\n\treturn parent\n}",
"func (nuo *NodeUpdateOne) SetPrev(n *Node) *NodeUpdateOne {\n\treturn nuo.SetPrevID(n.ID)\n}",
"func (hist *history) previous() (prev string) {\n\n\thist.index -= 1\n\tif hist.index < 0 {\n\t\thist.index = 0\n\t}\n\n\tif hist.index < len(hist.commandHistory) {\n\t\tprev = hist.commandHistory[hist.index]\n\t}\n\treturn prev\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithTotalRecords adds the totalRecords to the artifact lister o k response
|
func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {
o.TotalRecords = totalRecords
return o
}
|
[
"func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (g *GlobalResponse) Sum() {\n\tsum := 0\n\n\tfor _, v := range g.Records {\n\t\tsum += v.Fields.NumBikesAvailable\n\t}\n\n\tg.Total = sum\n}",
"func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *sc.QueryResponseMetadata) *bytes.Buffer {\n\n\tbuffer.WriteString(\"[{\\\"ResponseMetadata\\\":{\\\"RecordsCount\\\":\")\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(fmt.Sprintf(\"%v\", responseMetadata.FetchedRecordsCount))\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(\", \\\"Bookmark\\\":\")\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(responseMetadata.Bookmark)\n\tbuffer.WriteString(\"\\\"}}]\")\n\n\treturn buffer\n}",
"func (nsc *NilConsumerStatsCollector) AddGetRecordsCalled(int) {}",
"func outputRecordsAll(cmd *cobra.Command) error {\n\tclientCtx, err := client.GetClientQueryContext(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpageReq, e := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags()))\n\tif e != nil {\n\t\treturn e\n\t}\n\tqueryClient := types.NewQueryClient(clientCtx)\n\tres, err := queryClient.RecordsAll(\n\t\tcontext.Background(),\n\t\t&types.RecordsAllRequest{Pagination: pageReq},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !includeRequest {\n\t\tres.Request = nil\n\t}\n\n\treturn clientCtx.PrintProto(res)\n}",
"func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *pb.QueryResponseMetadata) *bytes.Buffer {\n\n buffer.WriteString(\"[{\\\"ResponseMetadata\\\":{\\\"RecordsCount\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(fmt.Sprintf(\"%v\", responseMetadata.FetchedRecordsCount))\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(\", \\\"Bookmark\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(responseMetadata.Bookmark)\n buffer.WriteString(\"\\\"}}]\")\n\n return buffer\n}",
"func (rb *ShardsRecordBuilder) FlushTotal(flushtotal string) *ShardsRecordBuilder {\n\trb.v.FlushTotal = &flushtotal\n\treturn rb\n}",
"func (dsc *DefaultConsumerStatsCollector) AddGetRecordsCalled(count int) {\n\tdsc.GetRecordsCalled.Inc(int64(count))\n}",
"func (a *Aggregator) AggregateRecords() (entry *kinesis.PutRecordsRequestEntry, err error) {\n\n\tif len(a.records) == 0 {\n\t\treturn nil, nil\n\t}\n\n\tpkeys := a.getPartitionKeys()\n\n\tagg := &AggregatedRecord{\n\t\tPartitionKeyTable: pkeys,\n\t\tRecords: a.records,\n\t}\n\n\tprotoBufData, err := proto.Marshal(agg)\n\tif err != nil {\n\t\tlogrus.Errorf(\"Failed to encode record: %v\", err)\n\t\treturn nil, err\n\t}\n\n\tmd5Sum := md5.New()\n\tmd5Sum.Write(protoBufData)\n\tmd5CheckSum := md5Sum.Sum(nil)\n\n\tkclData := append(kclMagicNumber, protoBufData...)\n\tkclData = append(kclData, md5CheckSum...)\n\n\tlogrus.Debugf(\"[kinesis ] Aggregated (%d) records of size (%d) with total size (%d), partition key (%s)\\n\", len(a.records), a.getSize(), len(kclData), pkeys[0])\n\n\t// Clear buffer if aggregation didn't fail\n\ta.clearBuffer()\n\n\treturn &kinesis.PutRecordsRequestEntry{\n\t\tData: kclData,\n\t\tPartitionKey: aws.String(pkeys[0]),\n\t}, nil\n}",
"func (this *BaseController) OnResultsWithTotalCountAny(viewName string, results interface{}, totalCount int64) {\n\n\tif this.IsJson() {\n\t\tthis.OnJsonResultsWithTotalCount(results, totalCount)\n\t} else {\n\t\tthis.OnResultsWithTotalCount(viewName, results, totalCount)\n\t}\n\n}",
"func (bguo *BarGroupUpdateOne) AddRecords(b ...*BarRecord) *BarGroupUpdateOne {\n\tids := make([]int, len(b))\n\tfor i := range b {\n\t\tids[i] = b[i].ID\n\t}\n\treturn bguo.AddRecordIDs(ids...)\n}",
"func (k Keeper) RecordsAll(c context.Context, req *types.RecordsAllRequest) (*types.RecordsAllResponse, error) {\n\tdefer telemetry.MeasureSince(time.Now(), types.ModuleName, \"query\", \"RecordsAll\")\n\tretval := types.RecordsAllResponse{Request: req}\n\n\tpageRequest := getPageRequest(req)\n\n\tctx := sdk.UnwrapSDKContext(c)\n\tkvStore := ctx.KVStore(k.storeKey)\n\tprefixStore := prefix.NewStore(kvStore, types.RecordKeyPrefix)\n\n\tpageRes, err := query.Paginate(prefixStore, pageRequest, func(key, value []byte) error {\n\t\tvar record types.Record\n\t\tvErr := record.Unmarshal(value)\n\t\tif vErr == nil {\n\t\t\tretval.Records = append(retval.Records, types.WrapRecord(&record))\n\t\t\treturn nil\n\t\t}\n\t\t// Something's wrong. Let's do what we can to give indications of it.\n\t\tvar addr types.MetadataAddress\n\t\tkErr := addr.Unmarshal(key)\n\t\tif kErr == nil {\n\t\t\tk.Logger(ctx).Error(\"failed to unmarshal record\", \"address\", addr, \"error\", vErr)\n\t\t\tretval.Records = append(retval.Records, types.WrapRecordNotFound(addr))\n\t\t} else {\n\t\t\tk64 := b64.StdEncoding.EncodeToString(key)\n\t\t\tk.Logger(ctx).Error(\"failed to unmarshal record key and value\",\n\t\t\t\t\"key error\", kErr, \"value error\", vErr, \"key (base64)\", k64)\n\t\t\tretval.Records = append(retval.Records, &types.RecordWrapper{})\n\t\t}\n\t\treturn nil // Still want to move on to the next.\n\t})\n\tif err != nil {\n\t\treturn &retval, status.Error(codes.Unavailable, err.Error())\n\t}\n\tretval.Pagination = pageRes\n\treturn &retval, nil\n}",
"func getTotals(snapshots []Snapshot) TotalResponse {\n reports := len(snapshots)\n days := make(map[string]int)\n people := make(map[string]int)\n locations := make(map[string]int)\n activities:= make(map[string]int)\n coffees := 0\n\n for _, snapshot := range snapshots {\n // Count people\n date := snapshot.Date[:10]\n days[date]++\n\n for _, response := range snapshot.Responses {\n question := response.QuestionPrompt\n // Count people\n if question == \"Who are you with?\" {\n for _, token := range response.Tokens {\n people[token.Text]++\n }\n } else if question == \"Where are you?\" {\n // count locations\n locations[response.LocationResponse.Text]++\n } else if question == \"How many coffees did you have today?\" {\n // count coffees\n amount, err := strconv.Atoi(response.NumericResponse)\n if err == nil {\n coffees += amount\n }\n } else if question == \"What are you doing?\" {\n for _, token := range response.Tokens {\n activities[token.Text]++\n }\n }\n }\n }\n\n return TotalResponse{\n TotalDays: len(days),\n TotalReports: reports,\n TotalPeople: len(people),\n TotalLocations: len(locations),\n AvgPerDay: float32(reports)/float32(len(days)),\n TotalCoffees: coffees,\n CoffeesPerDay: float32(coffees)/float32(len(days)),\n PeopleList: people,\n LocationList: locations,\n ActivityList: activities,\n }\n}",
"func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {\n\to.RemainingRecords = remainingRecords\n\treturn o\n}",
"func (o *ExportRuleGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (d *DBClient) RecordsCount(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tcount, err := d.Cache.RecordsCount()\n\n\tif err == nil {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tvar response recordsCount\n\t\tresponse.Count = count\n\t\tb, err := json.Marshal(response)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Error\": err.Error(),\n\t\t}).Error(\"Failed to get data from cache!\")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(500) // can't process this entity\n\t\treturn\n\t}\n}",
"func (bgu *BarGroupUpdate) AddRecords(b ...*BarRecord) *BarGroupUpdate {\n\tids := make([]int, len(b))\n\tfor i := range b {\n\t\tids[i] = b[i].ID\n\t}\n\treturn bgu.AddRecordIDs(ids...)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetTotalRecords sets the totalRecords to the artifact lister o k response
|
func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {
o.TotalRecords = totalRecords
}
|
[
"func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetRemainingRecords(remainingRecords uint64) {\n\to.RemainingRecords = remainingRecords\n}",
"func (o *ExportRuleGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (page *Page) SetTotal(rowCount, pageSize uint64) {\n\tpage.Total = int64(math.Ceil(float64(rowCount) / float64(pageSize)))\n\tpage.TotalRows = int64(rowCount)\n}",
"func (u *UserResultsPage) setTotalPages(p int) {\n\tu.TotalPages = p\n}",
"func (m *Office365GroupsActivityFileCounts) SetTotal(value *int64)() {\n err := m.GetBackingStore().Set(\"total\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (g *GlobalResponse) Sum() {\n\tsum := 0\n\n\tfor _, v := range g.Records {\n\t\tsum += v.Fields.NumBikesAvailable\n\t}\n\n\tg.Total = sum\n}",
"func (o *SnapmirrorGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (rb *ShardsRecordBuilder) FlushTotal(flushtotal string) *ShardsRecordBuilder {\n\trb.v.FlushTotal = &flushtotal\n\treturn rb\n}",
"func (b *Base) SetTotalCountHeader(total int64) {\n\tb.RespHeader().Set(\"X-Total-Count\", fmt.Sprint(total))\n\tb.AppendAccessControlExposeHeaders(\"X-Total-Count\")\n}",
"func (u *UserResultsPage) setTotalMatches(m int) {\n\tu.TotalMatches = m\n}",
"func (o *IscsiInterfaceGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (suite *TestPagingSuite) TestSetTotalCount(c *C) {\n\ttestCases := []*struct {\n\t\ttotalCount int32\n\t\texpected bool\n\t}{\n\t\t{21, true},\n\t\t{20, false},\n\t\t{19, false},\n\t\t{0, false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tcomment := ocheck.TestCaseComment(i)\n\t\tocheck.LogTestCase(c, testCase)\n\n\t\ttestedPaging := NewUndefinedPaging()\n\t\ttestedPaging.Position = 2\n\t\ttestedPaging.Size = 10\n\n\t\ttestedPaging.SetTotalCount(testCase.totalCount)\n\n\t\tc.Assert(testedPaging.PageMore, Equals, testCase.expected, comment)\n\t}\n}",
"func (nsc *NilConsumerStatsCollector) AddGetRecordsCalled(int) {}",
"func (o *IscsiInitiatorGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (r *MachinePoolsListServerResponse) Total(value int) *MachinePoolsListServerResponse {\n\tr.total = &value\n\treturn r\n}",
"func (fc *FileControl) TotalRecordCountField() string {\n\treturn fc.numericField(fc.TotalRecordCount, 8)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPayload adds the payload to the artifact lister o k response
|
func (o *ArtifactListerOK) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerOK {
o.Payload = payload
return o
}
|
[
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerPartialContent) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerPartialContent {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ListApiregistrationV1APIServiceOK) SetPayload(payload *models.IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceList) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerPartialContent) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecDefault) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {\n\to.Payload = payload\n\treturn o\n}",
"func (o *GetAuditregistrationV1alpha1APIResourcesOK) SetPayload(payload *models.IoK8sApimachineryPkgApisMetaV1APIResourceList) {\n\to.Payload = payload\n}",
"func (o *GetFeedOK) SetPayload(payload []*models.Offering) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *AlbumListMatchOK) SetPayload(payload *models.InlineResponse2006) {\n\to.Payload = payload\n}",
"func (o *GetAssetsListOK) SetPayload(payload []*models.TokenAssetRow) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageOK) SetPayload(payload CatalogEntryPackage.CatalogEntryPackage) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) WithPayload(payload *weles.ErrResponse) *ArtifactListerNotFound {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ListAppsV1NamespacedDeploymentOK) SetPayload(payload *models.IoK8sAPIAppsV1DeploymentList) {\n\to.Payload = payload\n}",
"func (o *GetImagesListOK) SetPayload(payload []*models.Image) {\n\to.Payload = payload\n}",
"func (o *GetCoreAPIVersionsOK) SetPayload(payload *models.IoK8sApimachineryPkgApisMetaV1APIVersions) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPayload sets the payload to the artifact lister o k response
|
func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {
o.Payload = payload
}
|
[
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerPartialContent) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecDefault) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetAssetsListOK) SetPayload(payload []*models.TokenAssetRow) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageOK) SetPayload(payload CatalogEntryPackage.CatalogEntryPackage) {\n\to.Payload = payload\n}",
"func (o *GetAuditregistrationV1alpha1APIResourcesOK) SetPayload(payload *models.IoK8sApimachineryPkgApisMetaV1APIResourceList) {\n\to.Payload = payload\n}",
"func (o *AddComponentRoleInternalServerError) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *AddReleasesInternalServerError) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *AddReleasesUnauthorized) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *GetItemNameOK) SetPayload(payload *models.Item) {\n\to.Payload = payload\n}",
"func (o *AddItemInternalServerError) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *GetFeedOK) SetPayload(payload []*models.Offering) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListUnauthorized) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *GetChartsInfoOK) SetPayload(payload []*models.ChartsData) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageInternalServerError) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *AddComponentRoleConflict) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateClusterUnauthorized) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewArtifactListerPartialContent creates ArtifactListerPartialContent with default headers values
|
func NewArtifactListerPartialContent() *ArtifactListerPartialContent {
return &ArtifactListerPartialContent{}
}
|
[
"func responderArtifact206(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerPartialContent) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\n\tresponder = artifacts.NewArtifactListerPartialContent()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tresponder.SetRemainingRecords(listInfo.RemainingRecords)\n\n\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\tartifactListerURL.After = &tmp\n\n\tif defaultPageLimit != paginator.Limit {\n\t\ttmp := paginator.Limit\n\t\tartifactListerURL.Limit = &tmp\n\t}\n\tresponder.SetNext(artifactListerURL.String())\n\n\tif paginator.ID != 0 { //... and not the first\n\t\t//paginator.ID is from query parameter not artifactmanager\n\t\tvar artifactListerURL artifacts.ArtifactListerURL\n\t\ttmp = artifactInfoReturned[0].ID\n\t\tartifactListerURL.Before = &tmp\n\t\tif defaultPageLimit != paginator.Limit {\n\t\t\ttmp := paginator.Limit\n\t\t\tartifactListerURL.Limit = &tmp\n\t\t}\n\t\tresponder.SetPrevious(artifactListerURL.String())\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {\n\to.RemainingRecords = remainingRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerPartialContent {\n\to.Payload = payload\n\treturn o\n}",
"func (a *APIDefaults) ArtifactLister(params artifacts.ArtifactListerParams) middleware.Responder {\n\tpaginator := weles.ArtifactPagination{}\n\tif a.PageLimit != 0 {\n\t\tif (params.After != nil) && (params.Before != nil) {\n\t\t\treturn artifacts.NewArtifactListerBadRequest().WithPayload(&weles.ErrResponse{\n\t\t\t\tMessage: weles.ErrBeforeAfterNotAllowed.Error()})\n\t\t}\n\t\tpaginator = setArtifactPaginator(params, a.PageLimit)\n\t}\n\tfilter := setArtifactFilter(params.ArtifactFilterAndSort.Filter)\n\tsorter := setArtifactSorter(params.ArtifactFilterAndSort.Sorter)\n\n\tartifactInfoReceived, listInfo, err := a.Managers.AM.ListArtifact(filter, sorter, paginator)\n\n\tswitch err {\n\tdefault:\n\t\treturn artifacts.NewArtifactListerInternalServerError().WithPayload(\n\t\t\t&weles.ErrResponse{Message: err.Error()})\n\tcase weles.ErrArtifactNotFound:\n\t\treturn artifacts.NewArtifactListerNotFound().WithPayload(\n\t\t\t&weles.ErrResponse{Message: weles.ErrArtifactNotFound.Error()})\n\tcase nil:\n\t}\n\n\tartifactInfoReturned := artifactInfoReceivedToReturn(artifactInfoReceived)\n\n\tif (listInfo.RemainingRecords == 0) || (a.PageLimit == 0) { //last page...\n\t\treturn responderArtifact200(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n\t} //not last page...\n\treturn responderArtifact206(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n}",
"func responderArtifact200(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerOK) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\tresponder = artifacts.NewArtifactListerOK()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tif paginator.ID != 0 { //not the first page\n\t\t// keep in mind that ArtifactPath in paginator is taken from query parameter,\n\t\t// not ArtifactManager\n\t\tif paginator.Forward {\n\t\t\ttmp := artifactInfoReturned[0].ID\n\t\t\tartifactListerURL.Before = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp\n\t\t\t}\n\t\t\tresponder.SetPrevious(artifactListerURL.String())\n\t\t} else {\n\t\t\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\t\t\tartifactListerURL.After = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp2 := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp2\n\t\t\t}\n\t\t\tresponder.SetNext(artifactListerURL.String())\n\t\t}\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func newFetchMediaView(res *FetchMedia) *fetcherviews.FetchMediaView {\n\tvres := &fetcherviews.FetchMediaView{\n\t\tStatus: &res.Status,\n\t\tArchiveHref: &res.ArchiveHref,\n\t}\n\treturn vres\n}",
"func NewActionResultPart()(*ActionResultPart) {\n m := &ActionResultPart{\n }\n m.SetAdditionalData(make(map[string]interface{}));\n return m\n}",
"func NewContents (rawContents []map[string]interface{}) []Content {\n newContents := make ([]Content, len (rawContents))\n\n for i, rawContent := range rawContents {\n newContents[i] = NewContent (rawContent)\n }\n\n return newContents\n}",
"func newFetchMedia(vres *fetcherviews.FetchMediaView) *FetchMedia {\n\tres := &FetchMedia{}\n\tif vres.Status != nil {\n\t\tres.Status = *vres.Status\n\t}\n\tif vres.ArchiveHref != nil {\n\t\tres.ArchiveHref = *vres.ArchiveHref\n\t}\n\treturn res\n}",
"func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}",
"func (a *DefaultApiService) ListFileContentSearchResults(ctx _context.Context, imageDigest string) ([]FileContentSearchResult, *_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 []FileContentSearchResult\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/images/{imageDigest}/artifacts/file_content_search\"\n\tlocalVarPath = strings.Replace(localVarPath, \"{\"+\"imageDigest\"+\"}\", _neturl.QueryEscape(parameterToString(imageDigest, \"\")) , -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\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\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 NewMobileAppContentFileCollectionResponse()(*MobileAppContentFileCollectionResponse) {\n m := &MobileAppContentFileCollectionResponse{\n BaseCollectionPaginationCountResponse: *NewBaseCollectionPaginationCountResponse(),\n }\n return m\n}",
"func (fm *FileManager) BuildResponse() *plugin.Response {\n\tres := plugin.NewResponse()\n\tfor _, f := range fm.files {\n\t\tcontent := f.Content\n\t\tfor _, p := range fm.patch[f.GetName()] {\n\t\t\tpos := plugin.InsertionPoint(p.GetInsertionPoint())\n\t\t\ttxt := p.Content + pos\n\t\t\tcontent = strings.Replace(content, pos, txt, -1)\n\t\t\tfm.log.Info(fmt.Sprintf(\"patch %q at %q with size %d\", f.GetName(), p.GetInsertionPoint(), len(p.Content)))\n\t\t}\n\n\t\tg := &plugin.Generated{\n\t\t\tName: f.Name,\n\t\t\tContent: stripInsertionPoint(content),\n\t\t}\n\t\tres.Contents = append(res.Contents, g)\n\t}\n\treturn res\n}",
"func newContentTypes(f interface{}, pkg *PackageInfo) *ContentTypes {\n\tcontent := &ContentTypes{\n\t\tpkg: pkg,\n\t}\n\n\tcontent.file = NewPackageFile(pkg, f, &content.ml, nil)\n\tcontent.file.LoadIfRequired(nil)\n\treturn content\n}",
"func (o *ArtifactListerPartialContent) WithPrevious(previous string) *ArtifactListerPartialContent {\n\to.Previous = previous\n\treturn o\n}",
"func newContent() content {\n\treturn content{\n\t\tConsts: make(map[string]Declaration),\n\t\tFuncs: make(map[string]Func),\n\t\tInterfaces: make(map[string]Interface),\n\t\tSimpleTypes: make(map[string]SimpleType),\n\t\tStructs: make(map[string]Struct),\n\t\tVars: make(map[string]Declaration),\n\t}\n}",
"func newListHandler(c client.Client, schema *schema.Schema) http.HandlerFunc {\n\tlistObject, err := forge.List(schema.NewStateObject(), protoregistry.GlobalFiles)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tlistFd := listObject.Descriptor().Fields().Get(0)\n\treturn func(w http.ResponseWriter, r *http.Request) {\n\t\theight, err := getHeight(r)\n\t\tif err != nil {\n\t\t\tbadRequest(w, \"bad height: %s\", err)\n\t\t\treturn\n\t\t}\n\n\t\tq := r.URL.Query()\n\t\tlistOptions := new(ListQueryParams)\n\t\terr = listOptions.UnmarshalURLValues(q)\n\t\tif err != nil {\n\t\t\tbadRequest(w, \"bad query: %s\", err)\n\t\t\treturn\n\t\t}\n\t\topts := []client.ListOption{\n\t\t\tclient.ListRange(listOptions.Start, listOptions.End),\n\t\t}\n\n\t\tif height != 0 {\n\t\t\topts = append(opts, client.ListAtHeight(height))\n\t\t}\n\n\t\tfor _, selection := range listOptions.SelectFields {\n\t\t\tsp := strings.SplitN(selection, \"=\", 2)\n\t\t\tif len(sp) != 2 {\n\t\t\t\tbadRequest(w, \"bad fieldSelection in query %s\", selection)\n\t\t\t\treturn\n\t\t\t}\n\t\t\t// check that index exists\n\t\t\t_, err := schema.Indexer(sp[0])\n\t\t\tif err != nil {\n\t\t\t\tbadRequest(w, \"bad fieldSelection in query: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\topts = append(opts, client.ListMatchFieldString(sp[0], sp[1]))\n\t\t}\n\n\t\titer, err := c.List(schema.NewStateObject(), opts...)\n\t\tif err != nil {\n\t\t\tbadRequest(w, \"unable to list any object: %s\", err)\n\t\t\treturn\n\t\t}\n\t\tdefer iter.Close()\n\n\t\tlist := listObject.New()\n\t\tlistValue := list.NewField(listFd).List()\n\n\t\tfor iter.Valid() {\n\t\t\tobj := schema.NewStateObject()\n\t\t\terr := iter.Get(obj)\n\t\t\tif err != nil {\n\t\t\t\tbadRequest(w, \"unable to list object: %s\", err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tlistValue.Append(protoreflect.ValueOfMessage(obj.ProtoReflect()))\n\t\t\titer.Next()\n\t\t}\n\t\tlist.Set(listFd, protoreflect.ValueOfList(listValue))\n\t\twriteObject(w, list.Interface())\n\t}\n}",
"func generateListVersionsResponse(bucket, prefix, marker, delimiter, encodingType string, maxKeys int, resp ListObjectsInfo) ListVersionsResponse {\n\tvar versions []ObjectVersion\n\tvar prefixes []CommonPrefix\n\tvar owner = Owner{}\n\tvar data = ListVersionsResponse{}\n\n\towner.ID = globalMinioDefaultOwnerID\n\tfor _, object := range resp.Objects {\n\t\tvar content = ObjectVersion{}\n\t\tif object.Name == \"\" {\n\t\t\tcontinue\n\t\t}\n\t\tcontent.Key = s3EncodeName(object.Name, encodingType)\n\t\tcontent.LastModified = object.ModTime.UTC().Format(timeFormatAMZLong)\n\t\tif object.ETag != \"\" {\n\t\t\tcontent.ETag = \"\\\"\" + object.ETag + \"\\\"\"\n\t\t}\n\t\tcontent.Size = object.Size\n\t\tcontent.StorageClass = object.StorageClass\n\t\tcontent.Owner = owner\n\t\tcontent.VersionID = \"null\"\n\t\tcontent.IsLatest = true\n\t\tversions = append(versions, content)\n\t}\n\tdata.Name = bucket\n\tdata.Versions = versions\n\n\tdata.EncodingType = encodingType\n\tdata.Prefix = s3EncodeName(prefix, encodingType)\n\tdata.KeyMarker = s3EncodeName(marker, encodingType)\n\tdata.Delimiter = s3EncodeName(delimiter, encodingType)\n\tdata.MaxKeys = maxKeys\n\n\tdata.NextKeyMarker = s3EncodeName(resp.NextMarker, encodingType)\n\tdata.IsTruncated = resp.IsTruncated\n\n\tfor _, prefix := range resp.Prefixes {\n\t\tvar prefixItem = CommonPrefix{}\n\t\tprefixItem.Prefix = s3EncodeName(prefix, encodingType)\n\t\tprefixes = append(prefixes, prefixItem)\n\t}\n\tdata.CommonPrefixes = prefixes\n\treturn data\n}",
"func (c helmClient) NewLister(flg flags.ListFlags) (Lister, error) {\n\tenvconfig := config.NewEnvConfig(&flg.GlobalFlags)\n\tactionconfig, err := config.NewActionConfig(envconfig, &flg.GlobalFlags)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlist := action.NewList(actionconfig.Configuration)\n\tlist.AllNamespaces = flg.AllNamespaces\n\tlist.Deployed = flg.Deployed\n\tlist.Failed = flg.Failed\n\tlist.Pending = flg.Pending\n\tlist.Uninstalling = flg.Uninstalling\n\tlist.Uninstalled = flg.Uninstalled\n\n\treturn &lister{\n\t\taction: list,\n\t\tenvSettings: envconfig.EnvSettings,\n\t}, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithNext adds the next to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {
o.Next = next
return o
}
|
[
"func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {\n\to.Next = next\n\treturn o\n}",
"func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}",
"func (o *ArtifactListerPartialContent) SetNext(next string) {\n\to.Next = next\n}",
"func (o *ArtifactListerOK) SetNext(next string) {\n\to.Next = next\n}",
"func (i *UploadShrinker) Next() *FileUpload {\n\tvar n int\n\tvar err error\n\n\tif i.Done() {\n\t\treturn nil\n\t}\n\n\tif n, err = i.f.Read(i.buff); err != nil && err != io.EOF {\n\t\ti.err = err\n\t\treturn nil\n\t}\n\n\ti.fu.Chunk = i.chunk\n\ti.fu.Content = i.buff[:n]\n\ti.chunk++\n\n\treturn i.fu\n}",
"func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}",
"func (client DatasetClient) listNextResults(ctx context.Context, lastResults DatasetListResponse) (result DatasetListResponse, err error) {\n req, err := lastResults.datasetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }",
"func (page *DatabaseOperationListResultPage) Next() error {\n\tnext, err := page.fn(page.dolr)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpage.dolr = next\n\treturn nil\n}",
"func (page *ListResultPage) Next() error {\n\treturn page.NextWithContext(context.Background())\n}",
"func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}",
"func (h *HandlersApp01sqVendor) ListNext(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar offset int\n\tvar cTable int\n\n\tlog.Printf(\"hndlrVendor.ListNext(%s)\\n\", r.Method)\n\n\tif r.Method != \"GET\" {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListNext(Error:405) - Not GET\\n\")\n\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Calculate the offset.\n\tcTable, err = h.db.TableCount()\n\tif err != nil {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListLast(Error:400) - %s\\n\", util.ErrorString(err))\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t}\n\toffset, _ = strconv.Atoi(r.FormValue(\"offset\"))\n\toffset += h.rowsPerPage\n\tif offset < 0 || offset > cTable {\n\t\toffset = 0\n\t}\n\n\t// Display the row in the form.\n\th.ListShow(w, offset, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.ListNext()\\n\")\n\n}",
"func (client ApplicationsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"nextLink\": nextLink,\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/{nextLink}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}",
"func (l *EnvironmentList) Next(ctx context.Context, c *Client) error {\n\treturn fmt.Errorf(\"no next page\")\n}",
"func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}",
"func (s Service) Next(msg *Message, data interface{}, useMeta map[string]string) error {\n\terr := msg.RawMessage.Ack(true)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif msg.Chain == nil {\n\t\treturn ErrorChainIsEmpty\n\t}\n\n\tchain := SetCurrentItemSuccess(msg.Chain)\n\n\tnextIndex := getCurrentChainIndex(chain)\n\tif nextIndex == -1 {\n\t\treturn ErrorNextIsNotDefined\n\t}\n\n\tnextElement := chain[nextIndex]\n\n\tmeta := Meta{}\n\tmeta.Merge(msg.Meta, useMeta)\n\n\tvar items []interface{}\n\n\tif nextElement.IsMultiple {\n\t\tval := reflect.ValueOf(data)\n\n\t\tif val.Kind() != reflect.Slice {\n\t\t\treturn ErrorDataIsNotArray\n\t\t}\n\n\t\tfor i := 0; i < val.Len(); i++ {\n\t\t\titems = append(items, val.Index(i).Interface())\n\t\t}\n\t} else {\n\t\titems = append(items, data)\n\t}\n\n\tfor _, item := range items {\n\t\tb, err := json.Marshal(item)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tm := InitialMessage{\n\t\t\tCatch: msg.InitialMessage.Catch,\n\t\t\tConfig: msg.Config,\n\t\t\tMeta: meta,\n\t\t\tChain: chain,\n\t\t\tData: b,\n\t\t}\n\n\t\tif err := s.Publish(m); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (l *Listing) Next() bool {\n\tif l.err != nil {\n\t\treturn false\n\t}\n\tif len(l.objects) > 0 {\n\t\tl.objects = l.objects[:len(l.objects)-1]\n\t}\n\tif len(l.objects) > 0 {\n\t\treturn true\n\t}\n\tif l.nextName == nil {\n\t\treturn false // end of iteration\n\t}\n\n\tdata := map[string]interface{}{\n\t\t\"bucketId\": l.b.ID,\n\t\t\"startFileName\": *l.nextName,\n\t\t\"maxFileCount\": l.nextPageCount,\n\t}\n\tendpoint := \"b2_list_file_names\"\n\tif l.versions {\n\t\tendpoint = \"b2_list_file_versions\"\n\t}\n\tif l.nextID != nil && *l.nextID != \"\" {\n\t\tdata[\"startFileId\"] = *l.nextID\n\t}\n\tr, err := l.b.c.doRequest(endpoint, data)\n\tif err != nil {\n\t\tl.err = err\n\t\treturn false\n\t}\n\tdefer drainAndClose(r.Body)\n\n\tvar x struct {\n\t\tFiles []fileInfoObj\n\t\tNextFileName *string\n\t\tNextFileID *string\n\t}\n\tif l.err = json.NewDecoder(r.Body).Decode(&x); l.err != nil {\n\t\treturn false\n\t}\n\n\tl.objects = make([]*FileInfo, len(x.Files))\n\tfor i, f := range x.Files {\n\t\tl.objects[len(l.objects)-1-i] = f.makeFileInfo()\n\t}\n\tl.nextName, l.nextID = x.NextFileName, x.NextFileID\n\treturn len(l.objects) > 0\n}",
"func (client UsageDetailsClient) listByDepartmentNextResults(ctx context.Context, lastResults UsageDetailsListResult) (result UsageDetailsListResult, err error) {\n\treq, err := lastResults.usageDetailsListResultPreparer(ctx)\n\tif err != nil {\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", nil, \"Failure preparing next results request\")\n\t}\n\tif req == nil {\n\t\treturn\n\t}\n\tresp, err := client.ListByDepartmentSender(req)\n\tif err != nil {\n\t\tresult.Response = autorest.Response{Response: resp}\n\t\treturn result, autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", resp, \"Failure sending next results request\")\n\t}\n\tresult, err = client.ListByDepartmentResponder(resp)\n\tif err != nil {\n\t\terr = autorest.NewErrorWithError(err, \"consumption.UsageDetailsClient\", \"listByDepartmentNextResults\", resp, \"Failure responding to next results request\")\n\t}\n\treturn\n}",
"func (f *FrontPage) next() *Article {\n\ta := &Article{SnapshotID: f.SnapshotID}\n\treturn a\n}",
"func (l *Headers) SetNext(h http.Handler) {\n\tl.next = h\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetNext sets the next to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) SetNext(next string) {
o.Next = next
}
|
[
"func (o *ArtifactListerOK) SetNext(next string) {\n\to.Next = next\n}",
"func (o *ArtifactListerPartialContent) WithNext(next string) *ArtifactListerPartialContent {\n\to.Next = next\n\treturn o\n}",
"func (o *ArtifactListerOK) WithNext(next string) *ArtifactListerOK {\n\to.Next = next\n\treturn o\n}",
"func (rl *ResourceList) next() error {\n\tif rl.Page == rl.NumPages-1 {\n\t\treturn errors.New(\"no more new pages\")\n\t}\n\treturn common.SendGetRequest(rl.NextPageURI, *rl.act, rl)\n}",
"func (h *Sagify) SetNext(next job.Handler) {\n\th.next = next\n}",
"func (l *Headers) SetNext(h http.Handler) {\n\tl.next = h\n}",
"func (g *GZipper) SetNext(h http.Handler) {\n\tg.next = h\n}",
"func (o *StdOutOutput) SetNext(next Output) {\n\to.next = next\n}",
"func (f *MutateFilter) SetNext(next Filter) {\n\tf.next = next\n}",
"func (bce *BaseCompositeEndpoint) SetNext(next CompositeEndpoint) CompositeEndpoint {\n\tif bce.self == nil {\n\t\tlogrus.Fatal(\"Any struct that edtends BaseCompositeEndpoint should have 'self' set. Consider using SetSelf().\")\n\t}\n\tbce.next = next\n\treturn bce.self\n}",
"func (s *Links) SetNext(val OptString) {\n\ts.Next = val\n}",
"func (c *Client) Next() goa.Endpoint {\n\tvar (\n\t\tdecodeResponse = DecodeNextResponse(c.decoder, c.RestoreResponseBody)\n\t)\n\treturn func(ctx context.Context, v interface{}) (interface{}, error) {\n\t\treq, err := c.BuildNextRequest(ctx, v)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tresp, err := c.NextDoer.Do(req)\n\t\tif err != nil {\n\t\t\treturn nil, goahttp.ErrRequestError(\"spin-broker\", \"next\", err)\n\t\t}\n\t\treturn decodeResponse(resp)\n\t}\n}",
"func (p *page) SetNext(id txfile.PageID) {\n\thdr := castEventPageHeader(p.Data)\n\thdr.next.Set(uint64(id))\n}",
"func (iter *ResourceListResultIterator) Next() error {\n\titer.i++\n\tif iter.i < len(iter.page.Values()) {\n\t\treturn nil\n\t}\n\terr := iter.page.Next()\n\tif err != nil {\n\t\titer.i--\n\t\treturn err\n\t}\n\titer.i = 0\n\treturn nil\n}",
"func (client ApplicationsClient) ListNextPreparer(ctx context.Context, nextLink string) (*http.Request, error) {\n\tpathParameters := map[string]interface{}{\n\t\t\"nextLink\": nextLink,\n\t\t\"tenantID\": autorest.Encode(\"path\", client.TenantID),\n\t}\n\n\tconst APIVersion = \"1.6\"\n\tqueryParameters := map[string]interface{}{\n\t\t\"api-version\": APIVersion,\n\t}\n\n\tpreparer := autorest.CreatePreparer(\n\t\tautorest.AsGet(),\n\t\tautorest.WithBaseURL(client.BaseURI),\n\t\tautorest.WithPathParameters(\"/{tenantID}/{nextLink}\", pathParameters),\n\t\tautorest.WithQueryParameters(queryParameters))\n\treturn preparer.Prepare((&http.Request{}).WithContext(ctx))\n}",
"func (client DatasetClient) listNextResults(ctx context.Context, lastResults DatasetListResponse) (result DatasetListResponse, err error) {\n req, err := lastResults.datasetListResponsePreparer(ctx)\n if err != nil {\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", nil , \"Failure preparing next results request\")\n }\n if req == nil {\n return\n }\n resp, err := client.ListSender(req)\n if err != nil {\n result.Response = autorest.Response{Response: resp}\n return result, autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure sending next results request\")\n }\n result, err = client.ListResponder(resp)\n if err != nil {\n err = autorest.NewErrorWithError(err, \"creator.DatasetClient\", \"listNextResults\", resp, \"Failure responding to next results request\")\n }\n return\n }",
"func (p *Playlist) Next() {\n\tp.ch <- \"next\"\n}",
"func (c *layerCache) setNext(next Layer) error {\n\tc.next = next\n\treturn nil\n}",
"func (c *Client) next() (rsp *Response, err error) {\n\traw, err := c.r.Next()\n\tif err == nil {\n\t\trsp, err = raw.Parse()\n\t}\n\treturn\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPrevious adds the previous to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) WithPrevious(previous string) *ArtifactListerPartialContent {
o.Previous = previous
return o
}
|
[
"func (o *ArtifactListerOK) WithPrevious(previous string) *ArtifactListerOK {\n\to.Previous = previous\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (o *ArtifactListerOK) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (c *Client) PlaylistPrevious() error {\n\t_, err := c.Exec(\"playlist-prev\", \"weak\")\n\treturn err\n}",
"func (app *builder) WithPrevious(prev Government) Builder {\n\tapp.prev = prev\n\treturn app\n}",
"func (lr *ListResponse) HasPrevious() bool {\n\tif lr.currentIndex == 0 {\n\t\treturn false\n\t}\n\treturn true\n}",
"func (h *HandlersApp01sqVendor) ListPrev(w http.ResponseWriter, r *http.Request) {\n\tvar err error\n\tvar offset int\n\tvar begin int\n\tvar cTable int\n\n\tlog.Printf(\"hndlrVendor.ListPrev(%s, %s)\\n\", r.Method, r.FormValue(\"offset\"))\n\n\tif r.Method != \"GET\" {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListPrev(Error:405) - Not GET\\n\")\n\n\t\thttp.Error(w, http.StatusText(405), http.StatusMethodNotAllowed)\n\t\treturn\n\t}\n\n\t// Calculate the offset.\n\tcTable, err = h.db.TableCount()\n\tif err != nil {\n\n\t\tlog.Printf(\"...end hndlrVendor.ListLast(Error:400) - %s\\n\", util.ErrorString(err))\n\n\t\thttp.Error(w, http.StatusText(400), http.StatusBadRequest)\n\t}\n\tbegin, _ = strconv.Atoi(r.FormValue(\"offset\"))\n\toffset = begin - h.rowsPerPage\n\tif offset < 0 {\n\t\tif begin > 0 {\n\t\t\toffset = 0\n\t\t} else {\n\t\t\toffset = cTable - h.rowsPerPage\n\t\t\tif offset < 0 {\n\t\t\t\toffset = 0\n\t\t\t}\n\t\t}\n\t}\n\n\t// Display the row in the form.\n\th.ListShow(w, offset, \"\")\n\n\tlog.Printf(\"...end hndlrVendor.ListPrev()\\n\")\n\n}",
"func NextPrev(w http.ResponseWriter, r *http.Request) {\n\tfmt.Println(\"Received Request: /MediaControls\")\n\taction := strings.TrimPrefix(r.URL.Path, \"/MediaControls/\")\n\tfmt.Println(\"Action:\", action)\n\n\tvar URL *url.URL\n\tURL, err := url.Parse(\"https://api.spotify.com\")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tURL.Path += \"/v1/me/player\"\n\n\tclient := &http.Client{}\n\n\tswitch action {\n\tcase \"Next\":\n\t\tURL.Path += \"/next\"\n\tcase \"Previous\":\n\t\tURL.Path += \"/previous\"\n\t}\n\n\treq, err := http.NewRequest(\"POST\", URL.String(), nil)\n\treq.Header.Set(\"Accept\", \"application/json\")\n\treq.Header.Set(\"Content-Type\", \"application/json\")\n\treq.Header.Set(\"Authorization\", \"Bearer \"+sAcsTok.AccessToken)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\t_, err = client.Do(req)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n}",
"func (r Response) Prev() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"prev\",\n\t}\n}",
"func (ref *UIElement) PreviousContents() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(PreviousContentsAttribute)\n}",
"func WithPrev(prev *url.URL) Opt {\n\treturn func(opts *Options) {\n\t\topts.Prev = prev\n\t}\n}",
"func (e *ListElement) Previous() *ListElement {\n\treturn (*ListElement)(atomic.LoadPointer(&e.previousElement))\n}",
"func (r AboutRequester) PreviousDeployment() (*Deployment, error) {\n\towner := \"jacobpatterson1549\"\n\trepo := \"nate-mlb\"\n\turi := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/deployments\", owner, repo)\n\tvar s githubRepoDeployments\n\terr := r.requester.structPointerFromURI(uri, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.previousDeployment(r.environment), nil\n}",
"func (el *Element) Previous() *Element {\n\tparent, err := el.PreviousE()\n\tkit.E(err)\n\treturn parent\n}",
"func Prev(hs ...Handler) {\n\trouterIns.prev = append(routerIns.prev, hs...)\n}",
"func (it *insertIterator) previous() *types.Header {\n\tif it.index < 1 {\n\t\treturn nil\n\t}\n\treturn it.chain[it.index-1].Header()\n}",
"func (app *folderNameBuilder) IsPrevious() FolderNameBuilder {\n\tapp.isPrevious = true\n\treturn app\n}",
"func (a *Art) SavePrevious(b *Buf) {\n\tif a.Page.AnsSave == \"on\" {\n\t\tb.ArrStr1 = append(append(b.ArrStr1, \" \"), a.Page.AnsWeb...)\n\t\tb.ArrStr2 = append(append(b.ArrStr2, \" \"), a.Page.AnsFile...)\n\t}\n\ta.Page.AnsWeb = b.ArrStr1\n\ta.Page.AnsFile = b.ArrStr2\n}",
"func (o *PaginatedChangeset) SetPrevious(v string) {\n\to.Previous = &v\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPrevious sets the previous to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) SetPrevious(previous string) {
o.Previous = previous
}
|
[
"func (o *ArtifactListerOK) SetPrevious(previous string) {\n\to.Previous = previous\n}",
"func (o *ArtifactListerPartialContent) WithPrevious(previous string) *ArtifactListerPartialContent {\n\to.Previous = previous\n\treturn o\n}",
"func (o *ArtifactListerOK) WithPrevious(previous string) *ArtifactListerOK {\n\to.Previous = previous\n\treturn o\n}",
"func (o *PaginatedChangeset) SetPrevious(v string) {\n\to.Previous = &v\n}",
"func (m *Mutation) SetPrevious(oldValueRevision uint64, oldValue []byte, copyPrevious bool) error {\n\tprevSignedEntry, err := FromLeafValue(oldValue)\n\tif err != nil {\n\t\treturn err\n\t}\n\tm.prevRev = oldValueRevision\n\tm.prevSignedEntry = prevSignedEntry\n\n\thash := sha256.Sum256(prevSignedEntry.GetEntry())\n\tm.entry.Previous = hash[:]\n\n\tvar prevEntry pb.Entry\n\tif err := proto.Unmarshal(prevSignedEntry.GetEntry(), &prevEntry); err != nil {\n\t\treturn err\n\t}\n\tif copyPrevious {\n\t\tm.entry.AuthorizedKeyset = prevEntry.GetAuthorizedKeyset()\n\t\tm.entry.Commitment = prevEntry.GetCommitment()\n\t}\n\treturn nil\n}",
"func (c *Client) PlaylistPrevious() error {\n\t_, err := c.Exec(\"playlist-prev\", \"weak\")\n\treturn err\n}",
"func (e *RepoEntity) PreviousCommit() {\n\te.Commit = e.Commits[(len(e.Commits)+e.currentCommitIndex()-1)%len(e.Commits)]\n}",
"func (r AboutRequester) PreviousDeployment() (*Deployment, error) {\n\towner := \"jacobpatterson1549\"\n\trepo := \"nate-mlb\"\n\turi := fmt.Sprintf(\"https://api.github.com/repos/%s/%s/deployments\", owner, repo)\n\tvar s githubRepoDeployments\n\terr := r.requester.structPointerFromURI(uri, &s)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn s.previousDeployment(r.environment), nil\n}",
"func (c *Collection) SetPrevSpec(s types.Spec) {\n\tc.writeTxn(func() error {\n\t\tcopy := s\n\t\tc.previous = ©\n\t\treturn nil\n\t})\n}",
"func (r Response) Prev() Command {\n\treturn Command{\n\t\tJID: r.IQ.From,\n\t\tSID: r.SID,\n\t\tNode: r.Node,\n\t\tAction: \"prev\",\n\t}\n}",
"func (e *RepoEntity) PreviousRemote() error {\n\te.Remote = e.Remotes[(len(e.Remotes)+e.currentRemoteIndex()-1)%len(e.Remotes)]\n\te.Remote.SyncBranches(e.Branch.Name)\n\treturn e.Publish(RepositoryUpdated, nil)\n}",
"func (c *CompletionManager) Previous() {\n\tif c.verticalScroll == c.selected && c.selected > 0 {\n\t\tc.verticalScroll--\n\t}\n\tc.selected--\n\tc.update()\n}",
"func (a *Art) SavePrevious(b *Buf) {\n\tif a.Page.AnsSave == \"on\" {\n\t\tb.ArrStr1 = append(append(b.ArrStr1, \" \"), a.Page.AnsWeb...)\n\t\tb.ArrStr2 = append(append(b.ArrStr2, \" \"), a.Page.AnsFile...)\n\t}\n\ta.Page.AnsWeb = b.ArrStr1\n\ta.Page.AnsFile = b.ArrStr2\n}",
"func (e *ListElement) Previous() *ListElement {\n\treturn (*ListElement)(atomic.LoadPointer(&e.previousElement))\n}",
"func (l *SyncList) Prev() {\n\tif l.cursor > 0 {\n\t\tl.cursor--\n\t}\n\n\tif l.start > l.cursor {\n\t\tl.start = l.cursor\n\t}\n}",
"func (el *Element) Previous() *Element {\n\tparent, err := el.PreviousE()\n\tkit.E(err)\n\treturn parent\n}",
"func (ref *UIElement) PreviousContents() []*UIElement {\n\treturn ref.SliceOfUIElementAttr(PreviousContentsAttribute)\n}",
"func (p *Player) Previous() *dbus.Error {\n\treturn nil\n}",
"func (r *Raft) setPreviousLog(req *pb.AppendEntriesRequest, nextIndex uint64) error {\n\t// Guard for the first index, since there is no 0 log entry\n\t// Guard against the previous index being a snapshot as well\n\tlastSnapIdx, lastSnapTerm := r.getLastSnapshot()\n\tif nextIndex == 1 {\n\t\treq.PrevLogIndex = 0\n\t\treq.PrevLogTerm = 0\n\t} else if (nextIndex - 1) == lastSnapIdx {\n\t\treq.PrevLogIndex = lastSnapIdx\n\t\treq.PrevLogTerm = lastSnapTerm\n\t} else {\n\t\tvar l pb.Log\n\t\tif err := r.logs.GetLog(nextIndex-1, &l); err != nil {\n\t\t\tklog.Errorf(fmt.Sprintf(\"failed to get log index:%d err:%v\", nextIndex-1, err))\n\t\t\treturn err\n\t\t}\n\n\t\t// Set the previous index and term (0 if nextIndex is 1)\n\t\treq.PrevLogIndex = l.Index\n\t\treq.PrevLogTerm = l.Term\n\t}\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithRemainingRecords adds the remainingRecords to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {
o.RemainingRecords = remainingRecords
return o
}
|
[
"func (o *ArtifactListerPartialContent) SetRemainingRecords(remainingRecords uint64) {\n\to.RemainingRecords = remainingRecords\n}",
"func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (app *builder) WithRemaining(remaining string) Builder {\n\tapp.remaining = remaining\n\treturn app\n}",
"func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func WithIncludeFinal(includeFinal bool) ListDealRecordsOption {\n\treturn func(c *rpc.ListDealRecordsConfig) {\n\t\tc.IncludeFinal = includeFinal\n\t}\n}",
"func (a *EarnUniApiService) ListUniLendRecords(ctx context.Context, localVarOptionals *ListUniLendRecordsOpts) ([]UniLendRecord, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []UniLendRecord\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/earn/uni/lend_records\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Currency.IsSet() {\n\t\tlocalVarQueryParams.Add(\"currency\", parameterToString(localVarOptionals.Currency.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Page.IsSet() {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Limit.IsSet() {\n\t\tlocalVarQueryParams.Add(\"limit\", parameterToString(localVarOptionals.Limit.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Type_.IsSet() {\n\t\tlocalVarQueryParams.Add(\"type\", parameterToString(localVarOptionals.Type_.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\"}\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 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 + \", \" + 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 localVarReturnValue, localVarHTTPResponse, gateErr\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 responderArtifact206(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerPartialContent) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\n\tresponder = artifacts.NewArtifactListerPartialContent()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tresponder.SetRemainingRecords(listInfo.RemainingRecords)\n\n\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\tartifactListerURL.After = &tmp\n\n\tif defaultPageLimit != paginator.Limit {\n\t\ttmp := paginator.Limit\n\t\tartifactListerURL.Limit = &tmp\n\t}\n\tresponder.SetNext(artifactListerURL.String())\n\n\tif paginator.ID != 0 { //... and not the first\n\t\t//paginator.ID is from query parameter not artifactmanager\n\t\tvar artifactListerURL artifacts.ArtifactListerURL\n\t\ttmp = artifactInfoReturned[0].ID\n\t\tartifactListerURL.Before = &tmp\n\t\tif defaultPageLimit != paginator.Limit {\n\t\t\ttmp := paginator.Limit\n\t\t\tartifactListerURL.Limit = &tmp\n\t\t}\n\t\tresponder.SetPrevious(artifactListerURL.String())\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func (_obj *DataService) GetActivityRecords(index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"getActivityRecords\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _is.Read_int32(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i20, e20 := int32(0), length; i20 < e20; i20++ {\n\n\t\t\terr = (*recordList)[i20].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}",
"func showRemainingBalance(res http.ResponseWriter, req *http.Request) {\n\ttype balanceStruct struct {\n\t\tItem string\n\t\tQuantity float64\n\t}\n\n\tvar itemData []balanceStruct\n\n\tfor i := 0; i < len(ds.Items); i++ {\n\t\tremainingQuantity := ds.Items[i].WeeklyCapacity - ds.Items[i].WeeklyOrder\n\t\td := balanceStruct{\n\t\t\tItem: ds.Items[i].Name,\n\t\t\tQuantity: remainingQuantity}\n\t\titemData = append(itemData, d)\n\t}\n\n\terr := tpl.ExecuteTemplate(res, \"itemBalance.gohtml\", itemData)\n\tif err != nil {\n\t\thttp.Error(res, err.Error(), http.StatusBadRequest)\n\t\tlog.Error(\"Error at itemBalance template.\", err)\n\t\treturn\n\t}\n}",
"func (_obj *DataService) GetActivityRecordsWithContext(tarsCtx context.Context, index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"getActivityRecords\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _is.Read_int32(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i21, e21 := int32(0), length; i21 < e21; i21++ {\n\n\t\t\terr = (*recordList)[i21].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}",
"func (rs *RuleSpec) fillRemaining() {\n\tlength := len(rs.RuleParameters)\n\tfor i, rp := range rs.RuleParameters {\n\t\trp.Remaining = length - i -1\n\t}\n}",
"func (*ListNSRecordsAfterVersionResponse) Descriptor() ([]byte, []int) {\n\treturn file_service_ns_record_proto_rawDescGZIP(), []int{10}\n}",
"func (s *statusCollector) fillRemaining(err error) {\n\t// Amount of times certain recipient was specified is indicated by the channel\n\t// buffer size, so once we fill it, we can be confident that we sent\n\t// at least as much statuses as needed. Extra statuses will be ignored anyway.\nchLoop:\n\tfor _, ch := range s.statusMap {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ch <- err:\n\t\t\tdefault:\n\t\t\t\tcontinue chLoop\n\t\t\t}\n\t\t}\n\t}\n}",
"func (s *ContainerInstance) SetRemainingResources(v []*Resource) *ContainerInstance {\n\ts.RemainingResources = v\n\treturn s\n}",
"func (o *ArtifactListerPartialContent) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerPartialContent {\n\to.Payload = payload\n\treturn o\n}",
"func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *pb.QueryResponseMetadata) *bytes.Buffer {\n\n buffer.WriteString(\"[{\\\"ResponseMetadata\\\":{\\\"RecordsCount\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(fmt.Sprintf(\"%v\", responseMetadata.FetchedRecordsCount))\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(\", \\\"Bookmark\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(responseMetadata.Bookmark)\n buffer.WriteString(\"\\\"}}]\")\n\n return buffer\n}",
"func RateLimitRemaining(r *http.Response) int {\n\treturn intResponseHeaderOrNegOne(r, \"X-RateLimit-Remaining\")\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetRemainingRecords sets the remainingRecords to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) SetRemainingRecords(remainingRecords uint64) {
o.RemainingRecords = remainingRecords
}
|
[
"func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {\n\to.RemainingRecords = remainingRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (s *ContainerInstance) SetRemainingResources(v []*Resource) *ContainerInstance {\n\ts.RemainingResources = v\n\treturn s\n}",
"func (rs *RuleSpec) fillRemaining() {\n\tlength := len(rs.RuleParameters)\n\tfor i, rp := range rs.RuleParameters {\n\t\trp.Remaining = length - i -1\n\t}\n}",
"func (rl RecordList) ResetRecords(tb *TableBlock) {\n\tif len(rl) <= 0 {\n\t\treturn\n\t}\n\n\t// Fast recycle means that we only reset record.Populated\n\t// this saves time when querying tables with lots of columns\n\tif !FLAGS.FAST_RECYCLE {\n\t\tfor _, record := range rl {\n\t\t\tif record.Ints != nil {\n\t\t\t\tfor i := range record.Ints {\n\t\t\t\t\trecord.Ints[i] = 0\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif record.Strs != nil {\n\t\t\t\tfor i := range record.Strs {\n\t\t\t\t\trecord.Strs[i] = 0\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, record := range rl {\n\t\tif record.SetMap != nil {\n\t\t\trecord.SetMap = make(SetMap)\n\t\t}\n\n\t\tfor i := range record.Populated {\n\t\t\trecord.Populated[i] = _NO_VAL\n\t\t}\n\n\t\trecord.block = tb\n\t}\n\n}",
"func (cl *Client) failBufferedRecords(err error) {\n\tp := &cl.producer\n\n\tfor _, partitions := range p.topics.load() {\n\t\tfor _, partition := range partitions.load().partitions {\n\t\t\trecBuf := partition.records\n\t\t\trecBuf.mu.Lock()\n\t\t\trecBuf.failAllRecords(err)\n\t\t\trecBuf.mu.Unlock()\n\t\t}\n\t}\n\n\tp.topicsMu.Lock()\n\tdefer p.topicsMu.Unlock()\n\tp.unknownTopicsMu.Lock()\n\tdefer p.unknownTopicsMu.Unlock()\n\n\ttoStore := p.topics.clone()\n\tdefer p.topics.storeData(toStore)\n\n\tvar toFail [][]promisedRec\n\tfor topic, unknown := range p.unknownTopics {\n\t\tdelete(toStore, topic)\n\t\tdelete(p.unknownTopics, topic)\n\t\tclose(unknown.wait)\n\t\ttoFail = append(toFail, unknown.buffered)\n\t}\n\n\tgo func() {\n\t\tfor _, fail := range toFail {\n\t\t\tfor _, pr := range fail {\n\t\t\t\tcl.finishRecordPromise(pr, err)\n\t\t\t}\n\t\t}\n\t}()\n}",
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (a *EarnUniApiService) ListUniLendRecords(ctx context.Context, localVarOptionals *ListUniLendRecordsOpts) ([]UniLendRecord, *http.Response, error) {\n\tvar (\n\t\tlocalVarHTTPMethod = http.MethodGet\n\t\tlocalVarPostBody interface{}\n\t\tlocalVarFormFileName string\n\t\tlocalVarFileName string\n\t\tlocalVarFileBytes []byte\n\t\tlocalVarReturnValue []UniLendRecord\n\t)\n\n\t// create path and map variables\n\tlocalVarPath := a.client.cfg.BasePath + \"/earn/uni/lend_records\"\n\tlocalVarHeaderParams := make(map[string]string)\n\tlocalVarQueryParams := url.Values{}\n\tlocalVarFormParams := url.Values{}\n\n\tif localVarOptionals != nil && localVarOptionals.Currency.IsSet() {\n\t\tlocalVarQueryParams.Add(\"currency\", parameterToString(localVarOptionals.Currency.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Page.IsSet() {\n\t\tlocalVarQueryParams.Add(\"page\", parameterToString(localVarOptionals.Page.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Limit.IsSet() {\n\t\tlocalVarQueryParams.Add(\"limit\", parameterToString(localVarOptionals.Limit.Value(), \"\"))\n\t}\n\tif localVarOptionals != nil && localVarOptionals.Type_.IsSet() {\n\t\tlocalVarQueryParams.Add(\"type\", parameterToString(localVarOptionals.Type_.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\"}\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 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 + \", \" + 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 localVarReturnValue, localVarHTTPResponse, gateErr\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 *statusCollector) fillRemaining(err error) {\n\t// Amount of times certain recipient was specified is indicated by the channel\n\t// buffer size, so once we fill it, we can be confident that we sent\n\t// at least as much statuses as needed. Extra statuses will be ignored anyway.\nchLoop:\n\tfor _, ch := range s.statusMap {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase ch <- err:\n\t\t\tdefault:\n\t\t\t\tcontinue chLoop\n\t\t\t}\n\t\t}\n\t}\n}",
"func (m *MeetingAttendanceReport) SetAttendanceRecords(value []AttendanceRecordable)() {\n m.attendanceRecords = value\n}",
"func (nsc *NilConsumerStatsCollector) UpdateGetRecordsReadResponseDuration(time.Duration) {}",
"func (p *Provider) SetRecords(ctx context.Context, zone string, records []libdns.Record) ([]libdns.Record, error) {\n\tp.mutex.Lock()\n\tdefer p.mutex.Unlock()\n\n\tclient := &http.Client{}\n\n\tvar updatedRecords []libdns.Record\n\n\tvar resourceRecordSets []LeasewebRecordSet\n\n\tfor _, record := range records {\n\n\t\trecordSet := LeasewebRecordSet{\n\t\t\tName: record.Name,\n\t\t\tType: record.Type,\n\t\t\tContent: []string{record.Value},\n\t\t\tTTL: int(record.TTL.Seconds()),\n\t\t}\n\n\t\tresourceRecordSets = append(resourceRecordSets, recordSet)\n\n\t\tupdatedRecords = append(updatedRecords, record)\n\t}\n\n\tbody := &LeasewebRecordSets{\n\t\tResourceRecordSets: resourceRecordSets,\n\t}\n\n\tbodyBuffer := new(bytes.Buffer)\n\tjson.NewEncoder(bodyBuffer).Encode(body)\n\n\treq, err := http.NewRequest(http.MethodPut, fmt.Sprintf(\"https://api.leaseweb.com/hosting/v2/domains/%s/resourceRecordSets\", zone), bodyBuffer)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treq.Header.Add(LeasewebApiKeyHeader, p.APIKey)\n\n\tres, err := client.Do(req)\n\tdefer res.Body.Close()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif res.StatusCode < 200 || res.StatusCode > 299 {\n\t\treturn nil, fmt.Errorf(\"Received StatusCode %d from Leaseweb API\", res.StatusCode)\n\t}\n\n\treturn updatedRecords, nil\n}",
"func (c *Conn) setReadRemaining(n int64) error {\n\tif n < 0 {\n\t\treturn ErrReadLimit\n\t}\n\n\tc.readRemaining = n\n\treturn nil\n}",
"func ResetRecords(resources *[]shaman.Resource) error {\n\tif storage == nil {\n\t\treturn nil\n\t}\n\tfor i := range *resources {\n\t\t(*resources)[i].Validate()\n\t}\n\n\treturn storage.resetRecords(*resources)\n}",
"func (_obj *DataService) GetActivityRecords(index int32, batch int32, activity_id string, nextIndex *int32, recordList *[]ActivityRecord, _opt ...map[string]string) (ret int32, err error) {\n\n\tvar length int32\n\tvar have bool\n\tvar ty byte\n\t_os := codec.NewBuffer()\n\terr = _os.Write_int32(index, 1)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(batch, 2)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_string(activity_id, 3)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32((*nextIndex), 4)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.WriteHead(codec.LIST, 5)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _os.Write_int32(int32(len((*recordList))), 0)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tfor _, v := range *recordList {\n\n\t\terr = v.WriteBlock(_os, 0)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tvar _status map[string]string\n\tvar _context map[string]string\n\tif len(_opt) == 1 {\n\t\t_context = _opt[0]\n\t} else if len(_opt) == 2 {\n\t\t_context = _opt[0]\n\t\t_status = _opt[1]\n\t}\n\t_resp := new(requestf.ResponsePacket)\n\ttarsCtx := context.Background()\n\n\terr = _obj.s.Tars_invoke(tarsCtx, 0, \"getActivityRecords\", _os.ToBytes(), _status, _context, _resp)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\t_is := codec.NewReader(tools.Int8ToByte(_resp.SBuffer))\n\terr = _is.Read_int32(&ret, 0, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr = _is.Read_int32(&(*nextIndex), 4, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\terr, have, ty = _is.SkipToNoCheck(5, true)\n\tif err != nil {\n\t\treturn ret, err\n\t}\n\n\tif ty == codec.LIST {\n\t\terr = _is.Read_int32(&length, 0, true)\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t\t(*recordList) = make([]ActivityRecord, length)\n\t\tfor i20, e20 := int32(0), length; i20 < e20; i20++ {\n\n\t\t\terr = (*recordList)[i20].ReadBlock(_is, 0, false)\n\t\t\tif err != nil {\n\t\t\t\treturn ret, err\n\t\t\t}\n\n\t\t}\n\t} else if ty == codec.SIMPLE_LIST {\n\t\terr = fmt.Errorf(\"not support simple_list type\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t} else {\n\t\terr = fmt.Errorf(\"require vector, but not\")\n\t\tif err != nil {\n\t\t\treturn ret, err\n\t\t}\n\n\t}\n\n\tif len(_opt) == 1 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t} else if len(_opt) == 2 {\n\t\tfor k := range _context {\n\t\t\tdelete(_context, k)\n\t\t}\n\t\tfor k, v := range _resp.Context {\n\t\t\t_context[k] = v\n\t\t}\n\t\tfor k := range _status {\n\t\t\tdelete(_status, k)\n\t\t}\n\t\tfor k, v := range _resp.Status {\n\t\t\t_status[k] = v\n\t\t}\n\n\t}\n\t_ = length\n\t_ = have\n\t_ = ty\n\treturn ret, nil\n}",
"func (lp *LoadPoint) setRemainingDuration(chargeRemainingDuration time.Duration) {\n\tlp.Lock()\n\tdefer lp.Unlock()\n\n\tif lp.chargeRemainingDuration != chargeRemainingDuration {\n\t\tlp.chargeRemainingDuration = chargeRemainingDuration\n\t\tlp.publish(\"chargeRemainingDuration\", chargeRemainingDuration)\n\t}\n}",
"func RateLimitRemaining(r *http.Response) int {\n\treturn intResponseHeaderOrNegOne(r, \"X-RateLimit-Remaining\")\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithTotalRecords adds the totalRecords to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {
o.TotalRecords = totalRecords
return o
}
|
[
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {\n\to.RemainingRecords = remainingRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetRemainingRecords(remainingRecords uint64) {\n\to.RemainingRecords = remainingRecords\n}",
"func (g *GlobalResponse) Sum() {\n\tsum := 0\n\n\tfor _, v := range g.Records {\n\t\tsum += v.Fields.NumBikesAvailable\n\t}\n\n\tg.Total = sum\n}",
"func (rest *RestController) All(w http.ResponseWriter, r *http.Request) (Response, error) {\n\tresources := reflect.New(reflect.SliceOf(reflect.TypeOf(rest.Table).Elem()))\n\tcount, err := rest.Table.List(resources.Interface(), models.NewDBQuery(r.URL.Query(), nil))\n\tif err != nil {\n\t\treturn nil, &httpError{err, \"\", 500}\n\t}\n\tw.Header().Set(\"Total\", strconv.FormatInt(count, 10))\n\treturn &JSONResponse{resources.Interface(), 200}, nil\n}",
"func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *sc.QueryResponseMetadata) *bytes.Buffer {\n\n\tbuffer.WriteString(\"[{\\\"ResponseMetadata\\\":{\\\"RecordsCount\\\":\")\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(fmt.Sprintf(\"%v\", responseMetadata.FetchedRecordsCount))\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(\", \\\"Bookmark\\\":\")\n\tbuffer.WriteString(\"\\\"\")\n\tbuffer.WriteString(responseMetadata.Bookmark)\n\tbuffer.WriteString(\"\\\"}}]\")\n\n\treturn buffer\n}",
"func outputRecordsAll(cmd *cobra.Command) error {\n\tclientCtx, err := client.GetClientQueryContext(cmd)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpageReq, e := client.ReadPageRequest(withPageKeyDecoded(cmd.Flags()))\n\tif e != nil {\n\t\treturn e\n\t}\n\tqueryClient := types.NewQueryClient(clientCtx)\n\tres, err := queryClient.RecordsAll(\n\t\tcontext.Background(),\n\t\t&types.RecordsAllRequest{Pagination: pageReq},\n\t)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif !includeRequest {\n\t\tres.Request = nil\n\t}\n\n\treturn clientCtx.PrintProto(res)\n}",
"func addPaginationMetadataToQueryResults(buffer *bytes.Buffer, responseMetadata *pb.QueryResponseMetadata) *bytes.Buffer {\n\n buffer.WriteString(\"[{\\\"ResponseMetadata\\\":{\\\"RecordsCount\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(fmt.Sprintf(\"%v\", responseMetadata.FetchedRecordsCount))\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(\", \\\"Bookmark\\\":\")\n buffer.WriteString(\"\\\"\")\n buffer.WriteString(responseMetadata.Bookmark)\n buffer.WriteString(\"\\\"}}]\")\n\n return buffer\n}",
"func (rb *ShardsRecordBuilder) FlushTotal(flushtotal string) *ShardsRecordBuilder {\n\trb.v.FlushTotal = &flushtotal\n\treturn rb\n}",
"func (this *BaseController) OnResultsWithTotalCountAny(viewName string, results interface{}, totalCount int64) {\n\n\tif this.IsJson() {\n\t\tthis.OnJsonResultsWithTotalCount(results, totalCount)\n\t} else {\n\t\tthis.OnResultsWithTotalCount(viewName, results, totalCount)\n\t}\n\n}",
"func (r *MachinePoolsListServerResponse) Total(value int) *MachinePoolsListServerResponse {\n\tr.total = &value\n\treturn r\n}",
"func (nsc *NilConsumerStatsCollector) AddGetRecordsCalled(int) {}",
"func (d *DBClient) RecordsCount(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tcount, err := d.Cache.RecordsCount()\n\n\tif err == nil {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tvar response recordsCount\n\t\tresponse.Count = count\n\t\tb, err := json.Marshal(response)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Error\": err.Error(),\n\t\t}).Error(\"Failed to get data from cache!\")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(500) // can't process this entity\n\t\treturn\n\t}\n}",
"func (resp *DomainRecordsPagedResponse) appendData(r *DomainRecordsPagedResponse) {\n\tresp.Data = append(resp.Data, r.Data...)\n}",
"func (dsc *DefaultConsumerStatsCollector) AddGetRecordsCalled(count int) {\n\tdsc.GetRecordsCalled.Inc(int64(count))\n}",
"func (d *DBClient) AllRecordsHandler(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\trecords, err := d.Cache.GetAllRequests()\n\n\tif err == nil {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tvar response recordedRequests\n\t\tresponse.Data = records\n\t\tb, err := json.Marshal(response)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Error\": err.Error(),\n\t\t}).Error(\"Failed to get data from cache!\")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(500) // can't process this entity\n\t\treturn\n\t}\n}",
"func (fc *FileControl) TotalRecordCountField() string {\n\treturn fc.numericField(fc.TotalRecordCount, 8)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetTotalRecords sets the totalRecords to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) SetTotalRecords(totalRecords uint64) {
o.TotalRecords = totalRecords
}
|
[
"func (o *ArtifactListerOK) SetTotalRecords(totalRecords uint64) {\n\to.TotalRecords = totalRecords\n}",
"func (o *ArtifactListerPartialContent) WithTotalRecords(totalRecords uint64) *ArtifactListerPartialContent {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerOK) WithTotalRecords(totalRecords uint64) *ArtifactListerOK {\n\to.TotalRecords = totalRecords\n\treturn o\n}",
"func (o *ArtifactListerPartialContent) SetRemainingRecords(remainingRecords uint64) {\n\to.RemainingRecords = remainingRecords\n}",
"func (o *ArtifactListerPartialContent) WithRemainingRecords(remainingRecords uint64) *ArtifactListerPartialContent {\n\to.RemainingRecords = remainingRecords\n\treturn o\n}",
"func (page *Page) SetTotal(rowCount, pageSize uint64) {\n\tpage.Total = int64(math.Ceil(float64(rowCount) / float64(pageSize)))\n\tpage.TotalRows = int64(rowCount)\n}",
"func (m *Office365GroupsActivityFileCounts) SetTotal(value *int64)() {\n err := m.GetBackingStore().Set(\"total\", value)\n if err != nil {\n panic(err)\n }\n}",
"func (o *ExportRuleGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (u *UserResultsPage) setTotalPages(p int) {\n\tu.TotalPages = p\n}",
"func (b *Base) SetTotalCountHeader(total int64) {\n\tb.RespHeader().Set(\"X-Total-Count\", fmt.Sprint(total))\n\tb.AppendAccessControlExposeHeaders(\"X-Total-Count\")\n}",
"func (r *MachinePoolsListServerResponse) Total(value int) *MachinePoolsListServerResponse {\n\tr.total = &value\n\treturn r\n}",
"func (rb *ShardsRecordBuilder) FlushTotal(flushtotal string) *ShardsRecordBuilder {\n\trb.v.FlushTotal = &flushtotal\n\treturn rb\n}",
"func (o *SnapmirrorGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (u *UserResultsPage) setTotalMatches(m int) {\n\tu.TotalMatches = m\n}",
"func (suite *TestPagingSuite) TestSetTotalCount(c *C) {\n\ttestCases := []*struct {\n\t\ttotalCount int32\n\t\texpected bool\n\t}{\n\t\t{21, true},\n\t\t{20, false},\n\t\t{19, false},\n\t\t{0, false},\n\t}\n\n\tfor i, testCase := range testCases {\n\t\tcomment := ocheck.TestCaseComment(i)\n\t\tocheck.LogTestCase(c, testCase)\n\n\t\ttestedPaging := NewUndefinedPaging()\n\t\ttestedPaging.Position = 2\n\t\ttestedPaging.Size = 10\n\n\t\ttestedPaging.SetTotalCount(testCase.totalCount)\n\n\t\tc.Assert(testedPaging.PageMore, Equals, testCase.expected, comment)\n\t}\n}",
"func (g *GlobalResponse) Sum() {\n\tsum := 0\n\n\tfor _, v := range g.Records {\n\t\tsum += v.Fields.NumBikesAvailable\n\t}\n\n\tg.Total = sum\n}",
"func (o *IscsiInterfaceGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (o *IscsiInitiatorGetIterResponseResult) NumRecords() int {\n\tvar r int\n\tif o.NumRecordsPtr == nil {\n\t\treturn r\n\t}\n\tr = *o.NumRecordsPtr\n\treturn r\n}",
"func (d *DBClient) RecordsCount(w http.ResponseWriter, req *http.Request, next http.HandlerFunc) {\n\tcount, err := d.Cache.RecordsCount()\n\n\tif err == nil {\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json\")\n\n\t\tvar response recordsCount\n\t\tresponse.Count = count\n\t\tb, err := json.Marshal(response)\n\n\t\tif err != nil {\n\t\t\tlog.Error(err)\n\t\t\thttp.Error(w, err.Error(), http.StatusInternalServerError)\n\t\t} else {\n\t\t\tw.Write(b)\n\t\t\treturn\n\t\t}\n\t} else {\n\t\tlog.WithFields(log.Fields{\n\t\t\t\"Error\": err.Error(),\n\t\t}).Error(\"Failed to get data from cache!\")\n\n\t\tw.Header().Set(\"Content-Type\", \"application/json; charset=UTF-8\")\n\t\tw.WriteHeader(500) // can't process this entity\n\t\treturn\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPayload adds the payload to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerPartialContent {
o.Payload = payload
return o
}
|
[
"func (o *ArtifactListerPartialContent) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerOK) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerOK {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ListApiregistrationV1APIServiceOK) SetPayload(payload *models.IoK8sKubeAggregatorPkgApisApiregistrationV1APIServiceList) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecDefault) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *GetAssetsListOK) SetPayload(payload []*models.TokenAssetRow) {\n\to.Payload = payload\n}",
"func (o *GetFeedOK) SetPayload(payload []*models.Offering) {\n\to.Payload = payload\n}",
"func (o *GetAuditregistrationV1alpha1APIResourcesOK) SetPayload(payload *models.IoK8sApimachineryPkgApisMetaV1APIResourceList) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ListStorageV1alpha1VolumeAttachmentOK) SetPayload(payload *models.IoK8sAPIStorageV1alpha1VolumeAttachmentList) {\n\to.Payload = payload\n}",
"func (o *UploadFileVersionOK) SetPayload(payload *models.FileList) {\n\to.Payload = payload\n}",
"func (o *AlbumListMatchOK) SetPayload(payload *models.InlineResponse2006) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecCreated) SetPayload(payload *models.RawSpec) {\n\to.Payload = payload\n}",
"func (o *ListAppsV1NamespacedDeploymentOK) SetPayload(payload *models.IoK8sAPIAppsV1DeploymentList) {\n\to.Payload = payload\n}",
"func (o *PatchApiextensionsV1beta1CustomResourceDefinitionStatusOK) SetPayload(payload *models.IoK8sApiextensionsApiserverPkgApisApiextensionsV1beta1CustomResourceDefinition) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPayload sets the payload to the artifact lister partial content response
|
func (o *ArtifactListerPartialContent) SetPayload(payload []*weles.ArtifactInfo) {
o.Payload = payload
}
|
[
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetAssetsListOK) SetPayload(payload []*models.TokenAssetRow) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecDefault) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *AddComponentRoleInternalServerError) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *LoadDesignDataPartsOK) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *GetAuditregistrationV1alpha1APIResourcesOK) SetPayload(payload *models.IoK8sApimachineryPkgApisMetaV1APIResourceList) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListUnauthorized) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateClusterUnauthorized) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecCreated) SetPayload(payload *models.RawSpec) {\n\to.Payload = payload\n}",
"func (o *AddComponentRoleConflict) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *AddItemInternalServerError) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *AddReleasesUnauthorized) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *GetFeedOK) SetPayload(payload []*models.Offering) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageOK) SetPayload(payload CatalogEntryPackage.CatalogEntryPackage) {\n\to.Payload = payload\n}",
"func (o *ListAppsV1NamespacedDeploymentOK) SetPayload(payload *models.IoK8sAPIAppsV1DeploymentList) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageInternalServerError) SetPayload(payload string) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewArtifactListerBadRequest creates ArtifactListerBadRequest with default headers values
|
func NewArtifactListerBadRequest() *ArtifactListerBadRequest {
return &ArtifactListerBadRequest{}
}
|
[
"func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {\n\to.Payload = payload\n\treturn o\n}",
"func NewListArtifactsBadRequest() *ListArtifactsBadRequest {\n\treturn &ListArtifactsBadRequest{}\n}",
"func NewListBadRequest(body *ListBadRequestResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}",
"func NewBadRequest(msg string, details ...string) APIError {\n\treturn NewAPIError(msg, strings.Join(details, \", \"), http.StatusBadRequest)\n}",
"func NewAllDashboardsBadRequest() *AllDashboardsBadRequest {\n return &AllDashboardsBadRequest{\n }\n}",
"func newErrBadRequest(ctx *context.T, err error) error {\n\treturn verror.New(errBadRequest, ctx, err)\n}",
"func BadRequest(format string, args ...interface{}) error {\n\treturn New(http.StatusBadRequest, format, args...)\n}",
"func NewContainerRegistryListBadRequest() *ContainerRegistryListBadRequest {\n\treturn &ContainerRegistryListBadRequest{}\n}",
"func SetNewBadRequestByFormat(ef *ErrorFormat) *ErrorMessage {\n\treturn &ErrorMessage{\n\t\tCode: http.StatusBadRequest,\n\t\tErrorList: []*ErrorFormat{\n\t\t\tef,\n\t\t},\n\t}\n}",
"func NewBadRequest(err error, msg string) error {\n\treturn &badRequest{wrap(err, msg, \"\")}\n}",
"func ErrBadRequestf(format string, arguments ...interface{}) *Status {\n\treturn &Status{Code: http.StatusBadRequest, Text: fmt.Sprintf(format, arguments...)}\n}",
"func NewAllUserAccessFiltersBadRequest() *AllUserAccessFiltersBadRequest {\n return &AllUserAccessFiltersBadRequest{\n }\n}",
"func NewAddItemBadRequest() *AddItemBadRequest {\n\n\treturn &AddItemBadRequest{}\n}",
"func NewListEventLoopGroupBadRequest() *ListEventLoopGroupBadRequest {\n\treturn &ListEventLoopGroupBadRequest{}\n}",
"func CreateBadRequest(errorMessage string) BadRequest {\n\treturn BadRequest{Error: errorMessage}\n}",
"func NewListBadRequestResponseBody(res *goa.ServiceError) *ListBadRequestResponseBody {\n\tbody := &ListBadRequestResponseBody{\n\t\tName: res.Name,\n\t\tID: res.ID,\n\t\tMessage: res.Message,\n\t\tTemporary: res.Temporary,\n\t\tTimeout: res.Timeout,\n\t\tFault: res.Fault,\n\t}\n\treturn body\n}",
"func NewListDealsBadRequest() *ListDealsBadRequest {\n\treturn &ListDealsBadRequest{}\n}",
"func NewObjectsListBadRequest() *ObjectsListBadRequest {\n\n\treturn &ObjectsListBadRequest{}\n}",
"func NewGetTagBadRequest() *GetTagBadRequest {\n\n\treturn &GetTagBadRequest{}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPayload adds the payload to the artifact lister bad request response
|
func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {
o.Payload = payload
return o
}
|
[
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {\n\to.Payload = payload\n\treturn o\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecBadRequest) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *ObjectsListBadRequest) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateOfferingByIDBadRequest) SetPayload(payload *models.InvalidParameterInput) {\n\to.Payload = payload\n}",
"func (o *GetGameOnResultsBadRequest) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *AddNewMaterialsForPostBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetLinkInfoBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListUnauthorized) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *AddReleasesBadRequest) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *GetAviServiceEngineGroupsBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *DeleteOfferingByIDBadRequest) SetPayload(payload *models.InvalidParameterInput) {\n\to.Payload = payload\n}",
"func (o *PostGameOnResultsBadRequest) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *ObjectsListForbidden) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPayload sets the payload to the artifact lister bad request response
|
func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {
o.Payload = payload
}
|
[
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *PutAPIInventoryAPIIDSpecsProvidedSpecBadRequest) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *AddNewMaterialsForPostBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListUnauthorized) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ObjectsListUnprocessableEntity) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateClusterBadRequest) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateOfferingByIDBadRequest) SetPayload(payload *models.InvalidParameterInput) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *GetVisiblePublishedPruebasFromQuestionTestBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *AddReleasesBadRequest) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *GetVSphereComputeResourcesBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ObjectsListBadRequest) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdatePostbyIDBadRequest) SetPayload(payload *models.Response) {\n\to.Payload = payload\n}",
"func (o *CheckDecryptionDecompressionStatusBadRequest) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *WeaviateActionsPatchUnprocessableEntity) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *CreatePackageUnprocessableEntity) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewArtifactListerNotFound creates ArtifactListerNotFound with default headers values
|
func NewArtifactListerNotFound() *ArtifactListerNotFound {
return &ArtifactListerNotFound{}
}
|
[
"func (o *ArtifactListerNotFound) WithPayload(payload *weles.ErrResponse) *ArtifactListerNotFound {\n\to.Payload = payload\n\treturn o\n}",
"func NewListArtifactsNotFound() *ListArtifactsNotFound {\n\treturn &ListArtifactsNotFound{}\n}",
"func NewNotFound(s string, v ...interface{}) error {\n\treturn asNotFound(fmt.Errorf(s, v...))\n}",
"func NewNotFound() error {\n\treturn requestError{\n\t\tClientError: ClientError{\n\t\t\tErrors: []clientErrorSubError{{Message: \"status code 404\"}},\n\t\t},\n\t}\n}",
"func NewNotFound(msg string) errstack.E {\n\tif msg == \"\" {\n\t\tmsg = \"object not found\"\n\t}\n\treturn notFound{errstack.NewReq(msg)}\n}",
"func NewNotFound(resource, field, value string) *NotFound {\n\treturn &NotFound{resource, field, value}\n}",
"func NewArtifactListerBadRequest() *ArtifactListerBadRequest {\n\n\treturn &ArtifactListerBadRequest{}\n}",
"func NewArtifactListerOK() *ArtifactListerOK {\n\n\treturn &ArtifactListerOK{}\n}",
"func (a *APIDefaults) ArtifactLister(params artifacts.ArtifactListerParams) middleware.Responder {\n\tpaginator := weles.ArtifactPagination{}\n\tif a.PageLimit != 0 {\n\t\tif (params.After != nil) && (params.Before != nil) {\n\t\t\treturn artifacts.NewArtifactListerBadRequest().WithPayload(&weles.ErrResponse{\n\t\t\t\tMessage: weles.ErrBeforeAfterNotAllowed.Error()})\n\t\t}\n\t\tpaginator = setArtifactPaginator(params, a.PageLimit)\n\t}\n\tfilter := setArtifactFilter(params.ArtifactFilterAndSort.Filter)\n\tsorter := setArtifactSorter(params.ArtifactFilterAndSort.Sorter)\n\n\tartifactInfoReceived, listInfo, err := a.Managers.AM.ListArtifact(filter, sorter, paginator)\n\n\tswitch err {\n\tdefault:\n\t\treturn artifacts.NewArtifactListerInternalServerError().WithPayload(\n\t\t\t&weles.ErrResponse{Message: err.Error()})\n\tcase weles.ErrArtifactNotFound:\n\t\treturn artifacts.NewArtifactListerNotFound().WithPayload(\n\t\t\t&weles.ErrResponse{Message: weles.ErrArtifactNotFound.Error()})\n\tcase nil:\n\t}\n\n\tartifactInfoReturned := artifactInfoReceivedToReturn(artifactInfoReceived)\n\n\tif (listInfo.RemainingRecords == 0) || (a.PageLimit == 0) { //last page...\n\t\treturn responderArtifact200(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n\t} //not last page...\n\treturn responderArtifact206(listInfo, paginator, artifactInfoReturned, a.PageLimit)\n}",
"func notFound(resource string) middleware.Responder {\n\tmessage := fmt.Sprintf(\"404 %s not found\", resource)\n\treturn operations.NewGetChartDefault(http.StatusNotFound).WithPayload(\n\t\t&models.Error{Code: helpers.Int64ToPtr(http.StatusNotFound), Message: &message},\n\t)\n}",
"func wrapNotFound(r Reference, err error) error {\n\tswitch {\n\tcase errors.Is(err, os.ErrNotExist):\n\t\terr = fmt.Errorf(\"%w (%v)\", NotFound, r)\n\t}\n\tif aerr, ok := err.(awserr.Error); ok {\n\t\tswitch aerr.Code() {\n\t\tcase s3.ErrCodeNoSuchBucket:\n\t\t\terr = fmt.Errorf(\"%w (no such bucket; %v)\", NotFound, r)\n\t\tcase s3.ErrCodeNoSuchKey:\n\t\t\terr = fmt.Errorf(\"%w (no such key; %v)\", NotFound, r)\n\t\t}\n\t}\n\treturn err\n}",
"func NewNotFound(parameters ...wparams.ParamStorer) Error {\n\treturn newGenericError(nil, DefaultNotFound, wparams.NewParamStorer(parameters...))\n}",
"func noFound(msg string) error {\n\treturn status.Error(codes.NotFound, msg)\n}",
"func NewShowNotFound(body *ShowNotFoundResponseBody) *goa.ServiceError {\n\tv := &goa.ServiceError{\n\t\tName: *body.Name,\n\t\tID: *body.ID,\n\t\tMessage: *body.Message,\n\t\tTemporary: *body.Temporary,\n\t\tTimeout: *body.Timeout,\n\t\tFault: *body.Fault,\n\t}\n\n\treturn v\n}",
"func NewAllDashboardsNotFound() *AllDashboardsNotFound {\n return &AllDashboardsNotFound{\n }\n}",
"func NewErrNotFound(msg string, args ...interface{}) Error {\n\treturn NewError(http.StatusNotFound, msg, args...)\n}",
"func responderArtifact200(listInfo weles.ListInfo, paginator weles.ArtifactPagination,\n\tartifactInfoReturned []*weles.ArtifactInfo, defaultPageLimit int32,\n) (responder *artifacts.ArtifactListerOK) {\n\tvar artifactListerURL artifacts.ArtifactListerURL\n\tresponder = artifacts.NewArtifactListerOK()\n\tresponder.SetTotalRecords(listInfo.TotalRecords)\n\tif paginator.ID != 0 { //not the first page\n\t\t// keep in mind that ArtifactPath in paginator is taken from query parameter,\n\t\t// not ArtifactManager\n\t\tif paginator.Forward {\n\t\t\ttmp := artifactInfoReturned[0].ID\n\t\t\tartifactListerURL.Before = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp\n\t\t\t}\n\t\t\tresponder.SetPrevious(artifactListerURL.String())\n\t\t} else {\n\t\t\ttmp := artifactInfoReturned[len(artifactInfoReturned)-1].ID\n\t\t\tartifactListerURL.After = &tmp\n\t\t\tif defaultPageLimit != paginator.Limit {\n\t\t\t\ttmp2 := paginator.Limit\n\t\t\t\tartifactListerURL.Limit = &tmp2\n\t\t\t}\n\t\t\tresponder.SetNext(artifactListerURL.String())\n\t\t}\n\t}\n\tresponder.SetPayload(artifactInfoReturned)\n\treturn\n}",
"func notFound(resp *ApiResponse, msg string) error {\n resp.StatusCode = http.StatusNotFound\n resp.Message = []byte(msg)\n resp.ErrorMessage = http.StatusText(http.StatusNotFound)\n\n return nil\n}",
"func NewGetEntriesNotFound() *GetEntriesNotFound {\n\treturn &GetEntriesNotFound{}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPayload adds the payload to the artifact lister not found response
|
func (o *ArtifactListerNotFound) WithPayload(payload *weles.ErrResponse) *ArtifactListerNotFound {
o.Payload = payload
return o
}
|
[
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerOK) WithPayload(payload []*weles.ArtifactInfo) *ArtifactListerOK {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetGameOnResultsNotFound) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *DeleteOrganizationNotFound) SetPayload(payload *models.MissingResponse) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageNotFound) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *V2ListEventsNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetOrgMembersV1NotFound) SetPayload(payload *model.StandardError) {\n\to.Payload = payload\n}",
"func (o *UpdateClusterNotFound) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *PostGameOnResultsNotFound) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *CheckCloudNFSExportRemoveStatusNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *CreatePackageNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetDashboardsNotFound) SetPayload(payload *models.Error) {\r\n\to.Payload = payload\r\n}",
"func (o *UpdateRecordNotFound) SetPayload(payload *models.NotFoundError) {\n\to.Payload = payload\n}",
"func (o *ListEventsNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPayload sets the payload to the artifact lister not found response
|
func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {
o.Payload = payload
}
|
[
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerOK) SetPayload(payload []*weles.ArtifactInfo) {\n\to.Payload = payload\n}",
"func (o *GetCatalogEntryPackageNotFound) SetPayload(payload string) {\n\to.Payload = payload\n}",
"func (o *PostFriendsUpdatesListNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateClusterNotFound) SetPayload(payload *models.APIResponse) {\n\to.Payload = payload\n}",
"func (o *CreatePackageNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetPreflightRequirementsNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *CheckCloudNFSExportRemoveStatusNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *UpdateRecordNotFound) SetPayload(payload *models.NotFoundError) {\n\to.Payload = payload\n}",
"func (o *GetWorkflowExecutionLogsNotFound) SetPayload(payload *models.MissingResponse) {\n\to.Payload = payload\n}",
"func (o *UpdatePostbyIDNotFound) SetPayload(payload *models.Response) {\n\to.Payload = payload\n}",
"func (o *DeleteOrganizationNotFound) SetPayload(payload *models.MissingResponse) {\n\to.Payload = payload\n}",
"func (o *GetPostbyIDNotFound) SetPayload(payload *models.Response) {\n\to.Payload = payload\n}",
"func (o *GetGameOnResultsNotFound) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *ShowPackageReleasesNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ListEventsNotFound) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetNamespacedNotebooksNotFound) SetPayload(payload *models.Error) {\r\n\to.Payload = payload\r\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
WithPayload adds the payload to the artifact lister internal server error response
|
func (o *ArtifactListerInternalServerError) WithPayload(payload *weles.ErrResponse) *ArtifactListerInternalServerError {
o.Payload = payload
return o
}
|
[
"func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerBadRequest) WithPayload(payload *weles.ErrResponse) *ArtifactListerBadRequest {\n\to.Payload = payload\n\treturn o\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetAviCloudsInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ObjectsListInternalServerError) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *GetAviServiceEngineGroupsInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetTagInternalServerError) SetPayload(payload models.Error) {\n\to.Payload = payload\n}",
"func (o *GetGameOnResultsInternalServerError) SetPayload(payload *models.APIError) {\n\to.Payload = payload\n}",
"func (o *V1ListHellosInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GraphqlPostInternalServerError) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}",
"func (o *GetApisInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetVSphereOSImagesInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ServiceAddServiceUnavailable) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetVSphereComputeResourcesInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *InstallHostInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetAviServiceEngineGroupsBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
SetPayload sets the payload to the artifact lister internal server error response
|
func (o *ArtifactListerInternalServerError) SetPayload(payload *weles.ErrResponse) {
o.Payload = payload
}
|
[
"func (o *ArtifactListerBadRequest) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *ArtifactListerNotFound) SetPayload(payload *weles.ErrResponse) {\n\to.Payload = payload\n}",
"func (o *GetVSphereDatastoresInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *SetVSphereEndpointInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetRepositoryInfoInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetVSphereComputeResourcesInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetAviCloudsInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *ImportFailedDependency) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetVSphereDatastoresBadRequest) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetV1RdssInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *AddNewMaterialsForPostInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetmoviesinfoInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *InstallHostInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *FetchTodoItemsInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *CounselingUpdateOrderPreconditionFailed) SetPayload(payload *ghcmessages.Error) {\n\to.Payload = payload\n}",
"func (o *GetApisInternalServerError) SetPayload(payload *models.Error) {\n\to.Payload = payload\n}",
"func (o *GetTagInternalServerError) SetPayload(payload models.Error) {\n\to.Payload = payload\n}",
"func (o *RegisterInternalServerError) SetPayload(payload *models.ResponseCode) {\n\to.Payload = payload\n}",
"func (o *GetIBAServerNotFound) SetPayload(payload *models.ErrorResponse) {\n\to.Payload = payload\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Get retrieves a byte buffer from the pool and resets it so that it is ready to use.
|
func (p *bufferPool) Get() *bytes.Buffer {
buf := p.underlying.Get().(*bytes.Buffer)
buf.Reset()
return buf
}
|
[
"func (bp *BufferPool) Get() *bytes.Buffer {\n\tbuffer := bp.pool.Get().(*bytes.Buffer)\n\treturn buffer\n}",
"func GetBuffer() *bytes.Buffer {\n\tbuf := bufPool.Get().(*bytes.Buffer)\n\tbuf.Reset()\n\treturn buf\n}",
"func GetBuffer() Buffer {\n\treturn pool.get()\n}",
"func GetBuffer() *bytes.Buffer {\n\treturn defaultPool.pool.Get().(*bytes.Buffer)\n}",
"func GetBuf() *Buffer {\n\tbuf := bufferPool.Get().(*Buffer)\n\tbuf.Reset()\n\treturn buf\n}",
"func getBuffer() (buf *bytes.Buffer) {\n\treturn bufferPool.Get().(*bytes.Buffer)\n}",
"func getBuffer() *bytes.Buffer {\n\treturn bufferPool.Get().(*bytes.Buffer)\n}",
"func GetBuffer() *bytes.Buffer {\n\treturn bufPool.Get().(*bytes.Buffer)\n}",
"func (p *BufferBucketPool) Get() *BufferBucket {\n\treturn p.pool.Get().(*BufferBucket)\n}",
"func (_ BufferPtrPool1M) Get() *[]byte {\n\treturn GetBytesSlicePtr1M()\n}",
"func (p *Pool) Get() ([]byte, error) {\n\tif b, ok := p.tryPop(); ok {\n\t\treturn b, nil\n\t}\n\n\tp.Lock()\n\tdefer p.Unlock()\n\n\tif len(p.allocated) == p.maxBlocks {\n\t\treturn nil, ErrPoolFull\n\t}\n\tresult, err := alloc(p.initOpts.blockSize)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tk := &result[0]\n\tp.allocated[k] = struct{}{}\n\treturn result, nil\n}",
"func (_ BufferPtrPool8M) Get() *[]byte {\n\treturn GetBytesSlicePtr8M()\n}",
"func GetBytesBuffer() *bytes.Buffer {\n\tbuf := defaultPool.Get().(*bytes.Buffer)\n\tbufCap := buf.Cap()\n\tif bufCap >= minBufCap && bufCap <= maxBufCap && poolObjectNumber.Load() > 0 {\n\t\tpoolObjectNumber.Dec()\n\t}\n\n\treturn buf\n}",
"func (_ BufferPtrPool8K) Get() *[]byte {\n\treturn GetBytesSlicePtr8K()\n}",
"func GetBuffer(cap int) *Object[*bytes.Buffer] {\n\treturn BufferPool.Get(cap)\n}",
"func (_ BufferPtrPool1K) Get() *[]byte {\n\treturn GetBytesSlicePtr1K()\n}",
"func getBuf(l int) []byte {\n\tx := bufPool.Get()\n\tif x == nil {\n\t\treturn make([]byte, l)\n\t}\n\tbuf := x.([]byte)\n\tif cap(buf) < l {\n\t\treturn make([]byte, l)\n\t}\n\treturn buf[:l]\n}",
"func (bufferP *BufferPool) Get(size int) (data []byte, err error) {\n\tif size == util.PacketHeaderSize {\n\t\tatomic.AddInt64(&headBuffersCount, 1)\n\t\tid := atomic.AddUint64(&headBufAllocId, 1)\n\t\treturn bufferP.getHead(id), nil\n\t} else if size == util.BlockSize {\n\t\tatomic.AddInt64(&normalBuffersCount, 1)\n\t\tid := atomic.AddUint64(&normalBufAllocId, 1)\n\t\treturn bufferP.getNoraml(id), nil\n\t} else if size == util.DefaultTinySizeLimit {\n\t\tatomic.AddInt64(&tinyBuffersCount, 1)\n\t\treturn bufferP.tinyPool.Get().([]byte), nil\n\t}\n\treturn nil, fmt.Errorf(\"can only support 45 or 65536 bytes\")\n}",
"func (_ BufferPtrPool2M) Get() *[]byte {\n\treturn GetBytesSlicePtr2M()\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Routes returns all of the api route for the DefaultApiController
|
func (c *DefaultApiController) Routes() Routes {
return Routes{
{
"GetJobOffer",
strings.ToUpper("Get"),
"/job_offer",
c.GetJobOffer,
},
{
"GetOccupation",
strings.ToUpper("Get"),
"/occupation",
c.GetOccupation,
},
{
"GetTotalPopulation",
strings.ToUpper("Get"),
"/total_population",
c.GetTotalPopulation,
},
}
}
|
[
"func (c *DefaultApiController) Routes() Routes {\n\treturn Routes{ \n\t\t{\n\t\t\t\"GetNumber1\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/number1\",\n\t\t\tc.GetNumber1,\n\t\t},\n\t\t{\n\t\t\t\"GetTest\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/test\",\n\t\t\tc.GetTest,\n\t\t},\n\t\t{\n\t\t\t\"GetTest2\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/test2\",\n\t\t\tc.GetTest2,\n\t\t},\n\t\t{\n\t\t\t\"PostHoge\",\n\t\t\tstrings.ToUpper(\"Post\"),\n\t\t\t\"/hoge\",\n\t\t\tc.PostHoge,\n\t\t},\n\t}\n}",
"func (c *DefaultApiController) Routes() Routes {\n\treturn Routes{ \n\t\t{\n\t\t\t\"AccountGet\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/api/v1/account\",\n\t\t\tc.AccountGet,\n\t\t},\n\t\t{\n\t\t\t\"EchoGet\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/api/v1/echo\",\n\t\t\tc.EchoGet,\n\t\t},\n\t}\n}",
"func (c *DefaultApiController) Routes() Routes {\n\treturn Routes{\n\t\t{\n\t\t\t\"GetJobOffer\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/job_offer\",\n\t\t\tc.GetJobOffer,\n\t\t},\n\t\t{\n\t\t\t\"GetOccupation\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/occupation\",\n\t\t\tc.GetOccupation,\n\t\t},\n\t\t{\n\t\t\t\"GetTotalPopulation\",\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/total_population\",\n\t\t\tc.GetTotalPopulation,\n\t\t},\n\t\t{\n\t\t\t\"PostJobOffer\",\n\t\t\tstrings.ToUpper(\"Post\"),\n\t\t\t\"/job_offer\",\n\t\t\tc.PostJobOffer,\n\t\t},\n\t\t{\n\t\t\t\"PostOccupation\",\n\t\t\tstrings.ToUpper(\"Post\"),\n\t\t\t\"/occupation\",\n\t\t\tc.PostOccupation,\n\t\t},\n\t\t{\n\t\t\t\"PostTotalPopulation\",\n\t\t\tstrings.ToUpper(\"Post\"),\n\t\t\t\"/total_population\",\n\t\t\tc.PostTotalPopulation,\n\t\t},\n\t}\n}",
"func (Http) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/http/cff_action/\",\n\t\t\"/api/objects/http/cff_action/{ref}\",\n\t\t\"/api/objects/http/cff_action/{ref}/usedby\",\n\t\t\"/api/objects/http/cff_profile/\",\n\t\t\"/api/objects/http/cff_profile/{ref}\",\n\t\t\"/api/objects/http/cff_profile/{ref}/usedby\",\n\t\t\"/api/objects/http/device_auth/\",\n\t\t\"/api/objects/http/device_auth/{ref}\",\n\t\t\"/api/objects/http/device_auth/{ref}/usedby\",\n\t\t\"/api/objects/http/domain_regex/\",\n\t\t\"/api/objects/http/domain_regex/{ref}\",\n\t\t\"/api/objects/http/domain_regex/{ref}/usedby\",\n\t\t\"/api/objects/http/exception/\",\n\t\t\"/api/objects/http/exception/{ref}\",\n\t\t\"/api/objects/http/exception/{ref}/usedby\",\n\t\t\"/api/objects/http/group/\",\n\t\t\"/api/objects/http/group/{ref}\",\n\t\t\"/api/objects/http/group/{ref}/usedby\",\n\t\t\"/api/objects/http/local_site/\",\n\t\t\"/api/objects/http/local_site/{ref}\",\n\t\t\"/api/objects/http/local_site/{ref}/usedby\",\n\t\t\"/api/objects/http/lsl_tag/\",\n\t\t\"/api/objects/http/lsl_tag/{ref}\",\n\t\t\"/api/objects/http/lsl_tag/{ref}/usedby\",\n\t\t\"/api/objects/http/pac_file/\",\n\t\t\"/api/objects/http/pac_file/{ref}\",\n\t\t\"/api/objects/http/pac_file/{ref}/usedby\",\n\t\t\"/api/objects/http/parent_proxy/\",\n\t\t\"/api/objects/http/parent_proxy/{ref}\",\n\t\t\"/api/objects/http/parent_proxy/{ref}/usedby\",\n\t\t\"/api/objects/http/profile/\",\n\t\t\"/api/objects/http/profile/{ref}\",\n\t\t\"/api/objects/http/profile/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_category/\",\n\t\t\"/api/objects/http/sp_category/{ref}\",\n\t\t\"/api/objects/http/sp_category/{ref}/usedby\",\n\t\t\"/api/objects/http/sp_subcat/\",\n\t\t\"/api/objects/http/sp_subcat/{ref}\",\n\t\t\"/api/objects/http/sp_subcat/{ref}/usedby\",\n\t}\n}",
"func (Stas) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/stas/collector/\",\n\t\t\"/api/objects/stas/collector/{ref}\",\n\t\t\"/api/objects/stas/collector/{ref}/usedby\",\n\t\t\"/api/objects/stas/group/\",\n\t\t\"/api/objects/stas/group/{ref}\",\n\t\t\"/api/objects/stas/group/{ref}/usedby\",\n\t}\n}",
"func (Status) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/status/version\",\n\t}\n}",
"func APIRoutes() *echo.Echo {\n\tapi := echo.New()\n\tapi.Use(middleware.CORSWithConfig(middleware.CORSConfig{\n\t\tAllowOrigins: []string{\"*\"},\n\t\tAllowHeaders: []string{\"*\"},\n\t}))\n\n\tapi.Use(middleware.Logger())\n\tapi.Use(middleware.Recover())\n\n\tapi.GET(\"/\", controller.HomePage)\n\tapi.GET(\"/timestamp\", controller.Timestamp)\n\tapi.GET(\"/payment_status\", controller.PaymentStatus)\n\n\treturn api\n}",
"func (RemoteSyslog) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/remote_syslog/group/\",\n\t\t\"/api/objects/remote_syslog/group/{ref}\",\n\t\t\"/api/objects/remote_syslog/group/{ref}/usedby\",\n\t\t\"/api/objects/remote_syslog/server/\",\n\t\t\"/api/objects/remote_syslog/server/{ref}\",\n\t\t\"/api/objects/remote_syslog/server/{ref}/usedby\",\n\t}\n}",
"func (Snmp) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/snmp/group/\",\n\t\t\"/api/objects/snmp/group/{ref}\",\n\t\t\"/api/objects/snmp/group/{ref}/usedby\",\n\t\t\"/api/objects/snmp/trap/\",\n\t\t\"/api/objects/snmp/trap/{ref}\",\n\t\t\"/api/objects/snmp/trap/{ref}/usedby\",\n\t}\n}",
"func (Spx) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/spx/group/\",\n\t\t\"/api/objects/spx/group/{ref}\",\n\t\t\"/api/objects/spx/group/{ref}/usedby\",\n\t\t\"/api/objects/spx/template/\",\n\t\t\"/api/objects/spx/template/{ref}\",\n\t\t\"/api/objects/spx/template/{ref}/usedby\",\n\t}\n}",
"func Routes(api *operations.ReturnEverythingAPI) {\n\tapi.GetEverythingHandler = operations.GetEverythingHandlerFunc(getEverything)\n\n\tapi.ApplicationGetAppHandler = application.GetAppHandlerFunc(getApp)\n\tapi.ApplicationGetAppFieldHandler = application.GetAppFieldHandlerFunc(getAppField)\n\tapi.ApplicationGetAppEnvsHandler = application.GetAppEnvsHandlerFunc(getAppEnvs)\n\tapi.ApplicationGetAppEnvHandler = application.GetAppEnvHandlerFunc(getAppEnv)\n\n\tapi.HostGetHostHandler = host.GetHostHandlerFunc(getHost)\n\tapi.HostGetHostFieldHandler = host.GetHostFieldHandlerFunc(getHostField)\n\n\tapi.RequestGetRequestInfoHandler = request.GetRequestInfoHandlerFunc(getRequestInfo)\n\tapi.RequestGetRequestFieldHandler = request.GetRequestFieldHandlerFunc(getRequestField)\n\tapi.RequestGetRequestHeadersHandler = request.GetRequestHeadersHandlerFunc(getRequestHeaders)\n\tapi.RequestGetRequestHeaderHandler = request.GetRequestHeaderHandlerFunc(getRequestHeader)\n\tapi.RequestGetRequestFormHandler = request.GetRequestFormHandlerFunc(getRequestForm)\n\tapi.RequestGetRequestPostFormHandler = request.GetRequestPostFormHandlerFunc(getRequestPostForm)\n\n\tapi.AwsGetAWSHandler = aws.GetAWSHandlerFunc(getAWS)\n\tapi.AwsGetAmazonEC2Handler = aws.GetAmazonEC2HandlerFunc(getAmazonEC2)\n\tapi.AwsGetAmazonEC2FieldHandler = aws.GetAmazonEC2FieldHandlerFunc(getAmazonEC2Field)\n\tapi.AwsGetAmazonECSHandler = aws.GetAmazonECSHandlerFunc(getAmazonECS)\n\tapi.AwsGetAmazonECSFieldHandler = aws.GetAmazonECSFieldHandlerFunc(getAmazonECSField)\n\n\tapi.GoogleGetGoogleCloudHandler = google.GetGoogleCloudHandlerFunc(getGoogleCloud)\n\tapi.GoogleGetGoogleComputeEngineHandler = google.GetGoogleComputeEngineHandlerFunc(getGoogleComputeEngine)\n\tapi.GoogleGetGoogleComputeEngineFieldHandler = google.GetGoogleComputeEngineFieldHandlerFunc(getGoogleComputeEngineField)\n\tapi.GoogleGetGoogleKubernetesEngineHandler = google.GetGoogleKubernetesEngineHandlerFunc(getGoogleKubernetesEngine)\n\tapi.GoogleGetGoogleKubernetesEngineFieldHandler = google.GetGoogleKubernetesEngineFieldHandlerFunc(getGoogleKubernetesEngineField)\n}",
"func initalizeRoutes() {\n\n\tv1 := app.Group(\"/v1\")\n\n\t// Auth controller routes\n\taccountRoutes := v1.Group(\"/account\")\n\taccountRoutes.POST(\"/register\", accountController.Register)\n\taccountRoutes.POST(\"/login\", accountController.Login)\n\taccountRoutes.POST(\"/refresh-token\", accountController.RefreshToken)\n\n\t// Post controller routes\n\tpostRoutes := v1.Group(\"/posts\").Use(middleware.Authorization())\n\tpostRoutes.GET(\"/\", postController.GetAll)\n\n}",
"func (Itfparams) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/itfparams/bridge_port/\",\n\t\t\"/api/objects/itfparams/bridge_port/{ref}\",\n\t\t\"/api/objects/itfparams/bridge_port/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/group/\",\n\t\t\"/api/objects/itfparams/group/{ref}\",\n\t\t\"/api/objects/itfparams/group/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/{ref}\",\n\t\t\"/api/objects/itfparams/link_aggregation_group/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/primary/\",\n\t\t\"/api/objects/itfparams/primary/{ref}\",\n\t\t\"/api/objects/itfparams/primary/{ref}/usedby\",\n\t\t\"/api/objects/itfparams/secondary/\",\n\t\t\"/api/objects/itfparams/secondary/{ref}\",\n\t\t\"/api/objects/itfparams/secondary/{ref}/usedby\",\n\t}\n}",
"func (Interface) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/interface/bridge/\",\n\t\t\"/api/objects/interface/bridge/{ref}\",\n\t\t\"/api/objects/interface/bridge/{ref}/usedby\",\n\t\t\"/api/objects/interface/ethernet/\",\n\t\t\"/api/objects/interface/ethernet/{ref}\",\n\t\t\"/api/objects/interface/ethernet/{ref}/usedby\",\n\t\t\"/api/objects/interface/group/\",\n\t\t\"/api/objects/interface/group/{ref}\",\n\t\t\"/api/objects/interface/group/{ref}/usedby\",\n\t\t\"/api/objects/interface/ppp3g/\",\n\t\t\"/api/objects/interface/ppp3g/{ref}\",\n\t\t\"/api/objects/interface/ppp3g/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppmodem/\",\n\t\t\"/api/objects/interface/pppmodem/{ref}\",\n\t\t\"/api/objects/interface/pppmodem/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppoa/\",\n\t\t\"/api/objects/interface/pppoa/{ref}\",\n\t\t\"/api/objects/interface/pppoa/{ref}/usedby\",\n\t\t\"/api/objects/interface/pppoe/\",\n\t\t\"/api/objects/interface/pppoe/{ref}\",\n\t\t\"/api/objects/interface/pppoe/{ref}/usedby\",\n\t\t\"/api/objects/interface/tunnel/\",\n\t\t\"/api/objects/interface/tunnel/{ref}\",\n\t\t\"/api/objects/interface/tunnel/{ref}/usedby\",\n\t\t\"/api/objects/interface/vlan/\",\n\t\t\"/api/objects/interface/vlan/{ref}\",\n\t\t\"/api/objects/interface/vlan/{ref}/usedby\",\n\t}\n}",
"func (Condition) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/condition/group/\",\n\t\t\"/api/objects/condition/group/{ref}\",\n\t\t\"/api/objects/condition/group/{ref}/usedby\",\n\t\t\"/api/objects/condition/objref/\",\n\t\t\"/api/objects/condition/objref/{ref}\",\n\t\t\"/api/objects/condition/objref/{ref}/usedby\",\n\t}\n}",
"func (c *StoreAPIController) Routes() Routes {\n\treturn Routes{\n\t\t\"DeleteOrder\": Route{\n\t\t\tstrings.ToUpper(\"Delete\"),\n\t\t\t\"/v2/store/order/{orderId}\",\n\t\t\tc.DeleteOrder,\n\t\t},\n\t\t\"GetInventory\": Route{\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/v2/store/inventory\",\n\t\t\tc.GetInventory,\n\t\t},\n\t\t\"GetOrderById\": Route{\n\t\t\tstrings.ToUpper(\"Get\"),\n\t\t\t\"/v2/store/order/{orderId}\",\n\t\t\tc.GetOrderById,\n\t\t},\n\t\t\"PlaceOrder\": Route{\n\t\t\tstrings.ToUpper(\"Post\"),\n\t\t\t\"/v2/store/order\",\n\t\t\tc.PlaceOrder,\n\t\t},\n\t}\n}",
"func (sc *ServiceConfig) getRoutes() []rest.Route {\n\n\troutes := []rest.Route{\n\t\trest.Route{\"GET\", \"/\", mainPage},\n\t\trest.Route{\"GET\", \"/test\", testPage},\n\t\trest.Route{\"GET\", \"/stats\", sc.isCollectingStats()},\n\t\trest.Route{\"GET\", \"/version\", sc.authorizedClient(restGetServicedVersion)},\n\t\trest.Route{\"GET\", \"/backup/create\", sc.authorizedClient(RestBackupCreate)},\n\t\trest.Route{\"GET\", \"/backup/restore\", sc.authorizedClient(RestBackupRestore)},\n\t\trest.Route{\"GET\", \"/backup/list\", sc.checkAuth(RestBackupFileList)},\n\t\trest.Route{\"GET\", \"/backup/status\", sc.authorizedClient(RestBackupStatus)},\n\t\trest.Route{\"GET\", \"/backup/restore/status\", sc.authorizedClient(RestRestoreStatus)},\n\t\t// Hosts\n\t\trest.Route{\"GET\", \"/hosts\", sc.checkAuth(restGetHosts)},\n\t\trest.Route{\"GET\", \"/hosts/running\", sc.checkAuth(restGetActiveHostIDs)},\n\t\trest.Route{\"GET\", \"/hosts/defaultHostAlias\", sc.checkAuth(restGetDefaultHostAlias)},\n\t\trest.Route{\"GET\", \"/hosts/:hostId\", sc.checkAuth(restGetHost)},\n\t\trest.Route{\"POST\", \"/hosts/add\", sc.checkAuth(restAddHost)},\n\t\trest.Route{\"DELETE\", \"/hosts/:hostId\", sc.checkAuth(restRemoveHost)},\n\t\trest.Route{\"PUT\", \"/hosts/:hostId\", sc.checkAuth(restUpdateHost)},\n\t\trest.Route{\"GET\", \"/hosts/:hostId/running\", sc.authorizedClient(restGetRunningForHost)},\n\t\trest.Route{\"DELETE\", \"/hosts/:hostId/:serviceStateId\", sc.authorizedClient(restKillRunning)},\n\n\t\t// Pools\n\t\trest.Route{\"GET\", \"/pools/:poolId\", sc.checkAuth(restGetPool)},\n\t\trest.Route{\"DELETE\", \"/pools/:poolId\", sc.checkAuth(restRemovePool)},\n\t\trest.Route{\"PUT\", \"/pools/:poolId\", sc.checkAuth(restUpdatePool)},\n\t\trest.Route{\"POST\", \"/pools/add\", sc.checkAuth(restAddPool)},\n\t\trest.Route{\"GET\", \"/pools\", sc.checkAuth(restGetPools)},\n\t\trest.Route{\"GET\", \"/pools/:poolId/hosts\", sc.checkAuth(restGetHostsForResourcePool)},\n\n\t\t// Pools (VirtualIP)\n\t\trest.Route{\"PUT\", \"/pools/:poolId/virtualip\", sc.checkAuth(restAddPoolVirtualIP)},\n\t\trest.Route{\"DELETE\", \"/pools/:poolId/virtualip/*ip\", sc.checkAuth(restRemovePoolVirtualIP)},\n\n\t\t// Pools (IPs)\n\t\trest.Route{\"GET\", \"/pools/:poolId/ips\", sc.checkAuth(restGetPoolIps)},\n\n\t\t// Services (Apps)\n\t\trest.Route{\"GET\", \"/services\", sc.authorizedClient(restGetAllServices)},\n\t\trest.Route{\"GET\", \"/servicehealth\", sc.authorizedClient(health.RestGetHealthStatus)},\n\t\trest.Route{\"GET\", \"/services/:serviceId\", sc.authorizedClient(restGetService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/running\", sc.authorizedClient(restGetRunningForService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/status\", sc.authorizedClient(restGetStatusForService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/running/:serviceStateId\", sc.authorizedClient(restGetRunningService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/:serviceStateId/logs\", sc.authorizedClient(restGetServiceStateLogs)},\n\t\trest.Route{\"POST\", \"/services/add\", sc.authorizedClient(restAddService)},\n\t\trest.Route{\"POST\", \"/services/deploy\", sc.authorizedClient(restDeployService)},\n\t\trest.Route{\"DELETE\", \"/services/:serviceId\", sc.authorizedClient(restRemoveService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/logs\", sc.authorizedClient(restGetServiceLogs)},\n\t\trest.Route{\"PUT\", \"/services/:serviceId\", sc.authorizedClient(restUpdateService)},\n\t\trest.Route{\"GET\", \"/services/:serviceId/snapshot\", sc.authorizedClient(restSnapshotService)},\n\t\trest.Route{\"PUT\", \"/services/:serviceId/startService\", sc.authorizedClient(restStartService)},\n\t\trest.Route{\"PUT\", \"/services/:serviceId/stopService\", sc.authorizedClient(restStopService)},\n\n\t\t// Services (Virtual Host)\n\t\trest.Route{\"GET\", \"/services/vhosts\", sc.authorizedClient(restGetVirtualHosts)},\n\t\trest.Route{\"PUT\", \"/services/:serviceId/endpoint/:application/vhosts/*name\", sc.authorizedClient(restAddVirtualHost)},\n\t\trest.Route{\"DELETE\", \"/services/:serviceId/endpoint/:application/vhosts/*name\", sc.authorizedClient(restRemoveVirtualHost)},\n\n\t\t// Services (IP)\n\t\trest.Route{\"PUT\", \"/services/:serviceId/ip\", sc.authorizedClient(restServiceAutomaticAssignIP)},\n\t\trest.Route{\"PUT\", \"/services/:serviceId/ip/*ip\", sc.authorizedClient(restServiceManualAssignIP)},\n\n\t\t// Service templates (App templates)\n\t\trest.Route{\"GET\", \"/templates\", sc.authorizedClient(restGetAppTemplates)},\n\t\trest.Route{\"POST\", \"/templates/add\", sc.authorizedClient(restAddAppTemplate)},\n\t\trest.Route{\"DELETE\", \"/templates/:templateId\", sc.authorizedClient(restRemoveAppTemplate)},\n\t\trest.Route{\"POST\", \"/templates/deploy\", sc.authorizedClient(restDeployAppTemplate)},\n\t\trest.Route{\"POST\", \"/templates/deploy/status\", sc.authorizedClient(restDeployAppTemplateStatus)},\n\t\trest.Route{\"GET\", \"/templates/deploy/active\", sc.authorizedClient(restDeployAppTemplateActive)},\n\n\t\t// Login\n\t\trest.Route{\"POST\", \"/login\", sc.unAuthorizedClient(restLogin)},\n\t\trest.Route{\"DELETE\", \"/login\", restLogout},\n\n\t\t// DockerLogin\n\t\trest.Route{\"GET\", \"/dockerIsLoggedIn\", sc.authorizedClient(restDockerIsLoggedIn)},\n\n\t\t// \"Misc\" stuff\n\t\trest.Route{\"GET\", \"/top/services\", sc.authorizedClient(restGetTopServices)},\n\t\trest.Route{\"GET\", \"/running\", sc.authorizedClient(restGetAllRunning)},\n\n\t\t// Generic static data\n\t\trest.Route{\"GET\", \"/favicon.ico\", favIcon},\n\t\trest.Route{\"GET\", \"/static*resource\", staticData},\n\t}\n\n\t// Hardcoding these target URLs for now.\n\t// TODO: When internal services are allowed to run on other hosts, look that up.\n\troutes = routeToInternalServiceProxy(\"/api/controlplane/elastic\", \"http://127.0.0.1:9100/\", routes)\n\troutes = routeToInternalServiceProxy(\"/metrics\", \"http://127.0.0.1:8888/\", routes)\n\n\treturn routes\n}",
"func (Ca) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/ca/crl/\",\n\t\t\"/api/objects/ca/crl/{ref}\",\n\t\t\"/api/objects/ca/crl/{ref}/usedby\",\n\t\t\"/api/objects/ca/csr/\",\n\t\t\"/api/objects/ca/csr/{ref}\",\n\t\t\"/api/objects/ca/csr/{ref}/usedby\",\n\t\t\"/api/objects/ca/group/\",\n\t\t\"/api/objects/ca/group/{ref}\",\n\t\t\"/api/objects/ca/group/{ref}/usedby\",\n\t\t\"/api/objects/ca/host_cert/\",\n\t\t\"/api/objects/ca/host_cert/{ref}\",\n\t\t\"/api/objects/ca/host_cert/{ref}/usedby\",\n\t\t\"/api/objects/ca/host_key_cert/\",\n\t\t\"/api/objects/ca/host_key_cert/{ref}\",\n\t\t\"/api/objects/ca/host_key_cert/{ref}/usedby\",\n\t\t\"/api/objects/ca/http_verification_ca/\",\n\t\t\"/api/objects/ca/http_verification_ca/{ref}\",\n\t\t\"/api/objects/ca/http_verification_ca/{ref}/usedby\",\n\t\t\"/api/objects/ca/meta_crl/\",\n\t\t\"/api/objects/ca/meta_crl/{ref}\",\n\t\t\"/api/objects/ca/meta_crl/{ref}/usedby\",\n\t\t\"/api/objects/ca/meta_x509/\",\n\t\t\"/api/objects/ca/meta_x509/{ref}\",\n\t\t\"/api/objects/ca/meta_x509/{ref}/usedby\",\n\t\t\"/api/objects/ca/rsa/\",\n\t\t\"/api/objects/ca/rsa/{ref}\",\n\t\t\"/api/objects/ca/rsa/{ref}/usedby\",\n\t\t\"/api/objects/ca/signing_ca/\",\n\t\t\"/api/objects/ca/signing_ca/{ref}\",\n\t\t\"/api/objects/ca/signing_ca/{ref}/usedby\",\n\t\t\"/api/objects/ca/verification_ca/\",\n\t\t\"/api/objects/ca/verification_ca/{ref}\",\n\t\t\"/api/objects/ca/verification_ca/{ref}/usedby\",\n\t}\n}",
"func (Dyndns) ApiRoutes() []string {\n\treturn []string{\n\t\t\"/api/objects/dyndns/dyndns/\",\n\t\t\"/api/objects/dyndns/dyndns/{ref}\",\n\t\t\"/api/objects/dyndns/dyndns/{ref}/usedby\",\n\t\t\"/api/objects/dyndns/group/\",\n\t\t\"/api/objects/dyndns/group/{ref}\",\n\t\t\"/api/objects/dyndns/group/{ref}/usedby\",\n\t}\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewCmdSnapshot adds command for operating on snapshot
|
func NewCmdSnapshot() *cobra.Command {
cmd := &cobra.Command{
Use: "snapshot",
Short: "Provides operations related to a Volume snapshot",
Long: snapshotCommandHelpText,
}
cmd.AddCommand(
NewCmdSnapshotCreate(),
NewCmdSnapshotList(),
NewCmdSnapshotRevert(),
)
cmd.PersistentFlags().StringVarP(&options.namespace, "namespace", "n", options.namespace,
"namespace name, required if volume is not in the default namespace")
return cmd
}
|
[
"func NewSnapshotCommand() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"snapshot <subcommand>\",\n\t\tShort: \"Manages etcd node snapshots\",\n\t}\n\tcmd.AddCommand(NewSnapshotSaveCommand())\n\tcmd.AddCommand(NewSnapshotRestoreCommand())\n\tcmd.AddCommand(newSnapshotStatusCommand())\n\treturn cmd\n}",
"func Snapshot() *Command {\n\tcmd := &Command{\n\t\tCommand: &cobra.Command{\n\t\t\tUse: \"snapshot\",\n\t\t\tAliases: []string{\"s\"},\n\t\t\tShort: \"Access and manage snapshots\",\n\t\t\tLong: \"The subcommands of `doctl compute snapshot` allow you to manage and retrieve information about Droplet and block storage volume snapshots.\",\n\t\t},\n\t}\n\n\tsnapshotDetail := `\n\n - The snapshot's ID\n - The snapshot's name\n - The date and time when the snapshot was created\n - The slugs of the datacenter regions in which the snapshot is available\n - The type of resource the snapshot was made from, Droplet or volume, and its ID\n - The minimum size in GB required for a Droplet or volume to use this snapshot\n - The compressed, billable size of the snapshot\n`\n\n\tcmdRunSnapshotList := CmdBuilder(cmd, RunSnapshotList, \"list [glob]\",\n\t\t\"List Droplet and volume snapshots\", \"List information about Droplet and block storage volume snapshots, including:\"+snapshotDetail,\n\t\tWriter, aliasOpt(\"ls\"), displayerType(&displayers.Snapshot{}))\n\tAddStringFlag(cmdRunSnapshotList, doctl.ArgResourceType, \"\", \"\", \"Filter by resource type (`droplet` or `volume`)\")\n\tAddStringFlag(cmdRunSnapshotList, doctl.ArgRegionSlug, \"\", \"\", \"Filter by regional availability\")\n\n\tCmdBuilder(cmd, RunSnapshotGet, \"get <snapshot-id>...\",\n\t\t\"Retrieve a Droplet or volume snapshot\", \"Retrieve information about a Droplet or block storage volume snapshot, including:\"+snapshotDetail,\n\t\tWriter, aliasOpt(\"g\"), displayerType(&displayers.Snapshot{}))\n\n\tcmdRunSnapshotDelete := CmdBuilder(cmd, RunSnapshotDelete, \"delete <snapshot-id>...\",\n\t\t\"Delete a snapshot of a Droplet or volume\", \"Delete a snapshot of a Droplet or volume by specifying its ID.\",\n\t\tWriter, aliasOpt(\"d\", \"rm\"), displayerType(&displayers.Snapshot{}))\n\tAddBoolFlag(cmdRunSnapshotDelete, doctl.ArgForce, doctl.ArgShortForce, false, \"Delete the snapshot without confirmation\")\n\n\treturn cmd\n}",
"func Snapshot() *cobra.Command {\n\tcmd := &cobra.Command{\n\t\tUse: \"snapshot\",\n\t\tAliases: []string{\"sn\"},\n\t\tShort: \"snapshot commands\",\n\t\tLong: `snapshot is used to access snapshot commands`,\n\t}\n\n\tcmd.AddCommand(snapshotCreate)\n\tcmd.AddCommand(snapshotCreateFromURL)\n\tcmd.AddCommand(snapshotDelete)\n\tcmd.AddCommand(snapshotList)\n\n\tsnapshotCreate.Flags().StringP(\"id\", \"i\", \"\", \"ID of the virtual machine to create a snapshot from.\")\n\tsnapshotCreate.Flags().StringP(\"description\", \"d\", \"\", \"(optional) Description of snapshot contents\")\n\tsnapshotCreate.MarkFlagRequired(\"id\")\n\n\tsnapshotCreateFromURL.Flags().StringP(\"url\", \"u\", \"\", \"Remote URL from where the snapshot will be downloaded.\")\n\tsnapshotCreateFromURL.MarkFlagRequired(\"url\")\n\n\treturn cmd\n}",
"func newSnapshot(name, namespace, className, boundToContent, snapshotUID, claimName string, ready bool, err *crdv1.VolumeSnapshotError, creationTime *metav1.Time, size *resource.Quantity) *crdv1.VolumeSnapshot {\n\tsnapshot := crdv1.VolumeSnapshot{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tName: name,\n\t\t\tNamespace: namespace,\n\t\t\tUID: types.UID(snapshotUID),\n\t\t\tResourceVersion: \"1\",\n\t\t\tSelfLink: \"/apis/snapshot.storage.k8s.io/v1beta1/namespaces/\" + \"default\" + \"/volumesnapshots/\" + name,\n\t\t},\n\t\tSpec: crdv1.VolumeSnapshotSpec{\n\t\t\tSource: crdv1.VolumeSnapshotSource{\n\t\t\t\tPersistentVolumeClaimName: &claimName,\n\t\t\t},\n\t\t\tVolumeSnapshotClassName: &className,\n\t\t},\n\t\tStatus: &crdv1.VolumeSnapshotStatus{\n\t\t\tBoundVolumeSnapshotContentName: &boundToContent,\n\t\t\tCreationTime: creationTime,\n\t\t\tReadyToUse: &ready,\n\t\t\tError: err,\n\t\t\tRestoreSize: size,\n\t\t},\n\t}\n\n\treturn &snapshot\n}",
"func GetSnapshotCommand(repoIdentifier, passwordFile string, tags map[string]string) *Command {\n\treturn &Command{\n\t\tCommand: \"snapshots\",\n\t\tRepoIdentifier: repoIdentifier,\n\t\tPasswordFile: passwordFile,\n\t\t// \"--last\" is replaced by \"--latest=1\" in restic v0.12.1\n\t\tExtraFlags: []string{\"--json\", \"--latest=1\", getSnapshotTagFlag(tags)},\n\t}\n}",
"func testCreateSnapshot(t *testing.T, volId string, snapName string) string {\n\tcli := fmt.Sprintf(\"px create volumesnapshot %s %s\", volId, snapName)\n\tlines := executeCli(cli)\n\tassert.Equal(t, 2, len(lines), \"Output does not match\")\n\tassert.Contains(t, lines[0], \"Snapshot of \"+volId+\" created with id\", \"expected message not received\")\n\twords := strings.Split(lines[0], \" \")\n\tassert.Equal(t, len(words), 7, \"expected message not received\")\n\t// The last item in the message is the id\n\treturn words[len(words)-1]\n}",
"func TestCmdSnapshot(t *testing.T) {\n\tassert := asrt.New(t)\n\n\ttestDir, _ := os.Getwd()\n\tfmt.Println(testDir)\n\tsite := TestSites[0]\n\tcleanup := site.Chdir()\n\tapp, err := ddevapp.NewApp(site.Dir, false, \"\")\n\tassert.NoError(err)\n\tdefer func() {\n\t\t// Make sure all databases are back to default empty\n\t\t_ = app.Stop(true, false)\n\t\t_ = app.Start()\n\t\tcleanup()\n\t}()\n\n\t// Ensure that a snapshot can be created\n\targs := []string{\"snapshot\", \"--name\", \"test-snapshot\"}\n\tout, err := exec.RunCommand(DdevBin, args)\n\tassert.NoError(err)\n\tassert.Contains(string(out), \"Created snapshot test-snapshot\")\n\n\t// Try to delete a not existing snapshot\n\targs = []string{\"snapshot\", \"--name\", \"not-existing-snapshot\", \"--cleanup\", \"--yes\"}\n\tout, err = exec.RunCommand(DdevBin, args)\n\tassert.Error(err)\n\tassert.Contains(string(out), \"Failed to delete snapshot\")\n\n\t// Ensure that an existing snapshot can be deleted\n\targs = []string{\"snapshot\", \"--name\", \"test-snapshot\", \"--cleanup\"}\n\tout, err = exec.RunCommand(DdevBin, args)\n\tassert.NoError(err)\n\tassert.Contains(string(out), \"Deleted database snapshot test-snapshot\")\n}",
"func newSnapshot(txn *dbTxn) *snapshot {\n\treturn &snapshot{\n\t\tdbTxn: txn,\n\t}\n}",
"func (vmrun *CLIVmrun) Snapshot(vmx string, name string) error {\n\t_, err := exec.Command(vmrun.vmrunPath, \"-T\", \"fusion\", \"snapshot\", vmx, name).Output()\n\treturn err\n}",
"func NewSnapshot(ctx *pulumi.Context,\n\tname string, args *SnapshotArgs, opts ...pulumi.ResourceOption) (*Snapshot, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.InstanceId == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'InstanceId'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Snapshot\n\terr := ctx.RegisterResource(\"alicloud:databasefilesystem/snapshot:Snapshot\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func FSPostSnapshotCmd(fstype, device string) []string {\n\tswitch fstype {\n\tcase \"xfs\":\n\t\treturn []string{\"xfs_admin\", \"-U\", \"generate\", device}\n\tcase \"ext2\", \"ext3\", \"ext4\", \"ext4dev\":\n\t\treturn []string{\"tune2fs\", \"-U\", \"time\", device}\n\t}\n\treturn nil\n}",
"func Command(app *kingpin.Application) {\n\tc := new(command)\n\n\tcmd := app.Command(\"snapshot\", \"Takes a snapshot of the existing Docker Compose stack.\").Action(c.run)\n\n\tcmd.Flag(\"config\", \"Config file to load.\").Default(\".rig.yml\").Envar(\"RIG_CONFIG\").StringVar(&c.Config)\n\n\t// Information used to run the correct images.\n\tcmd.Flag(\"repository\", \"Tag to apply to all images when performing a snapshot.\").Required().Envar(\"RIG_REPOSITORY\").StringVar(&c.Repository)\n\tcmd.Flag(\"username\", \"Username used to authenticate with the registry.\").Required().Envar(\"RIG_USERNAME\").StringVar(&c.Username)\n\tcmd.Flag(\"password\", \"Password used to authenticate with the registry.\").Required().Envar(\"RIG_PASSWORD\").StringVar(&c.Password)\n\tcmd.Arg(\"tag\", \"Tag to apply to all images when performing a snapshot.\").Required().StringVar(&c.Tag)\n}",
"func (s *Store) NewSnapshot() *rdb.Snapshot { return s.db.NewSnapshot() }",
"func (s *SnapshotHandler) generateNewSnapshot() {\n\t// Generate new snapshot version.\n\tsnapshotVersion := s.newSnapshotVersion()\n\n\t// Create an snapshot with all xDS resources.\n\tsnapshot := cache.NewSnapshot(snapshotVersion,\n\t\tasResources(s.resources[envoy_xds.Endpoint].Contents()),\n\t\tasResources(s.resources[envoy_xds.Cluster].Contents()),\n\t\tasResources(s.resources[envoy_xds.Route].Contents()),\n\t\tasResources(s.resources[envoy_xds.Listener].Contents()),\n\t\tnil)\n\n\t// Update the Secrets xDS resource manually until a new version of go-control-plane is released.\n\t// ref: https://github.com/envoyproxy/go-control-plane/pull/314\n\tsnapshot.Resources[envoy_xds.Secret] = cache.NewResources(snapshotVersion, asResources(s.resources[envoy_xds.Secret].Contents()))\n\n\tif err := s.snapshotCache.SetSnapshot(xds.DefaultHash.String(), snapshot); err != nil {\n\t\ts.Errorf(\"OnChange: Error setting snapshot: %q\", err)\n\t}\n}",
"func createSnapshot(sg *snapshotgroup.SnapshotGroup, annotations map[string]string) error {\n\ttimestamp := strconv.Itoa(int(time.Now().Unix()))\n\tannotations[TimestampAnnotation] = timestamp\n\tannotations[managedByAnnotation] = managerName\n\tannotations[GroupNameAnnotation] = sg.ObjectMeta.Name\n\n\tsnapshot := snapshotsv1.VolumeSnapshot{\n\t\tObjectMeta: metav1.ObjectMeta{\n\t\t\tNamespace: sg.ObjectMeta.Namespace,\n\t\t\tName: sg.ObjectMeta.Name + \"-\" + timestamp,\n\t\t\tAnnotations: annotations,\n\t\t},\n\t\tSpec: sg.Spec.Template.Spec,\n\t}\n\tname := getPVCName(sg)\n\tklog.Infof(\"%s/%s: creating snapshot for PVC %s\", sg.ObjectMeta.Namespace, sg.ObjectMeta.Name, name)\n\tsnapshot.Spec.Source.PersistentVolumeClaimName = &name\n\n\tmarshaled, err := json.Marshal(snapshot)\n\tif err != nil {\n\t\treturn err\n\t}\n\tunst := unstructured.Unstructured{\n\t\tObject: map[string]interface{}{},\n\t}\n\terr = json.Unmarshal(marshaled, &unst.Object)\n\tif err != nil {\n\t\treturn err\n\t}\n\tclient := kube.GetClient()\n\tunst.Object[\"kind\"] = \"VolumeSnapshot\"\n\tunst.Object[\"apiVersion\"] = client.VolumeSnapshotVersion\n\n\tif strings.HasSuffix(client.VolumeSnapshotVersion, \"v1alpha1\") {\n\t\t// There is a slight change in `source` from alpha to beta\n\t\tspec := unst.Object[\"spec\"].(map[string]interface{})\n\t\tsource := spec[\"source\"].(map[string]interface{})\n\t\tdelete(source, \"persistentVolumeClaimName\")\n\t\tsource[\"name\"] = name\n\t\tsource[\"kind\"] = \"PersistentVolumeClaim\"\n\t\tspec[\"source\"] = source\n\t\tunst.Object[\"spec\"] = spec\n\t}\n\n\tsnapClient := client.SnapshotClient.Namespace(snapshot.ObjectMeta.Namespace)\n\t_, err = snapClient.Create(&unst, metav1.CreateOptions{})\n\treturn err\n}",
"func NewSnapshot(ctx *pulumi.Context,\n\tname string, args *SnapshotArgs, opts ...pulumi.ResourceOption) (*Snapshot, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.NamespaceName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'NamespaceName'\")\n\t}\n\tif args.SnapshotName == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'SnapshotName'\")\n\t}\n\tvar resource Snapshot\n\terr := ctx.RegisterResource(\"aws:redshiftserverless/snapshot:Snapshot\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func (v *BtrfsVolume) Snapshot(label string) (err error) {\n\treturn BtrfsCmd(\"subvolume\", \"snapshot\", \"-r\", v.Dir(), path.Join(v.baseDir, label)).Run()\n}",
"func NewSnapshot(ctx *pulumi.Context,\n\tname string, args *SnapshotArgs, opts ...pulumi.ResourceOption) (*Snapshot, error) {\n\tif args == nil {\n\t\treturn nil, errors.New(\"missing one or more required arguments\")\n\t}\n\n\tif args.Instance == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Instance'\")\n\t}\n\tif args.Location == nil {\n\t\treturn nil, errors.New(\"invalid value for required argument 'Location'\")\n\t}\n\topts = internal.PkgResourceDefaultOpts(opts)\n\tvar resource Snapshot\n\terr := ctx.RegisterResource(\"gcp:filestore/snapshot:Snapshot\", name, args, &resource, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &resource, nil\n}",
"func MakeInstanceSnapshot(svc rdsiface.RDSAPI, instance *string) error {\n // snippet-start:[rds.go.create_instance_snapshot.call]\n // Get the current date and time to uniquely identify snapshot\n currentTime := time.Now()\n t := currentTime.Format(\"2006-01-02 15:04:05\")\n // Replace space with underscore for snapshot ID\n t = strings.Replace(t, \" \", \"_\", -1)\n\n _, err := svc.CreateDBSnapshot(&rds.CreateDBSnapshotInput{\n DBInstanceIdentifier: instance,\n DBSnapshotIdentifier: aws.String(*instance + t),\n })\n // snippet-end:[rds.go.create_instance_snapshot.call]\n if err != nil {\n return err\n }\n\n return nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
IsDNS1123Label tests for a string that conforms to the definition of a label in DNS (RFC 1123).
|
func IsDNS1123Label(value string) bool {
if len(value) > dns1123LabelMaxLength {
return false
}
if !dns1123LabelRegexp.MatchString(value) {
return false
}
return true
}
|
[
"func NameIsDNSLabel(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1123Label(name)\n}",
"func validDNSLabel(s string) bool {\n\tif len(s) > 63 {\n\t\treturn false\n\t}\n\n\tfor i, r := range s {\n\t\tif i == 0 || i == len(s)-1 {\n\t\t\tif (r < 'a' || r > 'z') && (r < '0' || r > '9') {\n\t\t\t\treturn false\n\t\t\t}\n\t\t} else {\n\t\t\tif (r < 'a' || r > 'z') && (r < '0' || r > '9') && (r != '-') {\n\t\t\t\treturn false\n\t\t\t}\n\t\t}\n\t}\n\n\treturn true\n}",
"func NameIsDNS1035Label(name string, prefix bool) []string {\n\tif prefix {\n\t\tname = maskTrailingDash(name)\n\t}\n\treturn validation.IsDNS1035Label(name)\n}",
"func isDnsRFC1035LabelFormat(fl FieldLevel) bool {\n\tval := fl.Field().String()\n\treturn dnsRegexRFC1035Label.MatchString(val)\n}",
"func IsValidLabel(label string) []string {\n\tvar labelerrs []string\n\n\texpectLabelName := false\n\texpectLabelPrefix := false\n\n\t// split label up into prefix, name and value\n\t// format: prefix/name=value\n\tvar labelprefix, labelname, labelvalue string\n\n\tkv := strings.SplitN(label, \"=\", 2)\n\tif len(kv) == 1 {\n\t\tlabelprefix = \"\"\n\t\tlabelname = \"\"\n\t\tlabelvalue = kv[0]\n\t} else {\n\t\tpn := strings.SplitN(kv[0], \"/\", 2)\n\t\tif len(pn) == 1 {\n\t\t\tlabelprefix = \"\"\n\t\t\tlabelname = pn[0]\n\t\t} else {\n\t\t\tlabelprefix = pn[0]\n\t\t\tlabelname = pn[1]\n\t\t\texpectLabelPrefix = true\n\t\t}\n\t\tlabelvalue = kv[1]\n\t\t// if \"=\" was in the label input, then expect a non-zero length name\n\t\texpectLabelName = true\n\t}\n\n\t// check label prefix validity - prefix is optional\n\tif len(labelprefix) > 0 {\n\t\terrs := validation.IsDNS1123Subdomain(labelprefix)\n\t\tif len(errs) > 0 {\n\t\t\tlabelerrs = append(labelerrs, \"Invalid label prefix - label=[\"+label+\"%], labelprefix=[\"+labelprefix+\"], errors: \")\n\t\t\tfor _, err := range errs {\n\t\t\t\tlabelerrs = append(labelerrs, err)\n\t\t\t}\n\t\t}\n\t} else if expectLabelPrefix {\n\t\tlabelerrs = append(labelerrs, \"Invalid label prefix - label=[\"+label+\"%], labelprefix=[\"+labelprefix+\"]\")\n\t}\n\tif expectLabelName {\n\t\terrs := validation.IsDNS1123Label(labelname)\n\t\tif len(errs) > 0 {\n\t\t\tlabelerrs = append(labelerrs, \"Invalid label name - label=[\"+label+\"%], labelname=[\"+labelname+\"], errors: \")\n\t\t\tfor _, err := range errs {\n\t\t\t\tlabelerrs = append(labelerrs, err)\n\t\t\t}\n\t\t}\n\t}\n\tif len(labelvalue) > 0 {\n\t\terrs := validation.IsValidLabelValue(labelvalue)\n\t\tif len(errs) > 0 {\n\t\t\tlabelerrs = append(labelerrs, \"Invalid label value - label=[\"+label+\"%], labelvalue=[\"+labelvalue+\"], errors: \")\n\t\t\tfor _, err := range errs {\n\t\t\t\tlabelerrs = append(labelerrs, err)\n\t\t\t}\n\t\t}\n\t} else {\n\t\t// expect a non-zero value\n\t\tlabelerrs = append(labelerrs, \"Invalid label value - label=[\"+label+\"%], labelvalue=[\"+labelvalue+\"]\")\n\t}\n\n\treturn labelerrs\n}",
"func DNSLabel(value string) error {\n\tre := `^([a-zA-Z0-9]{1}[a-zA-Z0-9_-]{0,62}){1}(\\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*?$`\n\tif !regexp.MustCompile(re).MatchString(value) {\n\t\treturn fmt.Errorf(\"value '%s' must match '%s' regexp (DNS label, RFC 1123)\", value, re)\n\t}\n\n\treturn nil\n}",
"func FormatToDNS1123(name string) string {\n\treturn strings.ToLower(strings.ReplaceAll(name, \"_\", \"-\"))\n}",
"func IsRFC1123CompliantClusterName(clusterName string) bool {\n\treturn !strings.Contains(clusterName, \"_\")\n}",
"func IsDNSName(str string) bool {\n\tif str == \"\" || len(strings.Replace(str, \".\", \"\", -1)) > 255 {\n\t\t// constraints already violated\n\t\treturn false\n\t}\n\treturn !IsIP(str) && rxDNSName.MatchString(str)\n}",
"func ValidLabel(label string) bool {\n\treturn len(label) <= maxLabel && labelRegex.Match([]byte(label))\n}",
"func IsDomainName(s string) (labels int, ok bool) {\n\t// XXX: The logic in this function was copied from packDomainName and\n\t// should be kept in sync with that function.\n\n\tconst lenmsg = 256\n\n\tif len(s) == 0 { // Ok, for instance when dealing with update RR without any rdata.\n\t\treturn 0, false\n\t}\n\n\ts = Fqdn(s)\n\n\t// Each dot ends a segment of the name. Except for escaped dots (\\.), which\n\t// are normal dots.\n\n\tvar (\n\t\toff int\n\t\tbegin int\n\t\twasDot bool\n\t)\n\tfor i := 0; i < len(s); i++ {\n\t\tswitch s[i] {\n\t\tcase '\\\\':\n\t\t\tif off+1 > lenmsg {\n\t\t\t\treturn labels, false\n\t\t\t}\n\n\t\t\t// check for \\DDD\n\t\t\tif i+3 < len(s) && isDigit(s[i+1]) && isDigit(s[i+2]) && isDigit(s[i+3]) {\n\t\t\t\ti += 3\n\t\t\t\tbegin += 3\n\t\t\t} else {\n\t\t\t\ti++\n\t\t\t\tbegin++\n\t\t\t}\n\n\t\t\twasDot = false\n\t\tcase '.':\n\t\t\tif wasDot {\n\t\t\t\t// two dots back to back is not legal\n\t\t\t\treturn labels, false\n\t\t\t}\n\t\t\twasDot = true\n\n\t\t\tlabelLen := i - begin\n\t\t\tif labelLen >= 1<<6 { // top two bits of length must be clear\n\t\t\t\treturn labels, false\n\t\t\t}\n\n\t\t\t// off can already (we're in a loop) be bigger than lenmsg\n\t\t\t// this happens when a name isn't fully qualified\n\t\t\toff += 1 + labelLen\n\t\t\tif off > lenmsg {\n\t\t\t\treturn labels, false\n\t\t\t}\n\n\t\t\tlabels++\n\t\t\tbegin = i + 1\n\t\tdefault:\n\t\t\twasDot = false\n\t\t}\n\t}\n\n\treturn labels, true\n}",
"func RFC1123(name string) string {\n\treturn string(label([]byte(name), 63, \"-\", \"-\"))\n}",
"func IsHostname(str string) bool {\n\tif !rxHostname.MatchString(str) {\n\t\treturn false\n\t}\n\n\t// the sum of all label octets and label lengths is limited to 255.\n\tif len(str) > 255 {\n\t\treturn false\n\t}\n\n\t// Each node has a label, which is zero to 63 octets in length\n\tparts := strings.Split(str, \".\")\n\tvalid := true\n\tfor _, p := range parts {\n\t\tif len(p) > 63 {\n\t\t\tvalid = false\n\t\t}\n\t}\n\treturn valid\n}",
"func DNSName(str string) bool {\n\tif str == \"\" || len(strings.Replace(str, \".\", \"\", -1)) > 255 {\n\t\t// constraints already violated\n\t\treturn false\n\t}\n\treturn rxDNSName.MatchString(str)\n}",
"func validateDockerLabel(dockerLabel string) (string, error) {\n\tdockerLabel = sanitize(dockerLabel)\n\tif dockerLabel == \"\" {\n\t\treturn \"dd-dns.hostname\", nil\n\t}\n\treturn dockerLabel, nil\n}",
"func LabelIsValid(label string) bool {\n\tcLabel := C.CString(label)\n\tdefer C.free(unsafe.Pointer(cLabel))\n\n\treturn bool(C.daos_label_is_valid(cLabel))\n}",
"func IsMSSQLLabel(s string) bool {\n\tif len(s) < 2 {\n\t\treturn false\n\t}\n\tif string(s[len(s)]) == \":\" && IsMSSQLIdentifier(s[0:len(s)-1]) {\n\t\treturn true\n\t}\n\treturn false\n}",
"func ValidateLabel(label string) error {\n\tif labelRegexp.Match([]byte(label)) == false {\n\t\treturn ErrLabel\n\t}\n\treturn nil\n}",
"func toDNS1123Subdomain(name string) string {\n\t// If it is not a valid DNS1123 subdomain, make it a valid one.\n\tif msgs := validation.IsDNS1123Subdomain(name); len(msgs) != 0 {\n\t\t// If the length exceeds the max, cut it and leave some room for a potential generated UUID.\n\t\tif len(name) > validation.DNS1123SubdomainMaxLength {\n\t\t\tname = name[:validation.DNS1123SubdomainMaxLength-generateNameSafety]\n\t\t}\n\t\tname = strings.ToLower(name)\n\t\tname = validChars.ReplaceAllString(name, \"\")\n\t\t// Only start/end with alphanumeric.\n\t\tname = strings.Trim(name, \"-.\")\n\t}\n\treturn name\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
getTemplatingSource fetches template source files and adds them to a data set to be used when running the template function
|
func getTemplatingSource(spec *opsv1alpha1.GitOps) (map[string]interface{}, error) {
if spec.Spec.Templating != nil {
sourceDir := spec.Status.RootFolder + "/" + spec.Spec.RootFolder + "/" + spec.Spec.Templating.SourceFolder
if spec.Spec.Templating.SourceFolder != "" {
sourceDir += "/"
}
t := spec.Spec.Templating
if t.Enabled {
if t.Source != nil {
data := make(map[string]interface{})
for _, f := range t.Source.TemplateDataFile {
temp := make(map[string]interface{})
fData, err := ioutil.ReadFile(sourceDir + f)
if err != nil {
log.Error(err, "Failed to read file")
return nil, err
}
yaml.Unmarshal(fData, temp)
for k, v := range temp {
data[k] = v
}
}
return data, nil
}
}
return nil, nil
}
return nil, nil
}
|
[
"func getTemplateSource() templateSource {\n\t// do lazy init to avoid zip decompression unless absolutely necessary\n\ttemplatesOnce.Do(func() {\n\t\ttemplates = &fsTemplateSource{\n\t\t\tfs: http.FS(templatesFs),\n\t\t\tnamingScheme: func(language extension.Language, category extension.Category, template string) string {\n\t\t\t\treturn \"/\" + path.Join(language.String(), category.String(), template)\n\t\t\t},\n\t\t}\n\t})\n\treturn templates\n}",
"func getTemplate(tmpls []string) *template.Template {\n\treturn template.Must(template.ParseFiles(tmpls...))\n}",
"func addSourceFile(t *Template, typ sourceType, file string) {}",
"func GetRawTemplate(ectx echo.Context, templateName string, data map[string]string) string {\n\t// Getting main template.\n\ttplRaw, err := assets.Data.ReadFile(templateName)\n\tif err != nil {\n\t\t_ = ectx.String(http.StatusBadRequest, templateName+\" not found.\")\n\n\t\treturn \"\"\n\t}\n\n\ttpl := string(tplRaw)\n\t// Replace placeholders with data from data map.\n\tfor placeholder, value := range data {\n\t\ttpl = strings.Replace(tpl, \"{\"+placeholder+\"}\", value, -1)\n\t}\n\n\treturn tpl\n}",
"func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\ttmpPath := path.Join(revel.AppPath, dir)\n\terr := os.RemoveAll(tmpPath)\n\tif err != nil {\n\t\trevel.ERROR.Println(\"Failed to remove dir:\", err)\n\t}\n\terr = os.Mkdir(tmpPath, 0777)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to make tmp directory: %v\", err)\n\t}\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(tmpPath, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}",
"func (a *templateLoader) Get(tmpl string) (io.Reader, error) {\n\tvar b []byte\n\tvar e error\n\ttmpl += a.ext\n\tif a.mgr != nil && a.mgr.Caches != nil {\n\t\tk := strings.TrimPrefix(tmpl, a.templateDir)\n\t\tb, e = a.mgr.GetTemplate(k)\n\t}\n\tif b == nil || e != nil {\n\t\tif e != nil {\n\t\t\ta.logger.Error(e)\n\t\t}\n\t\tb, e = ioutil.ReadFile(tmpl)\n\t}\n\tbuf := new(bytes.Buffer)\n\tbuf.WriteString(string(b))\n\treturn buf, e\n}",
"func (g *Generator) prepare(gen *FileMapGenerate) (*template.Template, error) {\n\t// Preload the function map (or else the functions will fail when\n\t// called due to a lack of valid context).\n\tvar (\n\t\tt = template.New(\"\").Funcs(Preload)\n\t\terr error\n\t)\n\n\t// Parse the included template files.\n\tfor _, inc := range gen.Include {\n\t\t_, err := g.loadTemplate(t, inc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Parse the template file to execute.\n\ttmpl, err := g.loadTemplate(t, gen.Template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t_, name := path.Split(gen.Template)\n\ttmpl = tmpl.Lookup(name)\n\treturn tmpl, nil\n}",
"func GetTemplate(r *registry.Registry) *template.Template {\n\tt := template.New(\"file\")\n\tt = t.Funcs(sprig.TxtFuncMap())\n\n\tt = t.Funcs(template.FuncMap{\n\t\t\"include\": include(t),\n\t\t\"tsType\": func(fieldType data.Type) string {\n\t\t\treturn tsType(r, fieldType)\n\t\t},\n\t\t\"renderURL\": renderURL(r),\n\t\t\"buildInitReq\": buildInitReq,\n\t\t\"fieldName\": fieldName(r),\n\t})\n\n\tt = template.Must(t.Parse(tmpl))\n\treturn t\n}",
"func gatherTemplates(cfg *config.Config, outFileNamer func(string) (string, error)) (templates []*tplate, err error) {\n\tmode, modeOverride, err := cfg.GetMode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\t// the arg-provided input string gets a special name\n\tcase cfg.Input != \"\":\n\t\ttemplates = []*tplate{{\n\t\t\tname: \"<arg>\",\n\t\t\tcontents: cfg.Input,\n\t\t\tmode: mode,\n\t\t\tmodeOverride: modeOverride,\n\t\t\ttargetPath: cfg.OutputFiles[0],\n\t\t}}\n\tcase cfg.InputDir != \"\":\n\t\t// input dirs presume output dirs are set too\n\t\ttemplates, err = walkDir(cfg.InputDir, outFileNamer, cfg.ExcludeGlob, mode, modeOverride)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase cfg.Input == \"\":\n\t\ttemplates = make([]*tplate, len(cfg.InputFiles))\n\t\tfor i := range cfg.InputFiles {\n\t\t\ttemplates[i], err = fileToTemplates(cfg.InputFiles[i], cfg.OutputFiles[i], mode, modeOverride)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn processTemplates(cfg, templates)\n}",
"func genSource(dir, filename, templateSource string, args map[string]interface{}) {\n\tsourceCode := revel.ExecuteTemplate(\n\t\ttemplate.Must(template.New(\"\").Parse(templateSource)),\n\t\targs)\n\n\t// Create a fresh dir.\n\t// tmpPath := path.Join(revel.AppPath, dir)\n\n\t// Create the file\n\tfile, err := os.Create(path.Join(dir, filename))\n\tdefer file.Close()\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to create file: %v\", err)\n\t}\n\t_, err = file.WriteString(sourceCode)\n\tif err != nil {\n\t\trevel.ERROR.Fatalf(\"Failed to write to file: %v\", err)\n\t}\n}",
"func (t TemplateToCompile) getData(name string) (interface{}, error) {\n\tif ret, ok := t.TemplatesData[name]; ok {\n\t\treturn ret, nil\n\t}\n\tif ret, ok := t.TemplatesData[\"*\"]; ok {\n\t\treturn ret, nil\n\t}\n\treturn nil, fmt.Errorf(\"Template data configuration not found for %v\", name)\n}",
"func (self templateEngine) loadTemplate(name string) (t string) {\n b, err := ioutil.ReadFile(self.templateFilepath(name))\n if err == nil {\n t = string(b)\n } else {\n log.Println(\"error loading template\", err)\n t = err.Error()\n }\n return\n}",
"func (t *localTemplate) SourcePath() string {\n\treturn t.sourcePath\n}",
"func (i *ImageTemplateSource) GetImageTemplateSource() *ImageTemplateSource { return i }",
"func addSourceFile(t *Template, typ sourceType, file string) {\n\tt.parseFilesSources = append(t.parseFilesSources, parseFileSources{\n\t\tType: typ,\n\t\tFile: file,\n\t})\n}",
"func TemplateConfig(frontendPath string) (map[string]*template.Template, error) {\n\t// Transform frontendPath to an absolute path\n\tfp, err := filepath.Abs(frontendPath)\n\tif err != nil {\n\t\tLog.Critical(\"frontend path could not be resolved.\")\n\t\tpanic(err)\n\t}\n\n\ttemplateSet := make(map[string]*template.Template)\n\n\tfuncMap := template.FuncMap{\n\t\t\"TGGetBotName\": TGGetBotName,\n\t\t\"TGGetBotID\": TGGetBotID,\n\t\t\"TGRunning\": TGRunning,\n\t\t\"Webroot\": GetWebroot,\n\t\t\"WebAPIPath\": GetWebAPIPath,\n\t\t\"VEnlOne\": GetvEnlOne,\n\t\t\"EnlRocks\": GetEnlRocks,\n\t\t\"TeamMenu\": TeamMenu,\n\t\t\"OpUserMenu\": OpUserMenu,\n\t\t\"OpColorMenu\": OpColorMenu,\n\t}\n\n\tLog.Info(\"Including frontend templates from: \", fp)\n\tfiles, err := ioutil.ReadDir(fp)\n\tif err != nil {\n\t\tLog.Error(err)\n\t\treturn nil, err\n\t}\n\n\tfor _, f := range files {\n\t\tlang := f.Name()\n\t\tif f.IsDir() && len(lang) == 2 {\n\t\t\ttemplateSet[lang] = template.New(\"\").Funcs(funcMap) // one funcMap for all languages\n\t\t\t// load the masters\n\t\t\tmasterpath := path.Join(fp, \"master\", \"*\")\n\t\t\t_, err = templateSet[lang].ParseGlob(masterpath)\n\t\t\tif err != nil {\n\t\t\t\tLog.Error(err)\n\t\t\t}\n\t\t\t// overwrite with language specific\n\t\t\tlangpath := path.Join(fp, lang, \"*\")\n\t\t\t_, err = templateSet[lang].ParseGlob(langpath)\n\t\t\tif err != nil {\n\t\t\t\tLog.Error(err)\n\t\t\t}\n\t\t\tLog.Debugf(\"Templates for lang [%s] %s\", lang, templateSet[lang].DefinedTemplates())\n\t\t}\n\t}\n\tts = templateSet\n\treturn templateSet, nil\n}",
"func (t *Template) SourceFile() string {\n\treturn strings.Join([]string{t.Path, \".go\"}, \"\")\n}",
"func (p *playbooks) GetTemplate() ([]playbook.ConfigTemplate, error) {\n\n\t// Get templates list\n\ttemplates, _ := filepath.Glob(fmt.Sprintf(\"%s/*%s\", p.templatePath, tplSuffix))\n\n\tif templates == nil {\n\t\treturn nil, fmt.Errorf(\"no template files found in directory %s\", p.templatePath)\n\t}\n\n\tvar cfgTpl []playbook.ConfigTemplate\n\n\tfor _, templ := range templates {\n\t\ttpl := template.New(filepath.Base(templ))\n\n\t\tp.initFuncMap(tpl) // add custom template functions\n\n\t\ttpl, err := tpl.ParseFiles(templ)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"template cannot parse files: %v\", err)\n\t\t}\n\n\t\t// create config file from tpl by removing the .tpl extension\n\t\text := filepath.Ext(templ)\n\t\t_, configFile := filepath.Split(templ[0 : len(templ)-len(ext)])\n\n\t\tconfig := playbook.ConfigTemplate{\n\t\t\tName: configFile,\n\t\t\tTemplate: tpl,\n\t\t}\n\n\t\tcfgTpl = append(cfgTpl, config)\n\t}\n\n\treturn cfgTpl, nil\n}",
"func prepareTemplate(templateName string) (*template.Template, error) {\n\t// stat for .gotmpl file size\n\tfi, err := pkger.Stat(templateName)\n\tif err != nil {\n\t\tlog.Printf(\"Stat: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\n\ttf, err := pkger.Open(templateName)\n\tif err != nil {\n\t\tlog.Printf(\"Open: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\tdefer tf.Close()\n\n\t// read the template source from pkger\n\tbuf := make([]byte, fi.Size())\n\t_, err = tf.Read(buf)\n\tif err != nil {\n\t\tlog.Printf(\"Unable to read template %s\\n\", templateName)\n\t\treturn nil, err\n\t}\n\n\t// create the template\n\tt := template.Must(template.New(\"Entity model template\").Parse(string(buf)))\n\tif t == nil {\n\t\tlog.Printf(\"Parse: %v\\n\", err)\n\t\treturn nil, err\n\t}\n\treturn t, nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
templateFile takes one yaml file as input and runs Go template engine on the file. Output is written to output directory
|
func (t *templater) templateFile(workDir string, outDir string, file os.FileInfo, d map[string]interface{}) {
if strings.Contains(file.Name(), "yaml") {
filePath := workDir + "/" + file.Name()
tEx := templ.New(file.Name())
tEx.Funcs(templateFuncs(workDir))
tEx.ParseFiles(filePath)
b := bytes.NewBuffer([]byte{})
err := tEx.Execute(b, d)
if err != nil {
log.Error(err, "Failed to execute template")
}
newF, err := os.Create(outDir + "/" + file.Name())
if err != nil {
log.Error(err, "Failed to create file", "file", file.Name())
return
}
newF.Write(b.Bytes())
newF.Close()
}
}
|
[
"func Template(output string, tmplPath string, data any) error {\n\tb, err := os.ReadFile(tmplPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl := template.Must(template.New(\"test\").Parse(string(b)))\n\tvar sb strings.Builder\n\terr = tmpl.Execute(&sb, data)\n\tif err != nil {\n\t\treturn err\n\t}\n\terr = os.WriteFile(output, []byte(sb.String()), 0644) // nolint:gosec // Non-crypto use\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func ProcessTemplateFile(template string, bundle interface{}) ([]byte, error) {\n\tvar byteValue []byte\n\tvar err error\n\tif fs == nil {\n\t\ttf, err := os.Open(template)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdefer tf.Close()\n\t\tbyteValue, err = ioutil.ReadAll(tf)\n\t} else {\n\t\ttf, err := fs.Open(template)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbyteValue, err = ioutil.ReadAll(tf)\n\t\tdefer tf.Close()\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toutput, err := Template(string(byteValue), bundle)\n\tif err != nil {\n\t\treturn []byte{}, err\n\t}\n\treturn []byte(output), nil\n}",
"func ExecuteTemplateFromFile(boxed, to string, templateData interface{}) {\n\ttemplateString, err := ioutil.ReadFile(boxed)\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to find template file: %v\\n\", err)\n\t\tos.Exit(1)\n\t}\n\texecuteTemplateFromString(string(templateString), to, templateData)\n}",
"func ExampleTemplateProcessor_generate_files() {\n\tapi := new(struct {\n\t\tKey string `json:\"key\" yaml:\"key\"`\n\t\tValue string `json:\"value\" yaml:\"value\"`\n\t})\n\t// create the template\n\ttemplateFn := framework.TemplateProcessor{\n\t\t// Templates input\n\t\tTemplateData: api,\n\t\t// Templates\n\t\tResourceTemplates: []framework.ResourceTemplate{{\n\t\t\tTemplates: parser.TemplateFiles(\"testdata/example/templatefiles/deployment.template.yaml\"),\n\t\t}},\n\t}\n\tcmd := command.Build(templateFn, command.StandaloneEnabled, false)\n\t// mimic standalone mode: testdata/template/config.yaml will be parsed into `api`\n\tcmd.SetArgs([]string{filepath.Join(\"testdata\", \"example\", \"templatefiles\", \"config.yaml\")})\n\tif err := cmd.Execute(); err != nil {\n\t\t_, _ = fmt.Fprintf(cmd.ErrOrStderr(), \"%v\\n\", err)\n\t}\n\n\t// Output:\n\t// # Copyright 2021 The Kubernetes Authors.\n\t// # SPDX-License-Identifier: Apache-2.0\n\t//\n\t// apiVersion: apps/v1\n\t// kind: Deployment\n\t// metadata:\n\t// name: foo\n\t// namespace: default\n\t// annotations:\n\t// a: b\n}",
"func Template(tempName string, templatePath string, replacings ...Replacement) *os.File {\n\treplacedFile, err := ioutil.TempFile(\"/tmp\", tempName+\"-*.yaml\")\n\tExpect(err).ToNot(HaveOccurred())\n\n\ttemplateContent, err := ioutil.ReadFile(templatePath)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treplacedStr := \"\"\n\tfor _, rep := range replacings {\n\t\tcontent := \"\"\n\t\tif replacedStr == \"\" {\n\t\t\tcontent = string(templateContent)\n\t\t} else {\n\t\t\tcontent = replacedStr\n\t\t}\n\t\treplacedStr = strings.ReplaceAll(content, rep.Old, rep.New)\n\t}\n\n\terr = ioutil.WriteFile(replacedFile.Name(), []byte(replacedStr), 0644)\n\tExpect(err).ToNot(HaveOccurred())\n\n\treturn replacedFile\n}",
"func Template(t string, ps []*Path, vars []string) error {\n\t// template body as string\n\tvar outTemplate string\n\tswitch {\n\tcase t != \"\":\n\t\tdata, err := ioutil.ReadFile(viper.GetString(\"path-template\"))\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\toutTemplate = string(data)\n\tdefault:\n\t\toutTemplate = defTemplate\n\t}\n\n\ttmpl, err := template.New(\"output-template\").Parse(outTemplate)\n\tif err != nil {\n\t\treturn err\n\t}\n\tinput := &templateIntput{\n\t\tPaths: ps,\n\t\tVars: make(map[string]string),\n\t}\n\tfor _, v := range vars {\n\t\tvk := strings.Split(v, \":::\")\n\t\tif len(vk) < 2 {\n\t\t\tlog.Printf(\"ignoring variable %s\", v)\n\t\t\tcontinue\n\t\t}\n\t\tinput.Vars[vk[0]] = strings.Join(vk[1:], \":::\")\n\t}\n\terr = tmpl.Execute(os.Stdout, input)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func RenderTemplate(templateFile, variableFile string, flagVars *map[string]string) (tpl *bytes.Buffer, err error) {\n\tif variableFile == \"\" {\n\t\tlogging.Debug(\"levant/templater: no variable file passed, trying defaults\")\n\t\tif variableFile = helper.GetDefaultVarFile(); variableFile != \"\" {\n\t\t\tlogging.Debug(\"levant/templater: found default variable file, using %s\", variableFile)\n\t\t}\n\t}\n\n\t// Process the variable file extension and log DEBUG so the template can be\n\t// correctly rendered.\n\tvar ext string\n\tif ext = path.Ext(variableFile); ext != \"\" {\n\t\tlogging.Debug(\"levant/templater: variable file extension %s detected\", ext)\n\t}\n\n\tsrc, err := ioutil.ReadFile(templateFile)\n\tif err != nil {\n\t\treturn\n\t}\n\n\t// If no command line variables are passed; log this as DEBUG to provide much\n\t// greater feedback.\n\tif len(*flagVars) == 0 {\n\t\tlogging.Debug(\"levant/templater: no command line variables passed\")\n\t}\n\n\tswitch ext {\n\tcase terraformVarExtension:\n\t\ttpl, err = renderTFTemplte(string(src), variableFile, flagVars)\n\n\tcase yamlVarExtension, ymlVarExtension:\n\t\t// Run the render using a YAML variable file.\n\t\ttpl, err = renderYAMLVarsTemplate(string(src), variableFile, flagVars)\n\n\tcase \"\":\n\t\t// No variables file passed; render using any passed CLI variables.\n\t\tlogging.Debug(\"levant/templater: variable file not passed\")\n\t\ttpl, err = readJobFile(string(src), flagVars)\n\n\tdefault:\n\t\terr = fmt.Errorf(\"variables file extension %v not supported\", ext)\n\t}\n\n\treturn\n}",
"func Template(templatePath string) Result {\n\tconfig := config.GetLoadedConfig()\n\tfullPath := filepath.Join(config.GetTemplatePath(), templatePath)\n\n\tif f, err := os.Open(fullPath); err != nil {\n\t\tlog.Printf(\"could not open template file %s\\n\", fullPath)\n\t} else {\n\t\tif bytes, err := io.ReadAll(f); err != nil {\n\t\t\tlog.Printf(\"could not read template file %s\\n\", fullPath)\n\t\t} else {\n\t\t\treturn StringResult(bytes)\n\t\t}\n\t}\n\n\treturn StringResult(\"\")\n}",
"func RunTemplateFromFile(path string, input interface{}) (*string, error) {\n\ttemplate, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttemplateString := string(template)\n\tresult, err := RunTemplate(templateString, input)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn result, nil\n}",
"func createFile(input map[string]*context,\n\ttemplate string, conf string) error {\n\t// read the template\n\tcontents, err := ioutil.ReadFile(template)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\t// replace\n\tfor _, ctx := range input {\n\t\tcontents = bytes.Replace(contents, []byte(ctx.templateKeyword),\n\t\t\t[]byte(ctx.cliInput), -1)\n\t}\n\t// write\n\terr = ioutil.WriteFile(conf, contents, 0644)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\treturn nil\n}",
"func RenderTemplateFromFile(config interface{}, path string) ([]byte, error) {\n\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\tglog.Fatalf(\"Error reading %#v\", err)\n\t}\n\n\tpopulatedData, err := renderTemplate(config, data)\n\tif err != nil {\n\t\tglog.Fatalf(\"Unable to render manifests %q: %v\", data, err)\n\t}\n\treturn populatedData, nil\n}",
"func Template(t, b string, o io.Writer) error {\n\tbf, err := Parse(b)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttf, err := os.OpenFile(t, os.O_RDONLY, os.ModePerm)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer tf.Close()\n\n\ttext, err := ioutil.ReadAll(tf)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttmpl, err := template.New(b).Parse(string(text))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn tmpl.Execute(o, bf)\n}",
"func processTemplate(path string, vars map[string]string) (string, error) {\n\tdata, err := ioutil.ReadFile(path)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"tpl: %v\", err)\n\t}\n\ttmpl, err := template.New(path).Parse(string(data))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"tpl: %v\", err)\n\t}\n\tb := bytes.NewBuffer([]byte{})\n\terr = tmpl.Execute(b, vars)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"tpl: %v\", err)\n\t}\n\tpath = path + \".out\"\n\terr = ioutil.WriteFile(path, b.Bytes(), os.ModePerm)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"tpl: %v\", err)\n\t}\n\treturn path, nil\n}",
"func Parse(filePath string, preprocessor Preprocessor, options protocols.ExecuterOptions) (*Template, error) {\n\tif value, err := parsedTemplatesCache.Has(filePath); value != nil {\n\t\treturn value.(*Template), err\n\t}\n\n\ttemplate := &Template{}\n\n\tf, err := os.Open(filePath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer f.Close()\n\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdata = template.expandPreprocessors(data)\n\tif preprocessor != nil {\n\t\tdata = preprocessor.Process(data)\n\t}\n\n\terr = yaml.Unmarshal(data, template)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif utils.IsBlank(template.Info.Name) {\n\t\treturn nil, errors.New(\"no template name field provided\")\n\t}\n\tif template.Info.Authors.IsEmpty() {\n\t\treturn nil, errors.New(\"no template author field provided\")\n\t}\n\n\t// Setting up variables regarding template metadata\n\toptions.TemplateID = template.ID\n\toptions.TemplateInfo = template.Info\n\toptions.TemplatePath = filePath\n\n\t// If no requests, and it is also not a workflow, return error.\n\tif len(template.RequestsDNS)+len(template.RequestsHTTP)+len(template.RequestsFile)+len(template.RequestsNetwork)+len(template.RequestsHeadless)+len(template.Workflows) == 0 {\n\t\treturn nil, fmt.Errorf(\"no requests defined for %s\", template.ID)\n\t}\n\n\t// Compile the workflow request\n\tif len(template.Workflows) > 0 {\n\t\tcompiled := &template.Workflow\n\n\t\tcompileWorkflow(filePath, preprocessor, &options, compiled, options.WorkflowLoader)\n\t\ttemplate.CompiledWorkflow = compiled\n\t\ttemplate.CompiledWorkflow.Options = &options\n\t}\n\n\t// Compile the requests found\n\trequests := []protocols.Request{}\n\tif len(template.RequestsDNS) > 0 && !options.Options.OfflineHTTP {\n\t\tfor _, req := range template.RequestsDNS {\n\t\t\trequests = append(requests, req)\n\t\t}\n\t\ttemplate.Executer = executer.NewExecuter(requests, &options)\n\t}\n\tif len(template.RequestsHTTP) > 0 {\n\t\tif options.Options.OfflineHTTP {\n\t\t\toperatorsList := []*operators.Operators{}\n\n\t\tmainLoop:\n\t\t\tfor _, req := range template.RequestsHTTP {\n\t\t\t\tfor _, path := range req.Path {\n\t\t\t\t\tif !(strings.EqualFold(path, \"{{BaseURL}}\") || strings.EqualFold(path, \"{{BaseURL}}/\")) {\n\t\t\t\t\t\tbreak mainLoop\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\toperatorsList = append(operatorsList, &req.Operators)\n\t\t\t}\n\t\t\tif len(operatorsList) > 0 {\n\t\t\t\toptions.Operators = operatorsList\n\t\t\t\ttemplate.Executer = executer.NewExecuter([]protocols.Request{&offlinehttp.Request{}}, &options)\n\t\t\t}\n\t\t} else {\n\t\t\tfor _, req := range template.RequestsHTTP {\n\t\t\t\trequests = append(requests, req)\n\t\t\t}\n\t\t\ttemplate.Executer = executer.NewExecuter(requests, &options)\n\t\t}\n\t}\n\tif len(template.RequestsFile) > 0 && !options.Options.OfflineHTTP {\n\t\tfor _, req := range template.RequestsFile {\n\t\t\trequests = append(requests, req)\n\t\t}\n\t\ttemplate.Executer = executer.NewExecuter(requests, &options)\n\t}\n\tif len(template.RequestsNetwork) > 0 && !options.Options.OfflineHTTP {\n\t\tfor _, req := range template.RequestsNetwork {\n\t\t\trequests = append(requests, req)\n\t\t}\n\t\ttemplate.Executer = executer.NewExecuter(requests, &options)\n\t}\n\tif len(template.RequestsHeadless) > 0 && !options.Options.OfflineHTTP && options.Options.Headless {\n\t\tfor _, req := range template.RequestsHeadless {\n\t\t\trequests = append(requests, req)\n\t\t}\n\t\ttemplate.Executer = executer.NewExecuter(requests, &options)\n\t}\n\tif template.Executer != nil {\n\t\terr := template.Executer.Compile()\n\t\tif err != nil {\n\t\t\treturn nil, errors.Wrap(err, \"could not compile request\")\n\t\t}\n\t\ttemplate.TotalRequests += template.Executer.Requests()\n\t}\n\tif template.Executer == nil && template.CompiledWorkflow == nil {\n\t\treturn nil, ErrCreateTemplateExecutor\n\t}\n\ttemplate.Path = filePath\n\n\tparsedTemplatesCache.Store(filePath, template, err)\n\treturn template, nil\n}",
"func ExecuteTemplate(sourceFilePath string, funcMap template.FuncMap, verbose bool) (string, error) {\n\tfileContent, err := ioutil.ReadFile(sourceFilePath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tt := template.New(\"ssmtpl\").Funcs(funcMap)\n\tif _, err := t.Parse(string(fileContent)); err != nil {\n\t\treturn \"\", err\n\t}\n\tvar buf bytes.Buffer\n\tvals := map[string]interface{}{}\n\tif err := t.Execute(&buf, vals); err != nil {\n\t\treturn \"\", err\n\t}\n\tif verbose {\n\t\tfmt.Println(string(buf.Bytes()))\n\t}\n\treturn buf.String(), nil\n}",
"func ExecTemplate(filename string, result io.Writer, data interface{}) error {\n\n\t// Set curent target file name for function fileMD5\n\ttmplTargetFileName = filename\n\t// Read template from file.\n\ttmplData, err := ioutil.ReadFile(filename)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Parse template.\n\ttmpl, err := template.New(\"main\").Funcs(TmplFunctionsMap()).Option(\"missingkey=error\").Parse(string(tmplData))\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Apply data to template.\n\terr = tmpl.Execute(result, &data)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func GenerateYamlTemplate(params GenerateParams) (compiledTemplate YamlCloudformation, err error) {\n\t// load the config file\n\tvar configData []byte\n\n\t// Setup out parser variables\n\tvar templateParsers,\n\t\tcoreParsers,\n\t\tpluginParsers map[string]types.ParserFunc\n\n\ttemplateParsers = make(map[string]types.ParserFunc)\n\tcoreParsers = make(map[string]types.ParserFunc)\n\tpluginParsers = make(map[string]types.ParserFunc)\n\n\t// Load core AWS parsers for resources\n\tcoreParsers = parsers.GetParsersResources()\n\n\ttemplateParsers = mergeParsers(templateParsers, coreParsers)\n\n\t// Load the parsers from Plugins\n\tpluginParsers = plugins.ExtractParsersFromPlugins(params.Plugins)\n\ttemplateParsers = mergeParsers(templateParsers, pluginParsers)\n\n\tif configData, err = params.ObjectStore.Get(params.Filename); err != nil {\n\t\treturn compiledTemplate, err\n\t}\n\n\t//preprocess - template in the environment variables and custom params\n\tbuf := new(bytes.Buffer)\n\n\tif err = executeTemplate(buf, configData, params.ParamMap); err != nil {\n\t\tprinter.Error(\n\t\t\tfmt.Errorf(\"Failed to execute the template\"),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"File: %s\",\n\t\t\t\tparams.Filename,\n\t\t\t),\n\t\t\t\"\",\n\t\t)\n\n\t\treturn compiledTemplate, err\n\t}\n\n\t// parse the config yaml\n\tdata := buf.Bytes()\n\tvar config YamlConfig\n\n\tconfig.Conditions = make(types.TemplateObject)\n\tconfig.Metadata = make(types.TemplateObject)\n\tconfig.Mappings = make(types.TemplateObject)\n\tconfig.Outputs = make(types.TemplateObject)\n\tconfig.Parameters = make(types.TemplateObject)\n\tconfig.Resources = make(map[string]types.CfResource)\n\tconfig.Transform = make(types.TemplateObject)\n\n\tif err = yaml.Unmarshal(data, &config); err != nil {\n\t\tprinter.Error(\n\t\t\tfmt.Errorf(\"Failed to unmarshal the template\"),\n\t\t\tfmt.Sprintf(\n\t\t\t\t\"File: %s\",\n\t\t\t\tparams.Filename,\n\t\t\t),\n\t\t\t\"\",\n\t\t)\n\t\treturn compiledTemplate, err\n\t}\n\n\t// Setup the initial types\n\tvar conditions,\n\t\tmetadata,\n\t\tmappings,\n\t\toutputs,\n\t\tparameters,\n\t\tresources,\n\t\ttransform map[string]interface{}\n\n\tconditions = make(map[string]interface{})\n\tmetadata = make(map[string]interface{})\n\tmappings = make(map[string]interface{})\n\toutputs = make(map[string]interface{})\n\tparameters = make(map[string]interface{})\n\tresources = make(map[string]interface{})\n\ttransform = make(map[string]interface{})\n\n\t// Process the core and plugin parsers\n\tconditions,\n\t\tmetadata,\n\t\tmappings,\n\t\toutputs,\n\t\tparameters,\n\t\tresources,\n\t\ttransform = processParsers(config.Resources, templateParsers, params.GenerateDefaultOutputs)\n\n\tcompiledTemplate = YamlCloudformation{\n\t\tAWSTemplateFormatVersion: config.AWSTemplateFormatVersion,\n\t\tDescription: config.Description,\n\t\tMetadata: mergeTemplates(config.Metadata, metadata),\n\t\tParameters: mergeTemplates(config.Parameters, parameters),\n\t\tConditions: mergeTemplates(config.Conditions, conditions),\n\t\tTransform: mergeTemplates(config.Transform, transform),\n\t\tMappings: mergeTemplates(config.Mappings, mappings),\n\t\t// As we've processed all the resources through our parsers, we don't want to merge in the\n\t\t// initial resources, as we will retain plugin definitions that don't map to\n\t\t// cloudformation template resources\n\t\tResources: resources,\n\t\tOutputs: mergeTemplates(config.Outputs, outputs),\n\t}\n\n\treturn compiledTemplate, nil\n}",
"func (g *Generator) ParseFile(path string) (*template.Template, error) {\n\treturn g.generateTemplate(path, nil)\n}",
"func GenerateFromFile(templFile string, subs map[string]string) (string, error) {\n\tb, err := ioutil.ReadFile(templFile)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not read template from file [ %v ]: %v\", templFile, err)\n\t}\n\treturn Generate(string(b), subs)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
templateDir runs through a directory recursively templating every file on the way down in the tree
|
func (t *templater) templateDir(workDir string, outDir string, d map[string]interface{}) {
log.Info("templating", "dir", workDir)
err := os.Mkdir(outDir, 0755)
if err != nil && !os.IsExist(err) {
log.Error(err, "Failed to create output dir")
return
}
files, err := ioutil.ReadDir(workDir)
if err != nil {
log.Error(err, "Failed to read dir")
}
for _, file := range files {
if file.IsDir() {
t.templateDir(workDir+"/"+file.Name(), outDir+"/"+file.Name(), d)
} else {
t.templateFile(workDir, outDir, file, d)
}
}
}
|
[
"func (r *Render) compileTemplatesFromDir() {\n\tr.templates = template.New(r.opt.Directory)\n\tr.templates.Delims(DefaultLeftDelim, DefaultRightDelim)\n\n\t// Walk the directory and compile any valid template.\n\tfilepath.Walk(r.opt.Directory, func(path string, info os.FileInfo, err error) error {\n\t\t// If we encounter a directory, return immediately since we can't\n\t\t// compile it.\n\t\tif info == nil || info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Get the path relative to our root template directory.\n\t\trel, err := filepath.Rel(r.opt.Directory, path)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Determine the file extension.\n\t\text := \"\"\n\t\tif strings.Index(rel, \".\") != -1 {\n\t\t\text = filepath.Ext(rel)\n\t\t}\n\n\t\t// Compile each template. We check if the extension matches the\n\t\t// allowed ones that we defined before compiling.\n\t\tfor _, extension := range r.opt.Extensions {\n\t\t\tif ext == extension {\n\t\t\t\tbuf, err := ioutil.ReadFile(path)\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t}\n\n\t\t\t\tname := (rel[0 : len(rel)-len(ext)])\n\t\t\t\ttmpl := r.templates.New(filepath.ToSlash(name))\n\n\t\t\t\t// Add our funcmaps.\n\t\t\t\tfor _, funcs := range r.opt.Funcs {\n\t\t\t\t\ttmpl.Funcs(funcs)\n\t\t\t\t}\n\n\t\t\t\t// Break out if this parsing fails. We don't want any silent\n\t\t\t\t// server starts.\n\t\t\t\ttemplate.Must(tmpl.Funcs(helperFuncs).Parse(string(buf)))\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n}",
"func visitTemplatesFromDir(templatesDirPath string, getParentTemplate types.TemplateSupplier, consumeTemplate types.TemplateConsumer) error {\n\tvar err error\n\n\t// Get the list of filesystem objects in the helpers directory\n\tvar filesystemObjects []os.FileInfo\n\tfilesystemObjects, err = ioutil.ReadDir(templatesDirPath)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Parse all templates in the given directory, ignoring sub-directories\n\tlog.Debug(\"Parsing templates in directory: %s\", templatesDirPath)\n\tfor _, filesystemObject := range filesystemObjects {\n\t\tvar fileName = filesystemObject.Name()\n\n\t\t// Ignore directories\n\t\tif filesystemObject.IsDir() {\n\t\t\tlog.Warning(\"Ignoring sub-directory: %s\", fileName)\n\t\t\tcontinue\n\t\t}\n\n\t\tlog.Debug(\"Parsing template: %s\", fileName)\n\n\t\t// Create a template object from the file\n\t\tvar filePath = filepath.Join(templatesDirPath, fileName)\n\t\tvar tmpl *template.Template\n\t\ttmpl, err = GetTemplateFromFile(getParentTemplate(), fileName, filePath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Consume template\n\t\tlog.Debug(\"Consuming template: %s\", tmpl.Name())\n\t\tconsumeTemplate(tmpl)\n\t}\n\n\treturn nil\n}",
"func TemplateDir(path string) Option {\n\treturn templateOption(func(t *gen.Template) (*gen.Template, error) {\n\t\treturn t.ParseDir(path)\n\t})\n}",
"func setupTemplates(folder string) error {\n\n\tcontents, err := ioutil.ReadDir(folder)\n\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tvar files []string\n\n\tfor _, file := range contents {\n\t\tfull_name := file.Name()\n\t\tfiles = append(files, filepath.Join(folder, full_name))\n\t}\n\n\tvar temperr error\n\n\ttemplates, temperr = ParseFiles(files...)\n\n\tif temperr != nil {\n\t\treturn temperr\n\t}\n\n\treturn nil\n}",
"func collectTemplateFiles(dir string, handler func(name, filename string) error) error {\n\tdir = filepath.Clean(dir)\n\tif err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\tif strings.HasSuffix(path, \".tmpl\") {\n\t\t\tname := strings.TrimSuffix(strings.TrimPrefix(path, dir+string(os.PathSeparator)), \".tmpl\")\n\t\t\tif err := handler(name, path); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func BuildTemplate(dir string, files ...string) error {\n\tif _, err := os.Stat(dir); err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"dir open err\")\n\t}\n\tself := &templateFile{\n\t\troot: dir,\n\t\tfiles: make(map[string][]string),\n\t}\n\terr := filepath.Walk(dir, func(path string, f os.FileInfo, err error) error {\n\t\treturn self.visit(path, f, err)\n\t})\n\tif err != nil {\n\t\tfmt.Printf(\"filepath.Walk() returned %v\\n\", err)\n\t\treturn err\n\t}\n\tbuildAllFiles := len(files) == 0\n\tfor _, v := range self.files {\n\t\tfor _, file := range v {\n\t\t\tif buildAllFiles || yeestrings.IsInSlice(files, file) {\n\t\t\t\ttemplatesLock.Lock()\n\t\t\t\text := filepath.Ext(file)\n\t\t\t\tvar t *template.Template\n\t\t\t\tif len(ext) == 0 {\n\t\t\t\t\tt, err = getTemplate(self.root, file, v...)\n\t\t\t\t} else {\n\t\t\t\t\tt, err = getTemplate(self.root, file, v...)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tpanic(err)\n\t\t\t\t} else {\n\t\t\t\t\tcacheTemplates[file] = t\n\t\t\t\t}\n\t\t\t\ttemplatesLock.Unlock()\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func (t *Repository) LoadDir(templatePath string) error {\n\terr := filepath.Walk(templatePath, func(path string, info os.FileInfo, err error) error {\n\n\t\tif strings.HasSuffix(path, \".gotmpl\") {\n\t\t\tif assetName, e := filepath.Rel(templatePath, path); e == nil {\n\t\t\t\tif data, e := ioutil.ReadFile(path); e == nil {\n\t\t\t\t\tif ee := t.AddFile(assetName, string(data)); ee != nil {\n\t\t\t\t\t\t// Fatality is decided by caller\n\t\t\t\t\t\t// log.Fatal(ee)\n\t\t\t\t\t\treturn fmt.Errorf(\"could not add template: %v\", ee)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t// Non-readable files are skipped\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\t// Non-template files are skipped\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not complete template processing in directory \\\"%s\\\": %v\", templatePath, err)\n\t}\n\treturn nil\n}",
"func loadTemplates(dir string) (multitemplate.Renderer, error) {\n\tr := multitemplate.NewRenderer()\n\tbase, err := filepath.Glob(dir + \"/*.html\")\n\tif err != nil {\n\t\treturn r, err\n\t}\n\n\tpages, err := filepath.Glob(\"templates/pages/*.html\")\n\tif err != nil {\n\t\treturn r, err\n\t}\n\n\tfor _, page := range pages {\n\t\ttemplates := make([]string, len(base))\n\t\tcopy(templates, base)\n\t\ttemplates = append(templates, page)\n\t\tr.AddFromFiles(filepath.Base(page), templates...)\n\t}\n\n\treturn r, nil\n}",
"func walkDir(dir string, outFileNamer func(string) (string, error), excludeGlob []string, mode os.FileMode, modeOverride bool) ([]*tplate, error) {\n\tdir = filepath.Clean(dir)\n\n\tdirStat, err := fs.Stat(dir)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"couldn't stat %s: %w\", dir, err)\n\t}\n\tdirMode := dirStat.Mode()\n\n\ttemplates := make([]*tplate, 0)\n\tmatcher := xignore.NewMatcher(fs)\n\n\t// work around bug in xignore - a basedir of '.' doesn't work\n\tbasedir := dir\n\tif basedir == \".\" {\n\t\tbasedir, _ = os.Getwd()\n\t}\n\tmatches, err := matcher.Matches(basedir, &xignore.MatchesOptions{\n\t\tIgnorefile: gomplateignore,\n\t\tNested: true, // allow nested ignorefile\n\t\tAfterPatterns: excludeGlob,\n\t})\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"ignore matching failed for %s: %w\", basedir, err)\n\t}\n\n\t// Unmatched ignorefile rules's files\n\tfiles := matches.UnmatchedFiles\n\tfor _, file := range files {\n\t\tnextInPath := filepath.Join(dir, file)\n\t\tnextOutPath, err := outFileNamer(file)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tfMode := mode\n\t\tif mode == 0 {\n\t\t\tstat, perr := fs.Stat(nextInPath)\n\t\t\tif perr == nil {\n\t\t\t\tfMode = stat.Mode()\n\t\t\t} else {\n\t\t\t\tfMode = dirMode\n\t\t\t}\n\t\t}\n\n\t\t// Ensure file parent dirs\n\t\tif err = fs.MkdirAll(filepath.Dir(nextOutPath), dirMode); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\ttemplates = append(templates, &tplate{\n\t\t\tname: nextInPath,\n\t\t\ttargetPath: nextOutPath,\n\t\t\tmode: fMode,\n\t\t\tmodeOverride: modeOverride,\n\t\t})\n\t}\n\n\treturn templates, nil\n}",
"func parseTemplateFiles(dir string) *template.Template {\n\ttempl := template.New(\"\").Funcs(\n\t\ttemplate.FuncMap{\n\t\t\t\"showLink\": func(target string) string {\n\t\t\t\treturn host + target\n\t\t\t},\n\t\t})\n\n\terr := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {\n\t\t//log.Println(path)\n\t\tif strings.Contains(path, \".html\") {\n\t\t\t_, err = templ.ParseFiles(path)\n\t\t\tif err != nil {\n\t\t\t\tlog.Println(err)\n\t\t\t}\n\t\t}\n\t\treturn err\n\t})\n\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn templ\n}",
"func FindAndParseTemplates(rootDir, ext string, funcMap template.FuncMap) (*template.Template, error) {\n\tcleanRoot := filepath.Clean(rootDir)\n\tpfx := len(cleanRoot) + 1\n\troot := template.New(\"\")\n\n\terr := filepath.Walk(cleanRoot, func(path string, info os.FileInfo, e1 error) error {\n\t\tif !info.IsDir() && strings.HasSuffix(path, ext) {\n\t\t\tif e1 != nil {\n\t\t\t\treturn e1\n\t\t\t}\n\n\t\t\tb, e2 := ioutil.ReadFile(path)\n\t\t\tif e2 != nil {\n\t\t\t\treturn e2\n\t\t\t}\n\n\t\t\tname := path[pfx:]\n\t\t\tt := root.New(name).Funcs(funcMap)\n\t\t\t_, e2 = t.Parse(string(b))\n\t\t\tif e2 != nil {\n\t\t\t\treturn e2\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t})\n\n\treturn root, err\n}",
"func (s *XTemplate) parseDir(root, extension string, onlyPartials bool) error {\n\t// parse partial templates (i.e files that are named _xxxxx.ext)\n\t_, err := s.shared.ParseGlob(\"_*\")\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif onlyPartials {\n\t\treturn err\n\t}\n\n\t// find all template files\n\terr = filepath.Walk(root, func(path string, info os.FileInfo, err error) error {\n\t\t// skip dirs\n\t\tif info == nil || info.IsDir() {\n\t\t\treturn nil\n\t\t}\n\n\t\t// check for extension\n\t\te := filepath.Ext(path)\n\t\tif e != extension {\n\t\t\treturn nil\n\t\t}\n\n\t\tname := strings.TrimPrefix(path, root)\n\n\t\tif strings.HasPrefix(name, \"_\") {\n\t\t\treturn nil\n\t\t}\n\n\t\t// parse template\n\t\ttpl, err := s.getTemplate(name)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// cache template\n\t\ts.cache[name] = tpl\n\n\t\treturn nil\n\t})\n\n\treturn err\n}",
"func CopyTemplateDir(boxed, to string, templateData interface{}) {\n\tvar files []string\n\terr := filepath.Walk(boxed, func(path string, info os.FileInfo, err error) error {\n\t\tfiles = append(files, path)\n\t\treturn nil\n\t})\n\tfiles = files[1:]\n\tif err != nil {\n\t\tlog.Errorf(\"Failed to list files in directory %s: %v\\n\", boxed, err)\n\t\tos.Exit(1)\n\t}\n\tfor _, file := range files {\n\t\tnewFile := filepath.Join(to, strings.Join(strings.Split(file, \"\")[len(boxed)+1:], \"\"))\n\t\ttmplFile, err := template.New(\"\").Option(\"missingkey=error\").Parse(newFile)\n\t\tif err != nil {\n\t\t\tlog.Errorf(\"Failed to parse template string: %v\\n\", err)\n\t\t\tos.Exit(1)\n\t\t}\n\t\tvar tmplBytes bytes.Buffer\n\t\terr = tmplFile.Execute(&tmplBytes, templateData)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tnewFile = tmplBytes.String()\n\t\tfi, err := os.Stat(file)\n\t\tif err != nil {\n\t\t\tfmt.Println(err)\n\t\t\treturn\n\t\t}\n\t\tswitch mode := fi.Mode(); {\n\t\tcase mode.IsDir():\n\t\t\terr := os.MkdirAll(newFile, 0755)\n\t\t\tif err != nil {\n\t\t\t\tlog.Errorf(\"Failed to create directory %s: %v\\n\", newFile, err)\n\t\t\t\tos.Exit(1)\n\t\t\t}\n\t\tcase mode.IsRegular():\n\t\t\tif strings.HasSuffix(newFile, \".tmpl\") {\n\t\t\t\tnewFile = strings.TrimSuffix(newFile, \".tmpl\")\n\t\t\t}\n\t\t\tExecuteTemplateFromFile(file, newFile, templateData)\n\t\t}\n\t}\n}",
"func GetTemplatesFromDir(parentTemplate *template.Template, templatesDirPath string) ([]*template.Template, error) {\n\tvar err error\n\n\tvar templates []*template.Template\n\terr = visitTemplatesFromDir(templatesDirPath, func() *template.Template {\n\t\t// Use the same parent template each time\n\t\treturn parentTemplate\n\t}, func(tmpl *template.Template) {\n\t\t// Add the template to the array\n\t\ttemplates = append(templates, tmpl)\n\t})\n\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn templates, nil\n}",
"func BuildTemplate(dir string, files ...string) error {\n\tvar err error\n\tfs := beeTemplateFS()\n\tf, err := fs.Open(dir)\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil\n\t\t}\n\t\treturn errors.New(\"dir open err\")\n\t}\n\tdefer f.Close()\n\n\tbeeTemplates, ok := beeViewPathTemplates[dir]\n\tif !ok {\n\t\tpanic(\"Unknown view path: \" + dir)\n\t}\n\tself := &templateFile{\n\t\troot: dir,\n\t\tfiles: make(map[string][]string),\n\t}\n\terr = Walk(fs, dir, self.visit)\n\tif err != nil {\n\t\tfmt.Printf(\"Walk() returned %v\\n\", err)\n\t\treturn err\n\t}\n\tbuildAllFiles := len(files) == 0\n\tfor _, v := range self.files {\n\t\tfor _, file := range v {\n\t\t\tif buildAllFiles || utils.InSlice(file, files) {\n\t\t\t\ttemplatesLock.Lock()\n\t\t\t\text := filepath.Ext(file)\n\t\t\t\tvar t *template.Template\n\t\t\t\tif len(ext) == 0 {\n\t\t\t\t\tt, err = getTemplate(self.root, fs, file, v...)\n\t\t\t\t} else if fn, ok := beeTemplateEngines[ext[1:]]; ok {\n\t\t\t\t\tt, err = fn(self.root, file, beegoTplFuncMap)\n\t\t\t\t} else {\n\t\t\t\t\tt, err = getTemplate(self.root, fs, file, v...)\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\tlogs.Error(\"parse template err:\", file, err)\n\t\t\t\t\ttemplatesLock.Unlock()\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tbeeTemplates[file] = t\n\t\t\t\ttemplatesLock.Unlock()\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}",
"func checkDir(relativePath string, pOpt *ParseOptions, isNonBase bool) {\n\tvar files []os.FileInfo\n\tvar err error\n\n\tfiles, err = ioutil.ReadDir(relativePath)\n\n\t// If there is an error: PANIC!\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// Iterate all found files and folders\n\tfor _, file := range files {\n\t\t// Extract the filename without extension\n\t\tfilename := strings.Split(file.Name(), \".\")[0]\n\t\thasChildren := checkIfHasChildren(pOpt, filename, files)\n\n\t\t// Check for inheritance marked by \"-\"\n\t\tif strings.Contains(filename, pOpt.Delimiter) && !file.IsDir() && !hasChildren {\n\t\t\t// Split the filename\n\t\t\tpartialTmpl := strings.Split(filename, pOpt.Delimiter)\n\t\t\trebuildTmpl := make([]string, len(partialTmpl))\n\n\t\t\t// Rename the strings correctly\n\t\t\t// Like: views/index.html && views/index-login.html\n\t\t\t// So index-login.html inherits from index.html\n\t\t\t// and index.html inherits from base.html\n\t\t\tfor i, _ := range partialTmpl {\n\t\t\t\tvar parent string\n\t\t\t\tfor j := 0; j <= i; j++ {\n\t\t\t\t\tif j == i {\n\t\t\t\t\t\tparent += partialTmpl[j]\n\t\t\t\t\t} else {\n\t\t\t\t\t\tparent += partialTmpl[j] + pOpt.Delimiter\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trebuildTmpl[i] = createPathToView(relativePath, parent, true, pOpt)\n\t\t\t}\n\n\t\t\t// Saving the templates like e.g.:\n\t\t\t// index.html inherits from base.html: templates[\"#index\"]\n\t\t\t// index-login.html inherits from index.html ...: templates[\"#index.login\"]\n\t\t\t// index-login-special.html inherits from index-login.html ...: templates[\"#login.special\"]\n\t\t\t// In NonBase, the '#' dissapears (doesn't extends base), like: templates[\"superspecial\"] for views/nonbase/superspecial.html\n\t\t\tif !isNonBase {\n\t\t\t\ttemplates[\"#\"+partialTmpl[len(partialTmpl)-2]+\".\"+partialTmpl[len(partialTmpl)-1]] = createInheritedTemplate(pOpt, true, rebuildTmpl...)\n\t\t\t} else if isNonBase && len(partialTmpl) == 2 {\n\t\t\t\ttemplates[partialTmpl[0]+\".\"+partialTmpl[1]] = createInheritedTemplate(pOpt, false, rebuildTmpl...)\n\t\t\t} else if isNonBase && len(partialTmpl) > 2 {\n\t\t\t\ttemplates[partialTmpl[0]+\".\"+partialTmpl[len(partialTmpl)-2]+\".\"+partialTmpl[len(partialTmpl)-1]] = createInheritedTemplate(pOpt, false, rebuildTmpl...)\n\t\t\t}\n\n\t\t} else if !file.IsDir() && !hasChildren {\n\t\t\t// Add template with inheritance\n\t\t\tif filename != pOpt.BaseName {\n\t\t\t\tif !isNonBase {\n\t\t\t\t\ttemplates[\"#\"+filename] = createInheritedTemplate(pOpt, true, createPathToView(relativePath, file.Name(), false, pOpt))\n\t\t\t\t} else {\n\t\t\t\t\ttemplates[filename] = createInheritedTemplate(pOpt, false, createPathToView(relativePath, file.Name(), false, pOpt))\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else if file.IsDir() && file.Name() == pOpt.NonBaseFolder {\n\t\t\t// Check if entering NonBase Folder\n\t\t\tcheckDir(filepath.Join(relativePath, file.Name()), pOpt, true)\n\n\t\t} else if file.IsDir() {\n\t\t\t// Check subfolder the same way.\n\t\t\tcheckDir(filepath.Join(relativePath, file.Name()), pOpt, isNonBase)\n\t\t}\n\t}\n}",
"func (e *Engine) compileDir(root, dirname, filtername string) (map[string]*Template, error) {\n\tresult := make(map[string]*Template)\n\n\tdir, err := os.Open(path.Join(root, dirname))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tdefer dir.Close()\n\n\tfilenames, err := dir.Readdir(-1)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor _, filename := range filenames {\n\t\tif filename.IsDir() {\n\t\t\ttpls, err := e.compileDir(root, path.Join(dirname, filename.Name()), filtername)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tfor k, v := range tpls {\n\t\t\t\tif result[k] == nil {\n\t\t\t\t\tresult[k] = v\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tif strings.HasSuffix(filename.Name(), \".ast.json\") {\n\t\t\t\tname := path.Join(dirname, filename.Name())\n\t\t\t\tname = name[:len(name)-len(\".ast.json\")]\n\n\t\t\t\tif filtername != \"\" && !strings.HasPrefix(name, filtername) {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\n\t\t\t\trenderState := newRenderState(path.Join(e.Basedir, \"template\", \"page\"), e.Debug, e.EventRouter, e.Logger)\n\t\t\t\trenderState.funcs = FuncMap{}\n\n\t\t\t\tfor k, f := range e.FuncProvider() {\n\t\t\t\t\trenderState.funcs[k] = f.Func\n\t\t\t\t}\n\n\t\t\t\ttoken, err := renderState.Parse(name)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, err\n\t\t\t\t}\n\t\t\t\tresult[name], e.TemplateCode[name], err = renderState.TokenToTemplate(name, token)\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\t\t}\n\t}\n\n\treturn result, nil\n}",
"func SetupTemplates(cfg chef.ServerConfig) ([]string, error) {\n\tfiles := make([]string, 0)\n\tlog.Debug().Msg(\"setting up templates\")\n\n\tlog.Debug().Msg(\"cleaning output directory\")\n\t// clean static output dir\n\terr := os.RemoveAll(TemplateOutputDir)\n\tif err != nil {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"error cleaning ouput directory %v : %w\", TemplateOutputDir, err)\n\t}\n\n\tlog.Debug().Str(\"OutputDir\", TemplateOutputDir).Msg(\"creating new output directories\")\n\t// Create/ensure output directory\n\tif err = EnsureDir(TemplateOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create subdirs\n\thtmlOutputDir := filepath.Join(TemplateOutputDir, \"html\")\n\tif err = EnsureDir(htmlOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tjsOutputDir := filepath.Join(TemplateOutputDir, \"js\")\n\tif err = EnsureDir(jsOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcssOutputDir := filepath.Join(TemplateOutputDir, \"css\")\n\tif err = EnsureDir(cssOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\ttsOutputDir := filepath.Join(TemplateOutputDir, \"src\")\n\tif err = EnsureDir(tsOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\timgOutputDir := filepath.Join(TemplateOutputDir, \"img\")\n\tif err = EnsureDir(imgOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmiscFilesOutputDir := filepath.Join(TemplateOutputDir, \"files\")\n\tif err = EnsureDir(miscFilesOutputDir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tlog.Debug().Str(\"BaseDir\", TemplateBaseDir).Msg(\"ensuring template base directory exists\")\n\t// Ensure base template directory exists\n\tif !Exists(TemplateBaseDir) {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"base Dir %v does not exist\", TemplateBaseDir)\n\t}\n\n\t// walk through all files in the template resource dir\n\terr = filepath.Walk(TemplateBaseDir,\n\t\tfunc(path string, info os.FileInfo, err error) error {\n\t\t\t// skip certain directories\n\t\t\tif info.IsDir() && info.Name() == \"node_modules\" {\n\t\t\t\treturn filepath.SkipDir\n\t\t\t}\n\n\t\t\thandleCopyFileErr := func(err error) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal().Err(err).Msg(\"error copying file\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\thandleExecuteTemlateErr := func(err error) {\n\t\t\t\tif err != nil {\n\t\t\t\t\tlog.Fatal().Err(err).Msg(\"error executing HTML template\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tswitch filepath.Ext(path) {\n\t\t\tcase \".html\":\n\t\t\t\tnewPath := filepath.Join(htmlOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleExecuteTemlateErr(ExecuteTemplateHTML(cfg, path, newPath))\n\t\t\tcase \".js\", \".map\":\n\t\t\t\tnewPath := filepath.Join(jsOutputDir, filepath.Base(path))\n\t\t\t\tif filepath.Base(path) == \"serviceWorker.js\" || filepath.Base(path) == \"serviceWorker.js.map\" {\n\t\t\t\t\tnewPath = filepath.Join(\"./\", filepath.Base(path))\n\t\t\t\t}\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".css\":\n\t\t\t\tnewPath := filepath.Join(cssOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".ts\":\n\t\t\t\tnewPath := filepath.Join(tsOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".ico\", \".png\", \".jpg\", \".svg\", \".gif\":\n\t\t\t\tnewPath := filepath.Join(imgOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\tcase \".pdf\", \".doc\", \".docx\", \".xml\":\n\t\t\t\tnewPath := filepath.Join(miscFilesOutputDir, filepath.Base(path))\n\t\t\t\tlog.Debug().Str(\"fromPath\", path).Str(\"toPath\", newPath).Msg(\"moving static web resources\")\n\t\t\t\thandleCopyFileErr(CopyFile(path, newPath))\n\t\t\t}\n\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn nil,\n\t\t\tfmt.Errorf(\"error walking %v : %w\", TemplateBaseDir, err)\n\t}\n\n\tlog.Debug().Msg(\"template setup complete.\")\n\treturn files, nil\n}",
"func gatherTemplates(cfg *config.Config, outFileNamer func(string) (string, error)) (templates []*tplate, err error) {\n\tmode, modeOverride, err := cfg.GetMode()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tswitch {\n\t// the arg-provided input string gets a special name\n\tcase cfg.Input != \"\":\n\t\ttemplates = []*tplate{{\n\t\t\tname: \"<arg>\",\n\t\t\tcontents: cfg.Input,\n\t\t\tmode: mode,\n\t\t\tmodeOverride: modeOverride,\n\t\t\ttargetPath: cfg.OutputFiles[0],\n\t\t}}\n\tcase cfg.InputDir != \"\":\n\t\t// input dirs presume output dirs are set too\n\t\ttemplates, err = walkDir(cfg.InputDir, outFileNamer, cfg.ExcludeGlob, mode, modeOverride)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\tcase cfg.Input == \"\":\n\t\ttemplates = make([]*tplate, len(cfg.InputFiles))\n\t\tfor i := range cfg.InputFiles {\n\t\t\ttemplates[i], err = fileToTemplates(cfg.InputFiles[i], cfg.OutputFiles[i], mode, modeOverride)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn processTemplates(cfg, templates)\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
RunPreExecutor runs an arbitary preexecutor to template the yaml files
|
func RunPreExecutor(spec *opsv1alpha1.GitOps, dir string) error {
if spec.Spec.Templating != nil {
t := spec.Spec.Templating
if t.Executor != nil {
// Create a new context and add a timeout to it
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel() // The cancel should be deferred so resources are cleaned up
cmd := exec.CommandContext(ctx, t.Executor.Exec)
cmd.Dir = GetGitRootDir(spec)
if spec.Spec.Templating.SourceFolder != "" {
cmd.Dir += "/" + spec.Spec.Templating.SourceFolder
}
if len(t.Executor.Args) >= 1 {
a := []string{t.Executor.Exec}
for _, add := range t.Executor.Args {
a = append(a, add)
}
cmd.Args = a
}
out, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
log.Error(err, "Command timed out")
return err
}
if err != nil {
log.Error(err, "Command failed", "output", string(out))
}
return err
}
}
return nil
}
|
[
"func (k *PluginRunner) preRun(cmd *cobra.Command, args []string) error {\n\tlr := fLdr.RestrictionRootOnly\n\tfSys := filesys.MakeFsOnDisk()\n\tldr, err := fLdr.NewLoader(lr, filepath.Clean(k.root), fSys)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tv := validator.NewKustValidator()\n\n\tuf := kunstruct.NewKunstructuredFactoryImpl()\n\tvar pm resmap.Merginator // TODO The actual implementation is internal now...\n\trf := resmap.NewFactory(resource.NewFactory(uf), pm)\n\n\tk.h = resmap.NewPluginHelpers(ldr, v, rf)\n\n\tif c, ok := k.plugin.(resmap.Configurable); ok {\n\t\tconfig, err := k.config(cmd, args)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := c.Config(k.h, config); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (m *Manager) RunPreCreateHooks(c container.Containerizer, info *types.ContainerTaskInfo) error {\n\tfor _, hook := range m.PreCreateHooks {\n\t\terr := hook.Execute(c, info)\n\t\tif err != nil {\n\t\t\tlogger.GetInstance().Error(fmt.Sprintf(\"%s pre-create hook has failed\", hook.Name), zap.Error(err))\n\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}",
"func preRunPublish(cmd *cobra.Command, args []string) error {\n\tlanguage, _ = validateLanguageFlag(language)\n\n\tmapped, err := parseBuildArgs(buildArgs)\n\n\tif err == nil {\n\t\tbuildArgMap = mapped\n\t}\n\n\tbuildLabelMap, err = util.ParseMap(buildLabels, \"build-label\")\n\n\tif parallel < 1 {\n\t\treturn fmt.Errorf(\"the --parallel flag must be great than 0\")\n\t}\n\n\tif len(yamlFile) == 0 {\n\t\treturn fmt.Errorf(\"--yaml or -f is required\")\n\t}\n\n\treturn err\n}",
"func (gen *Generator) RunBefore() (err error) {\n\tfor _, cmd := range gen.Template.RunBefore {\n\t\tvar command string\n\n\t\tif command, err = templates.Expand(cmd, gen.Project.helpers); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tLog.Info(\"run_before\", command)\n\n\t\tCommand := templates.CommandOptions{\n\t\t\tCmd: command,\n\t\t\tDir: gen.Project.Directory,\n\t\t\tUseStdOut: true,\n\t\t}\n\n\t\tif _, err := templates.Run(Command); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn err\n}",
"func (d *GobusterFuzz) PreRun(ctx context.Context, progress *libgobuster.Progress) error {\n\treturn nil\n}",
"func runPreHooks(ctx context.Context, payload []byte) (context.Context, []byte) {\n\tfor _, hook := range preHooks {\n\t\tctx, payload = hook.BeforeExecution(ctx, payload)\n\t}\n\n\treturn ctx, payload\n}",
"func PreCommitYaml() error {\n\treturn nil\n}",
"func (tr *TaskRunner) prestart() error {\n\t// Determine if the allocation is terminal and we should avoid running\n\t// prestart hooks.\n\tif tr.shouldShutdown() {\n\t\ttr.logger.Trace(\"skipping prestart hooks since allocation is terminal\")\n\t\treturn nil\n\t}\n\n\tif tr.logger.IsTrace() {\n\t\tstart := time.Now()\n\t\ttr.logger.Trace(\"running prestart hooks\", \"start\", start)\n\t\tdefer func() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished prestart hooks\", \"end\", end, \"duration\", end.Sub(start))\n\t\t}()\n\t}\n\n\t// use a join context to allow any blocking pre-start hooks\n\t// to be canceled by either killCtx or shutdownCtx\n\tjoinedCtx, joinedCancel := joincontext.Join(tr.killCtx, tr.shutdownCtx)\n\tdefer joinedCancel()\n\n\tfor _, hook := range tr.runnerHooks {\n\t\tpre, ok := hook.(interfaces.TaskPrestartHook)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tname := pre.Name()\n\n\t\t// Build the request\n\t\treq := interfaces.TaskPrestartRequest{\n\t\t\tTask: tr.Task(),\n\t\t\tTaskDir: tr.taskDir,\n\t\t\tTaskEnv: tr.envBuilder.Build(),\n\t\t\tTaskResources: tr.taskResources,\n\t\t}\n\n\t\torigHookState := tr.hookState(name)\n\t\tif origHookState != nil {\n\t\t\tif origHookState.PrestartDone {\n\t\t\t\ttr.logger.Trace(\"skipping done prestart hook\", \"name\", pre.Name())\n\n\t\t\t\t// Always set env vars from hooks\n\t\t\t\tif name == HookNameDevices {\n\t\t\t\t\ttr.envBuilder.SetDeviceHookEnv(name, origHookState.Env)\n\t\t\t\t} else {\n\t\t\t\t\ttr.envBuilder.SetHookEnv(name, origHookState.Env)\n\t\t\t\t}\n\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\t// Give the hook it's old data\n\t\t\treq.PreviousState = origHookState.Data\n\t\t}\n\n\t\treq.VaultToken = tr.getVaultToken()\n\t\treq.NomadToken = tr.getNomadToken()\n\n\t\t// Time the prestart hook\n\t\tvar start time.Time\n\t\tif tr.logger.IsTrace() {\n\t\t\tstart = time.Now()\n\t\t\ttr.logger.Trace(\"running prestart hook\", \"name\", name, \"start\", start)\n\t\t}\n\n\t\t// Run the prestart hook\n\t\tvar resp interfaces.TaskPrestartResponse\n\t\tif err := pre.Prestart(joinedCtx, &req, &resp); err != nil {\n\t\t\ttr.emitHookError(err, name)\n\t\t\treturn structs.WrapRecoverable(fmt.Sprintf(\"prestart hook %q failed: %v\", name, err), err)\n\t\t}\n\n\t\t// Store the hook state\n\t\t{\n\t\t\thookState := &state.HookState{\n\t\t\t\tData: resp.State,\n\t\t\t\tPrestartDone: resp.Done,\n\t\t\t\tEnv: resp.Env,\n\t\t\t}\n\n\t\t\t// Store and persist local state if the hook state has changed\n\t\t\tif !hookState.Equal(origHookState) {\n\t\t\t\ttr.stateLock.Lock()\n\t\t\t\ttr.localState.Hooks[name] = hookState\n\t\t\t\ttr.stateLock.Unlock()\n\n\t\t\t\tif err := tr.persistLocalState(); err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Store the environment variables returned by the hook\n\t\tif name == HookNameDevices {\n\t\t\ttr.envBuilder.SetDeviceHookEnv(name, resp.Env)\n\t\t} else {\n\t\t\ttr.envBuilder.SetHookEnv(name, resp.Env)\n\t\t}\n\n\t\t// Store the resources\n\t\tif len(resp.Devices) != 0 {\n\t\t\ttr.hookResources.setDevices(resp.Devices)\n\t\t}\n\t\tif len(resp.Mounts) != 0 {\n\t\t\ttr.hookResources.setMounts(resp.Mounts)\n\t\t}\n\n\t\tif tr.logger.IsTrace() {\n\t\t\tend := time.Now()\n\t\t\ttr.logger.Trace(\"finished prestart hook\", \"name\", name, \"end\", end, \"duration\", end.Sub(start))\n\t\t}\n\t}\n\n\treturn nil\n}",
"func runPreInit(ctx context.Context, workingDir string, deps *clientset.Clientset, cmdline cmdline.Cmdline, msg string) error {\n\tisEmptyDir, err := location.DirIsEmpty(deps.FS, workingDir)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif isEmptyDir {\n\t\treturn NewNoDevfileError(workingDir)\n\t}\n\n\tinitFlags := deps.InitClient.GetFlags(cmdline.GetFlags())\n\n\terr = deps.InitClient.InitDevfile(ctx, initFlags, workingDir,\n\t\tfunc(interactiveMode bool) {\n\t\t\tscontext.SetInteractive(cmdline.Context(), interactiveMode)\n\t\t\tif interactiveMode {\n\t\t\t\tlog.Title(msg, messages.SourceCodeDetected, \"odo version: \"+version.VERSION)\n\t\t\t\tlog.Info(\"\\n\" + messages.InteractiveModeEnabled)\n\t\t\t}\n\t\t},\n\t\tfunc(newDevfileObj parser.DevfileObj) error {\n\t\t\tdErr := newDevfileObj.WriteYamlDevfile()\n\t\t\tif dErr != nil {\n\t\t\t\treturn dErr\n\t\t\t}\n\t\t\tdErr = files.ReportLocalFileGeneratedByOdo(deps.FS, workingDir, filepath.Base(newDevfileObj.Ctx.GetAbsPath()))\n\t\t\tif dErr != nil {\n\t\t\t\tklog.V(4).Infof(\"error trying to report local file generated: %v\", dErr)\n\t\t\t}\n\t\t\treturn nil\n\t\t})\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}",
"func (f *engine) PreExecute(ctx context.Context, p fsm.Params) error {\n\treturn nil\n}",
"func (*checksExecutor) PreCheck(ctx context.Context) error {\n\treturn nil\n}",
"func (a *Agent) ExecutePreHooks(ctx context.Context, request json.RawMessage) context.Context {\n\ta.Reporter.FlushFlag()\n\n\t// Sort plugins w.r.t their orders\n\tsort.Slice(a.Plugins, func(i, j int) bool {\n\t\treturn a.Plugins[i].Order() < a.Plugins[j].Order()\n\t})\n\tplugin.TraceID = utils.GenerateNewID()\n\tplugin.TransactionID = utils.GenerateNewID()\n\n\t// Traverse sorted plugin slice\n\tfor _, p := range a.Plugins {\n\t\tctx = p.BeforeExecution(ctx, request)\n\t}\n\n\treturn ctx\n}",
"func (p *PrecheckHandler) Precheck(c echo.Context, clusterID uint, driverID uint, modules []model.ModuleType, moduleConfig string) error {\n\tavailableModules := make(map[string]string)\n\n\tcluster, err := p.clusterStore.GetByID(clusterID)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif cluster == nil {\n\t\treturn fmt.Errorf(\"not able to find cluster with id %d\", clusterID)\n\t}\n\n\tcfs, err := p.configFileStore.GetAll()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif driverID > 0 {\n\t\tdriver, err := p.driverStore.GetByID(driverID)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif driver == nil {\n\t\t\treturn fmt.Errorf(\"not able to find driver with id %d\", driverID)\n\t\t}\n\n\t\tdriverPrechecks := p.precheckGetter.GetDriverPrechecks(driver.StorageArrayType.Name, cluster.ConfigFileData, cluster.ClusterDetails.Nodes, modules, c.Logger())\n\t\tfor _, precheck := range driverPrechecks {\n\t\t\tc.Logger().Printf(\"Running precheck: %T for driver of type %s\", precheck, driver.StorageArrayType.Name)\n\t\t\terr := precheck.Validate()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tavailableModules[\"csidriver\"] = driver.StorageArrayType.Name\n\t}\n\n\tfor _, m := range modules {\n\t\tavailableModules[m.Name] = m.Name\n\t}\n\n\t// Run pre-checks for standalone modules (ex: observability)\n\tfor _, module := range modules {\n\t\tmodulePrechecks := p.precheckGetter.GetModuleTypePrechecks(module.Name, moduleConfig, cluster.ConfigFileData, cfs, availableModules)\n\t\tfor _, precheck := range modulePrechecks {\n\t\t\tc.Logger().Printf(\"Running precheck: %T for %s module\", precheck, module.Name)\n\t\t\terr := precheck.Validate()\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}",
"func (tr *Service) PreExecution(triggerType string, task m.Task) error {\n\thandler := tr.getTriggerHandler(triggerType)\n\treturn handler.PreExecution(task)\n}",
"func (w *DefaultPreWorkflowHooksCommandRunner) RunPreHooks(\n\tbaseRepo models.Repo,\n\theadRepo models.Repo,\n\tpull models.PullRequest,\n\tuser models.User,\n) {\n\tif opStarted := w.Drainer.StartOp(); !opStarted {\n\t\tif commentErr := w.VCSClient.CreateComment(baseRepo, pull.Num, ShutdownComment, \"pre_workflow_hooks\"); commentErr != nil {\n\t\t\tw.Logger.Log(logging.Error, \"unable to comment that Atlantis is shutting down: %s\", commentErr)\n\t\t}\n\t\treturn\n\t}\n\tdefer w.Drainer.OpDone()\n\n\tlog := w.buildLogger(baseRepo.FullName, pull.Num)\n\tdefer w.logPanics(baseRepo, pull.Num, log)\n\n\tlog.Info(\"running pre hooks\")\n\n\tunlockFn, err := w.WorkingDirLocker.TryLock(baseRepo.FullName, pull.Num, DefaultWorkspace)\n\tif err != nil {\n\t\tlog.Warn(\"workspace is locked\")\n\t\treturn\n\t}\n\tlog.Debug(\"got workspace lock\")\n\tdefer unlockFn()\n\n\trepoDir, _, err := w.WorkingDir.Clone(log, headRepo, pull, DefaultWorkspace)\n\tif err != nil {\n\t\tlog.Err(\"unable to run pre workflow hooks: %s\", err)\n\t\treturn\n\t}\n\n\tpreWorkflowHooks := make([]*valid.PreWorkflowHook, 0)\n\tfor _, repo := range w.GlobalCfg.Repos {\n\t\tif repo.IDMatches(baseRepo.ID()) && len(repo.PreWorkflowHooks) > 0 {\n\t\t\tpreWorkflowHooks = append(preWorkflowHooks, repo.PreWorkflowHooks...)\n\t\t}\n\t}\n\n\tctx := models.PreWorkflowHookCommandContext{\n\t\tBaseRepo: baseRepo,\n\t\tHeadRepo: headRepo,\n\t\tLog: log,\n\t\tPull: pull,\n\t\tUser: user,\n\t\tVerbose: false,\n\t}\n\n\terr = w.runHooks(ctx, preWorkflowHooks, repoDir)\n\n\tif err != nil {\n\t\tlog.Err(\"pre workflow hook run error results: %s\", err)\n\t}\n}",
"func setupPreparers(fixture consultest.Fixture) {\n\tfor _, node := range testNodes {\n\t\tkey := fmt.Sprintf(\"reality/%s/p2-preparer\", node)\n\t\tfixture.SetKV(key, []byte(testPreparerManifest))\n\t}\n}",
"func (c Carapace) PreRun(f func(cmd *cobra.Command, args []string)) {\n\tif entry := storage.get(c.cmd); entry.prerun != nil {\n\t\t_f := entry.prerun\n\t\tentry.prerun = func(cmd *cobra.Command, args []string) {\n\t\t\t// TODO yuck - probably best to append to a slice in storage\n\t\t\t_f(cmd, args)\n\t\t\tf(cmd, args)\n\t\t}\n\t} else {\n\t\tentry.prerun = f\n\t}\n}",
"func PreLoadInitImages(bc *bits.BuildContext, srcFolder string) error {\n\t// Currently docker images preloaded at build time gets lost at commit time, so this is a NOP\n\t// and images tars are loaded at node create time.\n\t// If we manage to get this working then we will speed up node creation time for docker;\n\t// A possible hint to solve is to remove VOLUME [ \"/var/lib/docker\" ] from the base image and add \"--change\", `VOLUME [ \"/var/lib/docker\" ]`\n\t// on commit, however this will force kinder to start using a new base image for all the docker jobs in ci\n\treturn nil\n}",
"func (f *fsmUpdateEngine) PreExecute(ctx context.Context, p fsm.Params) error {\n\treturn nil\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
NewConverter creates and returns a new Converter for the given Lua state.
|
func NewConverter(L *lua.LState) *Converter {
c := &Converter{
lstate: L,
}
c.metatable = c.ctyMetatable()
return c
}
|
[
"func NewConvert() (convert Converter) { return }",
"func NewConverter(config Configuration) *Converter {\n\tvar c Converter\n\tc.jobs = make(map[string]int)\n\tc.conf = config\n\treturn &c\n}",
"func NewConverter(config *ConverterConfig) *Converter {\n\treturn &Converter{\n\t\tencodeAsFlow: config.EncodeAsFlow,\n\t}\n}",
"func NewConverter() *coinConverter {\n\treturn &coinConverter{\n\t\tcmds: make(map[string]command),\n\t\ttokens: make(map[string]tokenv1.TokenI),\n\t}\n}",
"func (n NewConverter) New(ctx DocumentContext) (Converter, error) {\n\treturn n(ctx)\n}",
"func NewConverter(NameFunc) *Converter {\n\tc := &Converter{\n\t\tconversionFuncs: NewConversionFuncs(),\n\t\tgeneratedConversionFuncs: NewConversionFuncs(),\n\t\tignoredUntypedConversions: make(map[typePair]struct{}),\n\t}\n\tc.RegisterUntypedConversionFunc(\n\t\t(*[]byte)(nil), (*[]byte)(nil),\n\t\tfunc(a, b interface{}, s Scope) error {\n\t\t\treturn Convert_Slice_byte_To_Slice_byte(a.(*[]byte), b.(*[]byte), s)\n\t\t},\n\t)\n\treturn c\n}",
"func NewConverter(kind Kind) Converter {\n\treturn Converter{kind: kind}\n}",
"func New() *Reverter {\n\treturn &Reverter{}\n}",
"func NewConverter(h ...TestEventHandler) io.WriteCloser {\n\tc := new(converter)\n\t*c = converter{\n\t\th: h,\n\t}\n\treturn c\n}",
"func NewConversion() Conversion {\n\treturn Conversion{}\n}",
"func NewConversion() *Conversion {\n\treturn &Conversion{}\n}",
"func NewConvert(option *option.Option, outStream io.Writer) Convert {\n\treturn &convert{option: option, outStream: outStream}\n}",
"func (converterName converterName) CreateConverter() (cliConverter, error) {\n\tconv, err := Resolve(string(converterName))\n\treturn cliConverter{Converter: conv}, err\n}",
"func NewConversion(from, to Unit, formula string) {\n\texpr, err := govaluate.NewEvaluableExpression(formula)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// create conversion function\n\tfn := func(x float64) float64 {\n\t\tparams := make(map[string]interface{})\n\t\tparams[\"x\"] = x\n\n\t\tres, err := expr.Evaluate(params)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\treturn res.(float64)\n\t}\n\n\tNewConversionFromFn(from, to, fn, formula)\n}",
"func NewConversion(params ...interface{}) *Conversion {\n\tc := new(Conversion)\n\n\tc.base = \"0\"\n\tif len(params) != 0 {\n\t\tc.base = zero + ToString(params[0]) + zero\n\t}\n\n\tc.multiples = parseMultiples(params[:]...)\n\n\treturn c\n}",
"func NewSpecConverter(t mockConstructorTestingTNewSpecConverter) *SpecConverter {\n\tmock := &SpecConverter{}\n\tmock.Mock.Test(t)\n\n\tt.Cleanup(func() { mock.AssertExpectations(t) })\n\n\treturn mock\n}",
"func NewTypeConverter(h PackageNameResolver, optionalEntries map[string]FieldMapperEntry) *TypeConverter {\n\treturn &TypeConverter{\n\t\tLineBuilder: LineBuilder{},\n\t\tHelper: h,\n\t\tuninitialized: make(map[string]*fieldStruct),\n\t\tconvStructMap: make(map[string]string),\n\t\toptionalEntries: optionalEntries,\n\t}\n}",
"func Create(dictName string) (*Converter, error) {\n\tvar dict map[string]string\n\tvar name = strings.ToLower(dictName)\n\tswitch name {\n\tcase \"ru\":\n\t\tdict = ruDict\n\t\tbreak\n\tcase \"dvorak\":\n\t\tdict = dvorakDict\n\t\tbreak\n\tcase \"by\":\n\t\tdict = byDict\n\t\tbreak\n\tcase \"uk\":\n\t\tdict = ukDict\n\t\tbreak\n\tcase \"de\":\n\t\tdict = deDict\n\t\tbreak\n\tcase \"es\":\n\t\tdict = esDict\n\t\tbreak\n\tcase \"fa\":\n\t\tdict = faDict\n\t\tbreak\n\tcase \"he\":\n\t\tdict = heDict\n\t\tbreak\n\tcase \"kk\":\n\t\tdict = kkDict\n\t\tbreak\n\tcase \"kr\":\n\t\tdict = krDict\n\t\tbreak\n\tdefault:\n\t\treturn nil, errors.New(\"dict not found\")\n\t}\n\n\treturn createFromDict(dict)\n}",
"func New(path string, isDevelopment bool) *Translator {\n\tbundle := i18n.NewBundle(language.English)\n\tbundle.RegisterUnmarshalFunc(\"json\", json.Unmarshal)\n\n\ttranslator := &Translator{\n\t\tpath: path,\n\t\tbundle: bundle,\n\t\tisDevelopment: isDevelopment,\n\t}\n\ttranslator.parseTranslationFiles()\n\n\treturn translator\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
phi6primeSq evaluates the 6th cyclotomic polynomial, \phi_6(x) = x^2x+1, at p^2.
|
func phi6primeSq() []byte {
one := big.NewInt(1)
p := new(big.Int).SetBytes(fpOrder[:]) // p
p2 := new(big.Int).Mul(p, p) // p^2
p4 := new(big.Int).Sub(p2, one) // p^2 - 1
p4.Mul(p4, p2) // p^4 - p^2
p4.Add(p4, one) // p^4 - p^2 + 1
return p4.Bytes()
}
|
[
"func hash6(u uint64, h uint8) uint32 {\n\treturn uint32(((u << (64 - 48)) * prime6bytes) >> ((64 - h) & 63))\n}",
"func Pow6(in *big.Float) *big.Float {\n\treturn Pow(in, 6)\n}",
"func (s *Si5351) Clk6() *IntegerOutput {\n\treturn s.integerOutput[0]\n}",
"func Run6(scanner *bufio.Scanner) string {\n\tmessage := [8]*col{&col{}, &col{}, &col{}, &col{}, &col{}, &col{}, &col{}, &col{}}\n\tecVersion := \"\"\n\tfor scanner.Scan() {\n\t\tline := scanner.Text()\n\t\tfor i, c := range line {\n\t\t\tmessage[i].Add(string(c))\n\t\t}\n\t}\n\tfor _, m := range message {\n\t\tmin := 100000\n\t\tcommon := \"\"\n\t\tfor char, count := range m.c {\n\t\t\tif count < min {\n\t\t\t\tcommon = char\n\t\t\t\tmin = count\n\t\t\t}\n\t\t}\n\t\tecVersion += common\n\t}\n\treturn fmt.Sprintf(\"%s\", ecVersion)\n}",
"func (ip IP) v6(i uint8) uint8 {\n\tif i >= 8 {\n\t\treturn uint8(ip.lo >> ((15 - i) * 8))\n\t} else {\n\t\treturn uint8(ip.hi >> ((7 - i) * 8))\n\t}\n}",
"func Root6(in *big.Float) *big.Float {\n\treturn Root(in, 6)\n}",
"func NewConcurrentServerFactory6(processorFactory ConcurrentProcessorFactory, serverTransport ServerTransport,\n\tinputTransportFactory TransportFactory, outputTransportFactory TransportFactory,\n\tinputProtocolFactory ProtocolFactory, outputProtocolFactory ProtocolFactory) *ConcurrentServer {\n\treturn NewConcurrentServerFactory(\n\t\tprocessorFactory,\n\t\tserverTransport,\n\t\tInputTransportFactory(inputTransportFactory),\n\t\tOutputTransportFactory(outputTransportFactory),\n\t\tInputProtocolFactory(inputProtocolFactory),\n\t\tOutputProtocolFactory(outputProtocolFactory),\n\t)\n}",
"func hash7(u uint64, h uint8) uint32 {\n\treturn uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & 63))\n}",
"func NewConcurrentServer6(processor ConcurrentProcessor, serverTransport ServerTransport,\n\tinputTransportFactory TransportFactory, outputTransportFactory TransportFactory,\n\tinputProtocolFactory ProtocolFactory, outputProtocolFactory ProtocolFactory) *ConcurrentServer {\n\treturn NewConcurrentServerFactory(NewConcurrentProcessorFactory(processor),\n\t\tserverTransport,\n\t\tInputTransportFactory(inputTransportFactory),\n\t\tOutputTransportFactory(outputTransportFactory),\n\t\tInputProtocolFactory(inputProtocolFactory),\n\t\tOutputProtocolFactory(outputProtocolFactory),\n\t)\n}",
"func Optimal2x6p5o(samples []float64, x float64) float64 {\n\tconst middle = 2\n\txi := int(x)\n\n\tvar s [6]float64\n\tfor i := -2; i <= 3; i++ {\n\t\tif j := xi + i; j >= 0 && j < len(samples) {\n\t\t\ts[middle+i] = samples[j]\n\t\t}\n\t}\n\n\teven1 := s[middle+1] + s[middle]\n\todd1 := s[middle+1] - s[middle]\n\teven2 := s[middle+2] + s[middle-1]\n\todd2 := s[middle+2] - s[middle-1]\n\teven3 := s[middle+3] + s[middle-2]\n\todd3 := s[middle+3] - s[middle-2]\n\tc0 := even1*0.40513396007145713 + even2*0.09251794438424393 + even3*0.00234806603570670\n\tc1 := odd1*0.28342806338906690 + odd2*0.21703277024054901 + odd3*0.01309294748731515\n\tc2 := even1*-0.191337682540351941 + even2*0.16187844487943592 + even3*0.02946017143111912\n\tc3 := odd1*-0.16471626190554542 + odd2*-0.00154547203542499 + odd3*0.03399271444851909\n\tc4 := even1*0.03845798729588149 + even2*-0.05712936104242644 + even3*0.01866750929921070\n\tc5 := odd1*0.04317950185225609 + odd2*-0.01802814255926417 + odd3*0.00152170021558204\n\n\tz := x - math.Floor(x) - 1.0/2.0\n\treturn ((((c5*z+c4)*z+c3)*z+c2)*z+c1)*z + c0\n}",
"func (app *App) finalDrift6(i int) sc.Input {\n\treturn sc.LFNoise{\n\t\tInterpolation: sc.NoiseQuadratic,\n\t\tFreq: sc.C(0.1),\n\t}.Rate(sc.KR).Mul(sc.C(float32(i) / 3))\n}",
"func hash7(u uint64, h uint8) uint32 {\n\treturn uint32(((u << (64 - 56)) * prime7bytes) >> ((64 - h) & reg8SizeMask64))\n}",
"func (h *Histogram) ChiSquare(histogram Histogram) (float64, error) {\n\tvar sum float64\n\treturn sum, nil\n}",
"func D6() int {\n\treturn D(6) //nolint\n}",
"func DoHV6(base string) (ip netip.Addr, ok bool) {\n\tpopulateOnce.Do(populate)\n\tfor _, ip := range dohIPsOfBase[base] {\n\t\tif ip.Is6() {\n\t\t\treturn ip, true\n\t\t}\n\t}\n\treturn ip, false\n}",
"func TestCV6(t *testing.T) {\n\tstatedb, _ := state.New(common.Hash{}, state.NewDatabase(ethdb.NewMemDatabase()))\n\tmsg := createValidator()\n\tstatedb.AddBalance(msg.ValidatorAddress, tenK)\n\t// Website length: 200 characters\n\tmsg.Website = \"https://www.iwfhwifbwfbcerghveugbviuscbhwiefbcusidbcifwefhgciwefherhbfiwuehfciwiuebfcuyiewfhwieufwiweifhcwefhwefhwiewwerfhuwefiuewfwwwwwfiuewhfefhshfrheterhbvihfwuoefhusioehfeuwiafhaiobcfwfhceirui.com\"\n\twebsiteLengthCtxError := ctxerror.New(\"[EnsureLength] Exceed Maximum Length\", \"have\", len(msg.Website), \"maxWebsiteLen\", staking.MaxWebsiteLength)\n\t_, err := VerifyAndCreateValidatorFromMsg(\n\t\tstatedb, postStakingEpoch, big.NewInt(0), msg,\n\t)\n\tif err == nil {\n\t\tt.Errorf(\"expected non null error\")\n\t}\n\tctxerr, ok := err.(ctxerror.CtxError)\n\tif !ok {\n\t\tt.Errorf(\"expected context aware error\")\n\t}\n\tif ctxerr.Message() != websiteLengthCtxError.Message() {\n\t\tt.Error(\"expected\", websiteLengthCtxError, \"got\", err)\n\t}\n}",
"func EulerPhi(num int) int {\n\tresult := int(1)\n\tfor prime, cnt := range FactorMap(num) {\n\t\tresult *= (prime - 1) * Pow(prime, cnt-1)\n\t}\n\treturn result\n}",
"func H6(f *gofpdf.Fpdf, text string) {\n\tf.SetFont(\"helvetica\", \"B\", 10.5)\n\tf.SetTextColor(106, 115, 125)\n\n\tf.Ln(5)\n\tf.Write(1.5, text)\n\tf.Ln(6)\n}",
"func Htanprime(z float64) float64 {\n\treturn 1 - (math.Pow((math.Exp(2*z)-1)/(math.Exp(2*z)+1), 2))\n}"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.